@octane-xplat/docs-search 0.0.0-stage → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/dist/chunks.d.ts +23 -0
- package/dist/chunks.js +67 -0
- package/dist/index.d.ts +38 -0
- package/dist/index.js +177 -0
- package/dist/inference.d.ts +9 -0
- package/dist/inference.js +40 -0
- package/dist/model.d.ts +19 -0
- package/dist/model.js +109 -0
- package/package.json +46 -5
- package/src/chunks.ts +96 -0
- package/src/index.ts +249 -0
- package/src/inference.ts +53 -0
- package/src/model.ts +163 -0
package/README.md
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Local documentation search
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[Documentation](https://octane-xplat.goddardai.org/package-docs-search).
|
|
4
|
+
|
|
5
|
+
[API reference](https://octane-xplat.goddardai.org/api-docs-search).
|
package/dist/chunks.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** One Markdown file from a caller-validated, version-bound snapshot. */
|
|
2
|
+
export interface Document {
|
|
3
|
+
path: string;
|
|
4
|
+
corpus: string;
|
|
5
|
+
content: string;
|
|
6
|
+
}
|
|
7
|
+
/** A section excerpt whose line range refers to the original Markdown file. */
|
|
8
|
+
export interface Chunk {
|
|
9
|
+
key: string;
|
|
10
|
+
path: string;
|
|
11
|
+
corpus: string;
|
|
12
|
+
title: string;
|
|
13
|
+
heading: string;
|
|
14
|
+
line: number;
|
|
15
|
+
endLine: number;
|
|
16
|
+
content: string;
|
|
17
|
+
releaseVersion?: string;
|
|
18
|
+
releaseDate?: string;
|
|
19
|
+
}
|
|
20
|
+
/** Compute a stable SHA-256 fingerprint for a chunk or inventory. */
|
|
21
|
+
export declare const hash: (text: string) => string;
|
|
22
|
+
/** Split at headings/paragraphs, preserving fenced examples and release ownership. */
|
|
23
|
+
export declare function chunkMarkdown(doc: Document): Chunk[];
|
package/dist/chunks.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
/** Compute a stable SHA-256 fingerprint for a chunk or inventory. */
|
|
3
|
+
export const hash = (text) => createHash('sha256').update(text).digest('hex');
|
|
4
|
+
/** Split at headings/paragraphs, preserving fenced examples and release ownership. */
|
|
5
|
+
export function chunkMarkdown(doc) {
|
|
6
|
+
const lines = doc.content.split('\n');
|
|
7
|
+
const chunks = [];
|
|
8
|
+
let title = doc.path;
|
|
9
|
+
let heading = '';
|
|
10
|
+
let releaseVersion;
|
|
11
|
+
let releaseDate;
|
|
12
|
+
let start = 0;
|
|
13
|
+
let fence = '';
|
|
14
|
+
let size = 0;
|
|
15
|
+
const emit = (end) => {
|
|
16
|
+
const content = lines.slice(start, end).join('\n').trim();
|
|
17
|
+
if (content) {
|
|
18
|
+
chunks.push({
|
|
19
|
+
key: hash(`${doc.path}:${start}:${content}`),
|
|
20
|
+
path: doc.path,
|
|
21
|
+
corpus: doc.corpus,
|
|
22
|
+
title,
|
|
23
|
+
heading,
|
|
24
|
+
line: start + 1,
|
|
25
|
+
endLine: end,
|
|
26
|
+
content,
|
|
27
|
+
...(releaseVersion ? { releaseVersion } : {}),
|
|
28
|
+
...(releaseDate ? { releaseDate } : {}),
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
start = end;
|
|
32
|
+
size = 0;
|
|
33
|
+
};
|
|
34
|
+
for (let i = 0; i < lines.length; i++) {
|
|
35
|
+
const line = lines[i];
|
|
36
|
+
const marker = /^\s{0,3}(`{3,}|~{3,})/.exec(line)?.[1];
|
|
37
|
+
if (marker) {
|
|
38
|
+
if (!fence) {
|
|
39
|
+
fence = marker;
|
|
40
|
+
}
|
|
41
|
+
else if (marker[0] === fence[0] && marker.length >= fence.length) {
|
|
42
|
+
fence = '';
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
else if (!fence) {
|
|
46
|
+
const h = /^(#{1,6})\s+(.+)$/.exec(line);
|
|
47
|
+
if (h) {
|
|
48
|
+
emit(i);
|
|
49
|
+
heading = h[2];
|
|
50
|
+
if (h[1].length === 1) {
|
|
51
|
+
title = heading;
|
|
52
|
+
}
|
|
53
|
+
if (doc.corpus === 'changelog' && h[1].length <= 2) {
|
|
54
|
+
const release = /(?:Octane Xplat\s+|\[v?|^v?)(\d+\.\d+\.\d+(?:-[\w.-]+)?)/.exec(heading);
|
|
55
|
+
releaseVersion = release?.[1];
|
|
56
|
+
releaseDate = /\b\d{4}-\d{2}-\d{2}\b/.exec(heading)?.[0];
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
else if (size >= 900 && line.trim() === '') {
|
|
60
|
+
emit(i + 1);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
size += line.length + 1;
|
|
64
|
+
}
|
|
65
|
+
emit(lines.length);
|
|
66
|
+
return chunks;
|
|
67
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { Chunk, Document } from './chunks.ts';
|
|
2
|
+
import type { Embedder } from './model.ts';
|
|
3
|
+
export { chunkMarkdown } from './chunks.ts';
|
|
4
|
+
export type { Chunk, Document } from './chunks.ts';
|
|
5
|
+
export { MODEL, modelId, localEmbedder } from './model.ts';
|
|
6
|
+
export type { Embedder } from './model.ts';
|
|
7
|
+
/** Prepare reusable embeddings. Downloads happen only when explicitly requested here. */
|
|
8
|
+
export declare function prepareIndex({ documents, binding, cacheDir, embedder, }: {
|
|
9
|
+
documents: Document[];
|
|
10
|
+
binding: string;
|
|
11
|
+
cacheDir: string;
|
|
12
|
+
embedder?: Embedder;
|
|
13
|
+
}): Promise<{
|
|
14
|
+
status: string;
|
|
15
|
+
snapshot: string;
|
|
16
|
+
model: string;
|
|
17
|
+
chunks: number;
|
|
18
|
+
embedded: number;
|
|
19
|
+
}>;
|
|
20
|
+
/** Search only the supplied snapshot. Hybrid retrieval never downloads model files. */
|
|
21
|
+
export declare function searchIndex({ documents, binding, cacheDir, query, limit, mode, embedder, }: {
|
|
22
|
+
documents: Document[];
|
|
23
|
+
binding: string;
|
|
24
|
+
cacheDir: string;
|
|
25
|
+
query: string;
|
|
26
|
+
limit?: number;
|
|
27
|
+
mode?: 'hybrid' | 'lexical';
|
|
28
|
+
embedder?: Embedder;
|
|
29
|
+
}): Promise<{
|
|
30
|
+
retrieval: {
|
|
31
|
+
requested: "hybrid" | "lexical";
|
|
32
|
+
used: string;
|
|
33
|
+
reason?: string | undefined;
|
|
34
|
+
snapshot: string;
|
|
35
|
+
model: string;
|
|
36
|
+
};
|
|
37
|
+
results: Chunk[];
|
|
38
|
+
}>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { mkdirSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
4
|
+
import { chunkMarkdown, hash } from './chunks.js';
|
|
5
|
+
import { localEmbedder } from './model.js';
|
|
6
|
+
export { chunkMarkdown } from './chunks.js';
|
|
7
|
+
export { MODEL, modelId, localEmbedder } from './model.js';
|
|
8
|
+
const VERSION = 'sections-v1';
|
|
9
|
+
const embeddingText = (chunk) => `${chunk.title}\n${chunk.heading}\n${chunk.content}`;
|
|
10
|
+
function database(cacheDir) {
|
|
11
|
+
mkdirSync(cacheDir, { recursive: true });
|
|
12
|
+
const db = new DatabaseSync(join(cacheDir, 'search-v1.sqlite'));
|
|
13
|
+
db.exec(`PRAGMA busy_timeout=10000;
|
|
14
|
+
CREATE TABLE IF NOT EXISTS snapshots (id TEXT PRIMARY KEY);
|
|
15
|
+
CREATE TABLE IF NOT EXISTS chunks (snapshot TEXT, key TEXT, data TEXT, PRIMARY KEY(snapshot,key));
|
|
16
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS fulltext USING fts5(snapshot UNINDEXED, key UNINDEXED, text);
|
|
17
|
+
CREATE TABLE IF NOT EXISTS embeddings (model TEXT, hash TEXT, vector TEXT, PRIMARY KEY(model,hash));`);
|
|
18
|
+
return db;
|
|
19
|
+
}
|
|
20
|
+
function inventory(documents, binding) {
|
|
21
|
+
const chunks = documents.flatMap(chunkMarkdown);
|
|
22
|
+
const snapshot = hash(`${VERSION}:${binding}:${JSON.stringify(chunks)}`);
|
|
23
|
+
return { chunks, snapshot };
|
|
24
|
+
}
|
|
25
|
+
function sync(db, snapshot, chunks) {
|
|
26
|
+
if (db.prepare('SELECT id FROM snapshots WHERE id=?').get(snapshot)) {
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
db.exec('BEGIN IMMEDIATE');
|
|
30
|
+
try {
|
|
31
|
+
// Another process may have prepared this snapshot while waiting for the lock.
|
|
32
|
+
if (!db.prepare('SELECT id FROM snapshots WHERE id=?').get(snapshot)) {
|
|
33
|
+
const row = db.prepare('INSERT INTO chunks VALUES (?,?,?)');
|
|
34
|
+
const fts = db.prepare('INSERT INTO fulltext VALUES (?,?,?)');
|
|
35
|
+
for (const chunk of chunks) {
|
|
36
|
+
row.run(snapshot, chunk.key, JSON.stringify(chunk));
|
|
37
|
+
fts.run(snapshot, chunk.key, `${chunk.path}\n${embeddingText(chunk)}`);
|
|
38
|
+
}
|
|
39
|
+
db.prepare('INSERT INTO snapshots VALUES (?)').run(snapshot);
|
|
40
|
+
}
|
|
41
|
+
db.exec('COMMIT');
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
db.exec('ROLLBACK');
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function vector(db, embedder, chunk) {
|
|
49
|
+
const row = db
|
|
50
|
+
.prepare('SELECT vector FROM embeddings WHERE model=? AND hash=?')
|
|
51
|
+
.get(embedder.id, hash(embeddingText(chunk)));
|
|
52
|
+
if (!row) {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
const values = JSON.parse(row.vector);
|
|
56
|
+
return Array.isArray(values) && values.length > 0 && values.every(Number.isFinite) ? values : null;
|
|
57
|
+
}
|
|
58
|
+
function normalize(values) {
|
|
59
|
+
if (!values.length || !values.every(Number.isFinite)) {
|
|
60
|
+
throw new Error('Invalid embedding vector');
|
|
61
|
+
}
|
|
62
|
+
const norm = Math.hypot(...values);
|
|
63
|
+
if (!norm) {
|
|
64
|
+
throw new Error('Zero embedding vector');
|
|
65
|
+
}
|
|
66
|
+
return values.map((v) => v / norm);
|
|
67
|
+
}
|
|
68
|
+
/** Prepare reusable embeddings. Downloads happen only when explicitly requested here. */
|
|
69
|
+
export async function prepareIndex({ documents, binding, cacheDir, embedder = localEmbedder(cacheDir, true), }) {
|
|
70
|
+
const { chunks, snapshot } = inventory(documents, binding);
|
|
71
|
+
const db = database(cacheDir);
|
|
72
|
+
let embedded = 0;
|
|
73
|
+
try {
|
|
74
|
+
if (chunks.length) {
|
|
75
|
+
await embedder.prepare?.();
|
|
76
|
+
}
|
|
77
|
+
sync(db, snapshot, chunks);
|
|
78
|
+
const missing = new Map(chunks.filter((c) => !vector(db, embedder, c)).map((c) => [hash(embeddingText(c)), c]));
|
|
79
|
+
// Commit batches independently: interruption preserves completed work.
|
|
80
|
+
for (let offset = 0; offset < missing.size; offset += 32) {
|
|
81
|
+
const batch = [...missing.entries()].slice(offset, offset + 32);
|
|
82
|
+
const vectors = await embedder.embed(batch.map(([, c]) => embeddingText(c)));
|
|
83
|
+
if (vectors.length !== batch.length) {
|
|
84
|
+
throw new Error('Embedding count mismatch');
|
|
85
|
+
}
|
|
86
|
+
const normalized = vectors.map(normalize);
|
|
87
|
+
db.exec('BEGIN IMMEDIATE');
|
|
88
|
+
try {
|
|
89
|
+
const insert = db.prepare('INSERT OR REPLACE INTO embeddings VALUES (?,?,?)');
|
|
90
|
+
batch.forEach(([key], i) => insert.run(embedder.id, key, JSON.stringify(normalized[i])));
|
|
91
|
+
db.exec('COMMIT');
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
db.exec('ROLLBACK');
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
embedded += batch.length;
|
|
98
|
+
}
|
|
99
|
+
return { status: 'ready', snapshot, model: embedder.id, chunks: chunks.length, embedded };
|
|
100
|
+
}
|
|
101
|
+
finally {
|
|
102
|
+
db.close();
|
|
103
|
+
await embedder.dispose?.();
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/** Search only the supplied snapshot. Hybrid retrieval never downloads model files. */
|
|
107
|
+
export async function searchIndex({ documents, binding, cacheDir, query, limit = 10, mode = 'hybrid', embedder = localEmbedder(cacheDir), }) {
|
|
108
|
+
const { chunks, snapshot } = inventory(documents, binding);
|
|
109
|
+
const db = database(cacheDir);
|
|
110
|
+
try {
|
|
111
|
+
sync(db, snapshot, chunks);
|
|
112
|
+
const terms = query.match(/[\p{L}\p{N}_]+/gu) ?? [];
|
|
113
|
+
const expression = terms.map((t) => `"${t}"`).join(' OR ');
|
|
114
|
+
const lexical = expression
|
|
115
|
+
? db
|
|
116
|
+
.prepare(`SELECT key FROM fulltext
|
|
117
|
+
WHERE fulltext MATCH ? AND snapshot=? ORDER BY bm25(fulltext) LIMIT ?`)
|
|
118
|
+
.all(expression, snapshot, Math.max(50, limit * 5))
|
|
119
|
+
.map((r) => r.key)
|
|
120
|
+
: [];
|
|
121
|
+
let used = 'lexical';
|
|
122
|
+
let reason = mode === 'hybrid' ? 'index-not-ready' : undefined;
|
|
123
|
+
const ranks = new Map();
|
|
124
|
+
lexical.forEach((key, i) => ranks.set(key, 1 / (60 + i + 1)));
|
|
125
|
+
if (mode === 'hybrid' && chunks.length) {
|
|
126
|
+
const vectors = chunks.map((c) => vector(db, embedder, c));
|
|
127
|
+
if (vectors.every((v) => v !== null)) {
|
|
128
|
+
try {
|
|
129
|
+
const [raw] = await embedder.embed([query]);
|
|
130
|
+
const q = normalize(raw);
|
|
131
|
+
const semantic = chunks
|
|
132
|
+
.map((chunk, i) => {
|
|
133
|
+
const v = vectors[i];
|
|
134
|
+
if (v.length !== q.length) {
|
|
135
|
+
throw new Error('Embedding dimensions changed');
|
|
136
|
+
}
|
|
137
|
+
return { key: chunk.key, score: v.reduce((sum, n, j) => sum + n * q[j], 0) };
|
|
138
|
+
})
|
|
139
|
+
.filter((r) => r.score >= 0.2)
|
|
140
|
+
.sort((a, b) => b.score - a.score)
|
|
141
|
+
.slice(0, Math.max(50, limit * 5));
|
|
142
|
+
semantic.forEach(({ key }, i) => ranks.set(key, (ranks.get(key) ?? 0) + 1 / (60 + i + 1)));
|
|
143
|
+
used = 'hybrid';
|
|
144
|
+
reason = undefined;
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
reason = 'model-unavailable';
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
const needle = query.trim().toLowerCase();
|
|
152
|
+
// Preserve exact identifiers/phrases even when FTS tokenization differs.
|
|
153
|
+
for (const chunk of chunks) {
|
|
154
|
+
if (needle && `${chunk.path}\n${embeddingText(chunk)}`.toLowerCase().includes(needle)) {
|
|
155
|
+
ranks.set(chunk.key, (ranks.get(chunk.key) ?? 0) + 1);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
const byKey = new Map(chunks.map((c) => [c.key, c]));
|
|
159
|
+
return {
|
|
160
|
+
retrieval: {
|
|
161
|
+
requested: mode,
|
|
162
|
+
used,
|
|
163
|
+
...(reason ? { reason } : {}),
|
|
164
|
+
snapshot,
|
|
165
|
+
model: embedder.id,
|
|
166
|
+
},
|
|
167
|
+
results: [...ranks]
|
|
168
|
+
.sort((a, b) => b[1] - a[1])
|
|
169
|
+
.slice(0, limit)
|
|
170
|
+
.map(([key]) => byKey.get(key)),
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
finally {
|
|
174
|
+
db.close();
|
|
175
|
+
await embedder.dispose?.();
|
|
176
|
+
}
|
|
177
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Tokenizer } from '@huggingface/tokenizers';
|
|
2
|
+
/** Encode one BERT sequence, retaining its final separator when truncating. */
|
|
3
|
+
export declare function encodeText(tokenizer: Tokenizer, text: string, maxTokens: number): {
|
|
4
|
+
input_ids: number[];
|
|
5
|
+
attention_mask: number[];
|
|
6
|
+
token_type_ids: number[];
|
|
7
|
+
};
|
|
8
|
+
/** Attention-mask-weighted mean pooling followed by L2 normalization. */
|
|
9
|
+
export declare function poolEmbedding(values: Float32Array, mask: readonly number[], dimensions: number): number[];
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** Encode one BERT sequence, retaining its final separator when truncating. */
|
|
2
|
+
export function encodeText(tokenizer, text, maxTokens) {
|
|
3
|
+
const encoded = tokenizer.encode(text, { return_token_type_ids: true });
|
|
4
|
+
const truncate = (values) => values.length > maxTokens
|
|
5
|
+
? [...values.slice(0, maxTokens - 1), values[values.length - 1]]
|
|
6
|
+
: values;
|
|
7
|
+
return {
|
|
8
|
+
input_ids: truncate(encoded.ids),
|
|
9
|
+
attention_mask: truncate(encoded.attention_mask),
|
|
10
|
+
token_type_ids: truncate(encoded.token_type_ids),
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
/** Attention-mask-weighted mean pooling followed by L2 normalization. */
|
|
14
|
+
export function poolEmbedding(values, mask, dimensions) {
|
|
15
|
+
if (values.length !== mask.length * dimensions) {
|
|
16
|
+
throw new Error('Embedding shape mismatch');
|
|
17
|
+
}
|
|
18
|
+
const pooled = Array(dimensions).fill(0);
|
|
19
|
+
let count = 0;
|
|
20
|
+
for (let token = 0; token < mask.length; token++) {
|
|
21
|
+
if (!mask[token]) {
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
count++;
|
|
25
|
+
for (let dim = 0; dim < dimensions; dim++) {
|
|
26
|
+
pooled[dim] += values[token * dimensions + dim];
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
if (!count) {
|
|
30
|
+
throw new Error('Embedding has no attended tokens');
|
|
31
|
+
}
|
|
32
|
+
for (let dim = 0; dim < dimensions; dim++) {
|
|
33
|
+
pooled[dim] /= count;
|
|
34
|
+
}
|
|
35
|
+
const norm = Math.hypot(...pooled);
|
|
36
|
+
if (!Number.isFinite(norm) || !norm) {
|
|
37
|
+
throw new Error('Invalid embedding output');
|
|
38
|
+
}
|
|
39
|
+
return pooled.map((value) => value / norm);
|
|
40
|
+
}
|
package/dist/model.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Model identity participates in all embedding/cache keys. */
|
|
2
|
+
export declare const MODEL: {
|
|
3
|
+
readonly name: 'Xenova/all-MiniLM-L6-v2';
|
|
4
|
+
readonly revision: '751bff37182d3f1213fa05d7196b954e230abad9';
|
|
5
|
+
readonly dtype: 'q8';
|
|
6
|
+
readonly dimensions: 384;
|
|
7
|
+
readonly maxTokens: 512;
|
|
8
|
+
};
|
|
9
|
+
/** Embedding boundary; tests can supply deterministic vectors without model downloads. */
|
|
10
|
+
export interface Embedder {
|
|
11
|
+
id: string;
|
|
12
|
+
prepare?(): Promise<void>;
|
|
13
|
+
embed(texts: string[]): Promise<number[][]>;
|
|
14
|
+
dispose?(): Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
/** Cache identity covering model files, inference settings and engine version. */
|
|
17
|
+
export declare const modelId: string;
|
|
18
|
+
/** Load CPU inference lazily; only explicit preparation permits model downloads. */
|
|
19
|
+
export declare function localEmbedder(cacheDir: string, download?: boolean): Embedder;
|
package/dist/model.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
import { encodeText, poolEmbedding } from './inference.js';
|
|
5
|
+
/** Model identity participates in all embedding/cache keys. */
|
|
6
|
+
export const MODEL = {
|
|
7
|
+
name: 'Xenova/all-MiniLM-L6-v2',
|
|
8
|
+
revision: '751bff37182d3f1213fa05d7196b954e230abad9',
|
|
9
|
+
dtype: 'q8',
|
|
10
|
+
dimensions: 384,
|
|
11
|
+
maxTokens: 512,
|
|
12
|
+
};
|
|
13
|
+
/** Cache identity covering model files, inference settings and engine version. */
|
|
14
|
+
export const modelId = `${MODEL.name}@${MODEL.revision}:${MODEL.dtype}:mean:normalized:wasm-1.31.1:tokenizers-0.2.0:single-sequence-512:v1`;
|
|
15
|
+
// Immutable model files from the pinned Hugging Face revision, including q8 weights.
|
|
16
|
+
const FILES = {
|
|
17
|
+
'config.json': '7135149f7cffa1a573466c6e4d8423ed73b62fd2332c575bf738a0d033f70df7',
|
|
18
|
+
'tokenizer.json': 'da0e79933b9ed51798a3ae27893d3c5fa4a201126cef75586296df9b4d2c62a0',
|
|
19
|
+
'tokenizer_config.json': '9261e7d79b44c8195c1cada2b453e55b00aeb81e907a6664974b4d7776172ab3',
|
|
20
|
+
'onnx/model_quantized.onnx': 'afdb6f1a0e45b715d0bb9b11772f032c399babd23bfc31fed1c170afc848bdb1',
|
|
21
|
+
};
|
|
22
|
+
const digest = (bytes) => createHash('sha256').update(bytes).digest('hex');
|
|
23
|
+
async function modelDirectory(cacheDir, download) {
|
|
24
|
+
const dir = resolve(cacheDir, 'models', MODEL.name, MODEL.revision);
|
|
25
|
+
for (const [file, sha] of Object.entries(FILES)) {
|
|
26
|
+
const path = join(dir, file);
|
|
27
|
+
if (existsSync(path) && digest(readFileSync(path)) === sha) {
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
if (!download) {
|
|
31
|
+
throw new Error('Pinned model file is absent or invalid; run docs index');
|
|
32
|
+
}
|
|
33
|
+
const response = await fetch(`https://huggingface.co/${MODEL.name}/resolve/${MODEL.revision}/${file}`, { signal: AbortSignal.timeout(120000) });
|
|
34
|
+
if (!response.ok) {
|
|
35
|
+
throw new Error(`Model download failed (${response.status})`);
|
|
36
|
+
}
|
|
37
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
38
|
+
if (digest(bytes) !== sha) {
|
|
39
|
+
throw new Error('Model file checksum mismatch');
|
|
40
|
+
}
|
|
41
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
42
|
+
const tmp = `${path}.${randomUUID()}.tmp`;
|
|
43
|
+
try {
|
|
44
|
+
writeFileSync(tmp, bytes);
|
|
45
|
+
renameSync(tmp, path);
|
|
46
|
+
}
|
|
47
|
+
finally {
|
|
48
|
+
rmSync(tmp, { force: true });
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return dir;
|
|
52
|
+
}
|
|
53
|
+
/** Load CPU inference lazily; only explicit preparation permits model downloads. */
|
|
54
|
+
export function localEmbedder(cacheDir, download = false) {
|
|
55
|
+
let loading;
|
|
56
|
+
async function load() {
|
|
57
|
+
const dir = await modelDirectory(cacheDir, download);
|
|
58
|
+
const [{ Tokenizer }, ort] = await Promise.all([
|
|
59
|
+
import('@huggingface/tokenizers'),
|
|
60
|
+
import('onnxruntime-web/wasm'),
|
|
61
|
+
]);
|
|
62
|
+
const tokenizer = new Tokenizer(JSON.parse(readFileSync(join(dir, 'tokenizer.json'), 'utf8')), JSON.parse(readFileSync(join(dir, 'tokenizer_config.json'), 'utf8')));
|
|
63
|
+
// Node's WASM execution provider supports a single thread. Runtime assets
|
|
64
|
+
// resolve from the installed package; inference never needs a CDN.
|
|
65
|
+
ort.env.wasm.numThreads = 1;
|
|
66
|
+
const session = await ort.InferenceSession.create(new Uint8Array(readFileSync(join(dir, 'onnx/model_quantized.onnx'))), { executionProviders: ['wasm'] });
|
|
67
|
+
return { tokenizer, ort, session };
|
|
68
|
+
}
|
|
69
|
+
return {
|
|
70
|
+
id: modelId,
|
|
71
|
+
async prepare() {
|
|
72
|
+
await modelDirectory(cacheDir, download);
|
|
73
|
+
},
|
|
74
|
+
async embed(texts) {
|
|
75
|
+
if (!texts.length) {
|
|
76
|
+
return [];
|
|
77
|
+
}
|
|
78
|
+
loading ?? (loading = load());
|
|
79
|
+
const { tokenizer, ort, session } = await loading;
|
|
80
|
+
const vectors = [];
|
|
81
|
+
// One sequence per run avoids padding and batch-dependent q8 outputs.
|
|
82
|
+
for (const text of texts) {
|
|
83
|
+
const encoded = encodeText(tokenizer, text, MODEL.maxTokens);
|
|
84
|
+
const inputs = Object.fromEntries(Object.entries(encoded).map(([name, values]) => [
|
|
85
|
+
name,
|
|
86
|
+
new ort.Tensor('int64', BigInt64Array.from(values.map(BigInt)), [1, values.length]),
|
|
87
|
+
]));
|
|
88
|
+
const outputs = await session.run(inputs);
|
|
89
|
+
const output = outputs.last_hidden_state;
|
|
90
|
+
if (!output ||
|
|
91
|
+
output.type !== 'float32' ||
|
|
92
|
+
output.dims.length !== 3 ||
|
|
93
|
+
output.dims[0] !== 1 ||
|
|
94
|
+
output.dims[1] !== encoded.input_ids.length ||
|
|
95
|
+
output.dims[2] !== MODEL.dimensions) {
|
|
96
|
+
throw new Error('Unexpected MiniLM embedding output');
|
|
97
|
+
}
|
|
98
|
+
vectors.push(poolEmbedding(output.data, encoded.attention_mask, MODEL.dimensions));
|
|
99
|
+
}
|
|
100
|
+
return vectors;
|
|
101
|
+
},
|
|
102
|
+
async dispose() {
|
|
103
|
+
const current = loading;
|
|
104
|
+
loading = undefined;
|
|
105
|
+
const loaded = await current?.catch(() => undefined);
|
|
106
|
+
await loaded?.session.release();
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@octane-xplat/docs-search",
|
|
3
|
+
"version": "0.20.0",
|
|
4
|
+
"description": "Local documentation retrieval engine used by the Xplat CLI and MCP server.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/octane-xplat/octane-xplat",
|
|
9
|
+
"directory": "packages/docs-search"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist",
|
|
13
|
+
"src",
|
|
14
|
+
"README.md"
|
|
15
|
+
],
|
|
16
|
+
"type": "module",
|
|
17
|
+
"exports": {
|
|
18
|
+
"./chunks": {
|
|
19
|
+
"types": "./dist/chunks.d.ts",
|
|
20
|
+
"default": "./dist/chunks.js"
|
|
21
|
+
},
|
|
22
|
+
".": {
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"default": "./dist/index.js"
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"publishConfig": {
|
|
28
|
+
"access": "public"
|
|
29
|
+
},
|
|
30
|
+
"scripts": {
|
|
31
|
+
"build": "tsc --runExternalCode -p tsconfig.build.json",
|
|
32
|
+
"typegen": "tsc --runExternalCode -p tsconfig.build.json",
|
|
33
|
+
"typecheck": "tsc --runExternalCode -p tsconfig.json",
|
|
34
|
+
"test": "node --test tests/*.test.mjs",
|
|
35
|
+
"test:model": "node tests/model-smoke.mjs && bun tests/model-smoke.mjs",
|
|
36
|
+
"prepack": "bun run build"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@huggingface/tokenizers": "0.2.0",
|
|
40
|
+
"onnxruntime-web": "1.31.1"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@types/node": "26.6.6",
|
|
44
|
+
"typescript": "7.1.0-beta",
|
|
45
|
+
"@tsrx/content-mapper": "0.1.2"
|
|
46
|
+
}
|
|
47
|
+
}
|
package/src/chunks.ts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
|
|
3
|
+
/** One Markdown file from a caller-validated, version-bound snapshot. */
|
|
4
|
+
export interface Document {
|
|
5
|
+
path: string
|
|
6
|
+
corpus: string
|
|
7
|
+
content: string
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** A section excerpt whose line range refers to the original Markdown file. */
|
|
11
|
+
export interface Chunk {
|
|
12
|
+
key: string
|
|
13
|
+
path: string
|
|
14
|
+
corpus: string
|
|
15
|
+
title: string
|
|
16
|
+
heading: string
|
|
17
|
+
line: number
|
|
18
|
+
endLine: number
|
|
19
|
+
content: string
|
|
20
|
+
releaseVersion?: string
|
|
21
|
+
releaseDate?: string
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Compute a stable SHA-256 fingerprint for a chunk or inventory. */
|
|
25
|
+
export const hash = (text: string) => createHash('sha256').update(text).digest('hex')
|
|
26
|
+
|
|
27
|
+
/** Split at headings/paragraphs, preserving fenced examples and release ownership. */
|
|
28
|
+
export function chunkMarkdown(doc: Document): Chunk[] {
|
|
29
|
+
const lines = doc.content.split('\n')
|
|
30
|
+
const chunks: Chunk[] = []
|
|
31
|
+
let title = doc.path
|
|
32
|
+
let heading = ''
|
|
33
|
+
let releaseVersion: string | undefined
|
|
34
|
+
let releaseDate: string | undefined
|
|
35
|
+
let start = 0
|
|
36
|
+
let fence = ''
|
|
37
|
+
let size = 0
|
|
38
|
+
const emit = (end: number) => {
|
|
39
|
+
const content = lines.slice(start, end).join('\n').trim()
|
|
40
|
+
|
|
41
|
+
if (content) {
|
|
42
|
+
chunks.push({
|
|
43
|
+
key: hash(`${doc.path}:${start}:${content}`),
|
|
44
|
+
path: doc.path,
|
|
45
|
+
corpus: doc.corpus,
|
|
46
|
+
title,
|
|
47
|
+
heading,
|
|
48
|
+
line: start + 1,
|
|
49
|
+
endLine: end,
|
|
50
|
+
content,
|
|
51
|
+
...(releaseVersion ? { releaseVersion } : {}),
|
|
52
|
+
...(releaseDate ? { releaseDate } : {}),
|
|
53
|
+
})
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
start = end
|
|
57
|
+
size = 0
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
for (let i = 0; i < lines.length; i++) {
|
|
61
|
+
const line = lines[i]
|
|
62
|
+
const marker = /^\s{0,3}(`{3,}|~{3,})/.exec(line)?.[1]
|
|
63
|
+
|
|
64
|
+
if (marker) {
|
|
65
|
+
if (!fence) {
|
|
66
|
+
fence = marker
|
|
67
|
+
} else if (marker[0] === fence[0] && marker.length >= fence.length) {
|
|
68
|
+
fence = ''
|
|
69
|
+
}
|
|
70
|
+
} else if (!fence) {
|
|
71
|
+
const h = /^(#{1,6})\s+(.+)$/.exec(line)
|
|
72
|
+
|
|
73
|
+
if (h) {
|
|
74
|
+
emit(i)
|
|
75
|
+
heading = h[2]
|
|
76
|
+
if (h[1].length === 1) {
|
|
77
|
+
title = heading
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (doc.corpus === 'changelog' && h[1].length <= 2) {
|
|
81
|
+
const release = /(?:Octane Xplat\s+|\[v?|^v?)(\d+\.\d+\.\d+(?:-[\w.-]+)?)/.exec(heading)
|
|
82
|
+
|
|
83
|
+
releaseVersion = release?.[1]
|
|
84
|
+
releaseDate = /\b\d{4}-\d{2}-\d{2}\b/.exec(heading)?.[0]
|
|
85
|
+
}
|
|
86
|
+
} else if (size >= 900 && line.trim() === '') {
|
|
87
|
+
emit(i + 1)
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
size += line.length + 1
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
emit(lines.length)
|
|
95
|
+
return chunks
|
|
96
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import { mkdirSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { DatabaseSync } from 'node:sqlite'
|
|
4
|
+
import { chunkMarkdown, hash } from './chunks.ts'
|
|
5
|
+
import type { Chunk, Document } from './chunks.ts'
|
|
6
|
+
import { localEmbedder } from './model.ts'
|
|
7
|
+
import type { Embedder } from './model.ts'
|
|
8
|
+
|
|
9
|
+
export { chunkMarkdown } from './chunks.ts'
|
|
10
|
+
export type { Chunk, Document } from './chunks.ts'
|
|
11
|
+
export { MODEL, modelId, localEmbedder } from './model.ts'
|
|
12
|
+
export type { Embedder } from './model.ts'
|
|
13
|
+
|
|
14
|
+
const VERSION = 'sections-v1'
|
|
15
|
+
const embeddingText = (chunk: Chunk) => `${chunk.title}\n${chunk.heading}\n${chunk.content}`
|
|
16
|
+
|
|
17
|
+
function database(cacheDir: string) {
|
|
18
|
+
mkdirSync(cacheDir, { recursive: true })
|
|
19
|
+
|
|
20
|
+
const db = new DatabaseSync(join(cacheDir, 'search-v1.sqlite'))
|
|
21
|
+
|
|
22
|
+
db.exec(`PRAGMA busy_timeout=10000;
|
|
23
|
+
CREATE TABLE IF NOT EXISTS snapshots (id TEXT PRIMARY KEY);
|
|
24
|
+
CREATE TABLE IF NOT EXISTS chunks (snapshot TEXT, key TEXT, data TEXT, PRIMARY KEY(snapshot,key));
|
|
25
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS fulltext USING fts5(snapshot UNINDEXED, key UNINDEXED, text);
|
|
26
|
+
CREATE TABLE IF NOT EXISTS embeddings (model TEXT, hash TEXT, vector TEXT, PRIMARY KEY(model,hash));`)
|
|
27
|
+
|
|
28
|
+
return db
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function inventory(documents: Document[], binding: string) {
|
|
32
|
+
const chunks = documents.flatMap(chunkMarkdown)
|
|
33
|
+
const snapshot = hash(`${VERSION}:${binding}:${JSON.stringify(chunks)}`)
|
|
34
|
+
|
|
35
|
+
return { chunks, snapshot }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function sync(db: DatabaseSync, snapshot: string, chunks: Chunk[]) {
|
|
39
|
+
if (db.prepare('SELECT id FROM snapshots WHERE id=?').get(snapshot)) {
|
|
40
|
+
return
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
db.exec('BEGIN IMMEDIATE')
|
|
44
|
+
try {
|
|
45
|
+
// Another process may have prepared this snapshot while waiting for the lock.
|
|
46
|
+
if (!db.prepare('SELECT id FROM snapshots WHERE id=?').get(snapshot)) {
|
|
47
|
+
const row = db.prepare('INSERT INTO chunks VALUES (?,?,?)')
|
|
48
|
+
const fts = db.prepare('INSERT INTO fulltext VALUES (?,?,?)')
|
|
49
|
+
|
|
50
|
+
for (const chunk of chunks) {
|
|
51
|
+
row.run(snapshot, chunk.key, JSON.stringify(chunk))
|
|
52
|
+
fts.run(snapshot, chunk.key, `${chunk.path}\n${embeddingText(chunk)}`)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
db.prepare('INSERT INTO snapshots VALUES (?)').run(snapshot)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
db.exec('COMMIT')
|
|
59
|
+
} catch (error) {
|
|
60
|
+
db.exec('ROLLBACK')
|
|
61
|
+
throw error
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function vector(db: DatabaseSync, embedder: Embedder, chunk: Chunk): number[] | null {
|
|
66
|
+
const row = db
|
|
67
|
+
.prepare('SELECT vector FROM embeddings WHERE model=? AND hash=?')
|
|
68
|
+
.get(embedder.id, hash(embeddingText(chunk)))
|
|
69
|
+
|
|
70
|
+
if (!row) {
|
|
71
|
+
return null
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const values: unknown = JSON.parse(row.vector as string)
|
|
75
|
+
|
|
76
|
+
return Array.isArray(values) && values.length > 0 && values.every(Number.isFinite) ? values : null
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function normalize(values: number[]) {
|
|
80
|
+
if (!values.length || !values.every(Number.isFinite)) {
|
|
81
|
+
throw new Error('Invalid embedding vector')
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const norm = Math.hypot(...values)
|
|
85
|
+
|
|
86
|
+
if (!norm) {
|
|
87
|
+
throw new Error('Zero embedding vector')
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return values.map((v) => v / norm)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Prepare reusable embeddings. Downloads happen only when explicitly requested here. */
|
|
94
|
+
export async function prepareIndex({
|
|
95
|
+
documents,
|
|
96
|
+
binding,
|
|
97
|
+
cacheDir,
|
|
98
|
+
embedder = localEmbedder(cacheDir, true),
|
|
99
|
+
}: {
|
|
100
|
+
documents: Document[]
|
|
101
|
+
binding: string
|
|
102
|
+
cacheDir: string
|
|
103
|
+
embedder?: Embedder
|
|
104
|
+
}) {
|
|
105
|
+
const { chunks, snapshot } = inventory(documents, binding)
|
|
106
|
+
const db = database(cacheDir)
|
|
107
|
+
let embedded = 0
|
|
108
|
+
|
|
109
|
+
try {
|
|
110
|
+
if (chunks.length) {
|
|
111
|
+
await embedder.prepare?.()
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
sync(db, snapshot, chunks)
|
|
115
|
+
|
|
116
|
+
const missing = new Map(
|
|
117
|
+
chunks.filter((c) => !vector(db, embedder, c)).map((c) => [hash(embeddingText(c)), c]),
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
// Commit batches independently: interruption preserves completed work.
|
|
121
|
+
for (let offset = 0; offset < missing.size; offset += 32) {
|
|
122
|
+
const batch = [...missing.entries()].slice(offset, offset + 32)
|
|
123
|
+
const vectors = await embedder.embed(batch.map(([, c]) => embeddingText(c)))
|
|
124
|
+
|
|
125
|
+
if (vectors.length !== batch.length) {
|
|
126
|
+
throw new Error('Embedding count mismatch')
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const normalized = vectors.map(normalize)
|
|
130
|
+
|
|
131
|
+
db.exec('BEGIN IMMEDIATE')
|
|
132
|
+
try {
|
|
133
|
+
const insert = db.prepare('INSERT OR REPLACE INTO embeddings VALUES (?,?,?)')
|
|
134
|
+
|
|
135
|
+
batch.forEach(([key], i) => insert.run(embedder.id, key, JSON.stringify(normalized[i])))
|
|
136
|
+
db.exec('COMMIT')
|
|
137
|
+
} catch (error) {
|
|
138
|
+
db.exec('ROLLBACK')
|
|
139
|
+
throw error
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
embedded += batch.length
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return { status: 'ready', snapshot, model: embedder.id, chunks: chunks.length, embedded }
|
|
146
|
+
} finally {
|
|
147
|
+
db.close()
|
|
148
|
+
await embedder.dispose?.()
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Search only the supplied snapshot. Hybrid retrieval never downloads model files. */
|
|
153
|
+
export async function searchIndex({
|
|
154
|
+
documents,
|
|
155
|
+
binding,
|
|
156
|
+
cacheDir,
|
|
157
|
+
query,
|
|
158
|
+
limit = 10,
|
|
159
|
+
mode = 'hybrid',
|
|
160
|
+
embedder = localEmbedder(cacheDir),
|
|
161
|
+
}: {
|
|
162
|
+
documents: Document[]
|
|
163
|
+
binding: string
|
|
164
|
+
cacheDir: string
|
|
165
|
+
query: string
|
|
166
|
+
limit?: number
|
|
167
|
+
mode?: 'hybrid' | 'lexical'
|
|
168
|
+
embedder?: Embedder
|
|
169
|
+
}) {
|
|
170
|
+
const { chunks, snapshot } = inventory(documents, binding)
|
|
171
|
+
const db = database(cacheDir)
|
|
172
|
+
|
|
173
|
+
try {
|
|
174
|
+
sync(db, snapshot, chunks)
|
|
175
|
+
|
|
176
|
+
const terms = query.match(/[\p{L}\p{N}_]+/gu) ?? []
|
|
177
|
+
const expression = terms.map((t) => `"${t}"`).join(' OR ')
|
|
178
|
+
const lexical = expression
|
|
179
|
+
? db
|
|
180
|
+
.prepare(`SELECT key FROM fulltext
|
|
181
|
+
WHERE fulltext MATCH ? AND snapshot=? ORDER BY bm25(fulltext) LIMIT ?`)
|
|
182
|
+
.all(expression, snapshot, Math.max(50, limit * 5))
|
|
183
|
+
.map((r) => r.key as string)
|
|
184
|
+
: []
|
|
185
|
+
|
|
186
|
+
let used = 'lexical'
|
|
187
|
+
let reason: string | undefined = mode === 'hybrid' ? 'index-not-ready' : undefined
|
|
188
|
+
const ranks = new Map<string, number>()
|
|
189
|
+
|
|
190
|
+
lexical.forEach((key, i) => ranks.set(key, 1 / (60 + i + 1)))
|
|
191
|
+
if (mode === 'hybrid' && chunks.length) {
|
|
192
|
+
const vectors = chunks.map((c) => vector(db, embedder, c))
|
|
193
|
+
|
|
194
|
+
if (vectors.every((v) => v !== null)) {
|
|
195
|
+
try {
|
|
196
|
+
const [raw] = await embedder.embed([query])
|
|
197
|
+
const q = normalize(raw)
|
|
198
|
+
const semantic = chunks
|
|
199
|
+
.map((chunk, i) => {
|
|
200
|
+
const v = vectors[i]!
|
|
201
|
+
|
|
202
|
+
if (v.length !== q.length) {
|
|
203
|
+
throw new Error('Embedding dimensions changed')
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
return { key: chunk.key, score: v.reduce((sum, n, j) => sum + n * q[j], 0) }
|
|
207
|
+
})
|
|
208
|
+
.filter((r) => r.score >= 0.2)
|
|
209
|
+
.sort((a, b) => b.score - a.score)
|
|
210
|
+
.slice(0, Math.max(50, limit * 5))
|
|
211
|
+
|
|
212
|
+
semantic.forEach(({ key }, i) => ranks.set(key, (ranks.get(key) ?? 0) + 1 / (60 + i + 1)))
|
|
213
|
+
used = 'hybrid'
|
|
214
|
+
reason = undefined
|
|
215
|
+
} catch {
|
|
216
|
+
reason = 'model-unavailable'
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const needle = query.trim().toLowerCase()
|
|
222
|
+
|
|
223
|
+
// Preserve exact identifiers/phrases even when FTS tokenization differs.
|
|
224
|
+
for (const chunk of chunks) {
|
|
225
|
+
if (needle && `${chunk.path}\n${embeddingText(chunk)}`.toLowerCase().includes(needle)) {
|
|
226
|
+
ranks.set(chunk.key, (ranks.get(chunk.key) ?? 0) + 1)
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const byKey = new Map(chunks.map((c) => [c.key, c]))
|
|
231
|
+
|
|
232
|
+
return {
|
|
233
|
+
retrieval: {
|
|
234
|
+
requested: mode,
|
|
235
|
+
used,
|
|
236
|
+
...(reason ? { reason } : {}),
|
|
237
|
+
snapshot,
|
|
238
|
+
model: embedder.id,
|
|
239
|
+
},
|
|
240
|
+
results: [...ranks]
|
|
241
|
+
.sort((a, b) => b[1] - a[1])
|
|
242
|
+
.slice(0, limit)
|
|
243
|
+
.map(([key]) => byKey.get(key)!),
|
|
244
|
+
}
|
|
245
|
+
} finally {
|
|
246
|
+
db.close()
|
|
247
|
+
await embedder.dispose?.()
|
|
248
|
+
}
|
|
249
|
+
}
|
package/src/inference.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { Tokenizer } from '@huggingface/tokenizers'
|
|
2
|
+
|
|
3
|
+
/** Encode one BERT sequence, retaining its final separator when truncating. */
|
|
4
|
+
export function encodeText(tokenizer: Tokenizer, text: string, maxTokens: number) {
|
|
5
|
+
const encoded = tokenizer.encode(text, { return_token_type_ids: true })
|
|
6
|
+
const truncate = (values: number[]) =>
|
|
7
|
+
values.length > maxTokens
|
|
8
|
+
? [...values.slice(0, maxTokens - 1), values[values.length - 1]]
|
|
9
|
+
: values
|
|
10
|
+
|
|
11
|
+
return {
|
|
12
|
+
input_ids: truncate(encoded.ids),
|
|
13
|
+
attention_mask: truncate(encoded.attention_mask),
|
|
14
|
+
token_type_ids: truncate(encoded.token_type_ids),
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Attention-mask-weighted mean pooling followed by L2 normalization. */
|
|
19
|
+
export function poolEmbedding(values: Float32Array, mask: readonly number[], dimensions: number) {
|
|
20
|
+
if (values.length !== mask.length * dimensions) {
|
|
21
|
+
throw new Error('Embedding shape mismatch')
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const pooled = Array<number>(dimensions).fill(0)
|
|
25
|
+
let count = 0
|
|
26
|
+
|
|
27
|
+
for (let token = 0; token < mask.length; token++) {
|
|
28
|
+
if (!mask[token]) {
|
|
29
|
+
continue
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
count++
|
|
33
|
+
for (let dim = 0; dim < dimensions; dim++) {
|
|
34
|
+
pooled[dim] += values[token * dimensions + dim]
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (!count) {
|
|
39
|
+
throw new Error('Embedding has no attended tokens')
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
for (let dim = 0; dim < dimensions; dim++) {
|
|
43
|
+
pooled[dim] /= count
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const norm = Math.hypot(...pooled)
|
|
47
|
+
|
|
48
|
+
if (!Number.isFinite(norm) || !norm) {
|
|
49
|
+
throw new Error('Invalid embedding output')
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return pooled.map((value) => value / norm)
|
|
53
|
+
}
|
package/src/model.ts
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { dirname, join, resolve } from 'node:path'
|
|
4
|
+
import { encodeText, poolEmbedding } from './inference.ts'
|
|
5
|
+
|
|
6
|
+
/** Model identity participates in all embedding/cache keys. */
|
|
7
|
+
export const MODEL = {
|
|
8
|
+
name: 'Xenova/all-MiniLM-L6-v2',
|
|
9
|
+
revision: '751bff37182d3f1213fa05d7196b954e230abad9',
|
|
10
|
+
dtype: 'q8',
|
|
11
|
+
dimensions: 384,
|
|
12
|
+
maxTokens: 512,
|
|
13
|
+
} as const
|
|
14
|
+
|
|
15
|
+
/** Embedding boundary; tests can supply deterministic vectors without model downloads. */
|
|
16
|
+
export interface Embedder {
|
|
17
|
+
id: string
|
|
18
|
+
prepare?(): Promise<void>
|
|
19
|
+
embed(texts: string[]): Promise<number[][]>
|
|
20
|
+
dispose?(): Promise<void>
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Cache identity covering model files, inference settings and engine version. */
|
|
24
|
+
export const modelId = `${MODEL.name}@${MODEL.revision}:${MODEL.dtype}:mean:normalized:wasm-1.31.1:tokenizers-0.2.0:single-sequence-512:v1`
|
|
25
|
+
|
|
26
|
+
// Immutable model files from the pinned Hugging Face revision, including q8 weights.
|
|
27
|
+
const FILES = {
|
|
28
|
+
'config.json': '7135149f7cffa1a573466c6e4d8423ed73b62fd2332c575bf738a0d033f70df7',
|
|
29
|
+
'tokenizer.json': 'da0e79933b9ed51798a3ae27893d3c5fa4a201126cef75586296df9b4d2c62a0',
|
|
30
|
+
'tokenizer_config.json': '9261e7d79b44c8195c1cada2b453e55b00aeb81e907a6664974b4d7776172ab3',
|
|
31
|
+
'onnx/model_quantized.onnx': 'afdb6f1a0e45b715d0bb9b11772f032c399babd23bfc31fed1c170afc848bdb1',
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const digest = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex')
|
|
35
|
+
|
|
36
|
+
async function modelDirectory(cacheDir: string, download: boolean) {
|
|
37
|
+
const dir = resolve(cacheDir, 'models', MODEL.name, MODEL.revision)
|
|
38
|
+
|
|
39
|
+
for (const [file, sha] of Object.entries(FILES)) {
|
|
40
|
+
const path = join(dir, file)
|
|
41
|
+
|
|
42
|
+
if (existsSync(path) && digest(readFileSync(path)) === sha) {
|
|
43
|
+
continue
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (!download) {
|
|
47
|
+
throw new Error('Pinned model file is absent or invalid; run docs index')
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const response = await fetch(
|
|
51
|
+
`https://huggingface.co/${MODEL.name}/resolve/${MODEL.revision}/${file}`,
|
|
52
|
+
{ signal: AbortSignal.timeout(120_000) },
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
if (!response.ok) {
|
|
56
|
+
throw new Error(`Model download failed (${response.status})`)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const bytes = new Uint8Array(await response.arrayBuffer())
|
|
60
|
+
|
|
61
|
+
if (digest(bytes) !== sha) {
|
|
62
|
+
throw new Error('Model file checksum mismatch')
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
66
|
+
|
|
67
|
+
const tmp = `${path}.${randomUUID()}.tmp`
|
|
68
|
+
|
|
69
|
+
try {
|
|
70
|
+
writeFileSync(tmp, bytes)
|
|
71
|
+
renameSync(tmp, path)
|
|
72
|
+
} finally {
|
|
73
|
+
rmSync(tmp, { force: true })
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return dir
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Load CPU inference lazily; only explicit preparation permits model downloads. */
|
|
81
|
+
export function localEmbedder(cacheDir: string, download = false): Embedder {
|
|
82
|
+
let loading: ReturnType<typeof load> | undefined
|
|
83
|
+
async function load() {
|
|
84
|
+
const dir = await modelDirectory(cacheDir, download)
|
|
85
|
+
const [{ Tokenizer }, ort] = await Promise.all([
|
|
86
|
+
import('@huggingface/tokenizers'),
|
|
87
|
+
import('onnxruntime-web/wasm'),
|
|
88
|
+
])
|
|
89
|
+
|
|
90
|
+
const tokenizer = new Tokenizer(
|
|
91
|
+
JSON.parse(readFileSync(join(dir, 'tokenizer.json'), 'utf8')),
|
|
92
|
+
JSON.parse(readFileSync(join(dir, 'tokenizer_config.json'), 'utf8')),
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
// Node's WASM execution provider supports a single thread. Runtime assets
|
|
96
|
+
// resolve from the installed package; inference never needs a CDN.
|
|
97
|
+
ort.env.wasm.numThreads = 1
|
|
98
|
+
|
|
99
|
+
const session = await ort.InferenceSession.create(
|
|
100
|
+
new Uint8Array(readFileSync(join(dir, 'onnx/model_quantized.onnx'))),
|
|
101
|
+
{ executionProviders: ['wasm'] },
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
return { tokenizer, ort, session }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return {
|
|
108
|
+
id: modelId,
|
|
109
|
+
async prepare() {
|
|
110
|
+
await modelDirectory(cacheDir, download)
|
|
111
|
+
},
|
|
112
|
+
async embed(texts) {
|
|
113
|
+
if (!texts.length) {
|
|
114
|
+
return []
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
loading ??= load()
|
|
118
|
+
|
|
119
|
+
const { tokenizer, ort, session } = await loading
|
|
120
|
+
const vectors: number[][] = []
|
|
121
|
+
|
|
122
|
+
// One sequence per run avoids padding and batch-dependent q8 outputs.
|
|
123
|
+
for (const text of texts) {
|
|
124
|
+
const encoded = encodeText(tokenizer, text, MODEL.maxTokens)
|
|
125
|
+
const inputs = Object.fromEntries(
|
|
126
|
+
Object.entries(encoded).map(([name, values]) => [
|
|
127
|
+
name,
|
|
128
|
+
new ort.Tensor('int64', BigInt64Array.from(values.map(BigInt)), [1, values.length]),
|
|
129
|
+
]),
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
const outputs = await session.run(inputs)
|
|
133
|
+
const output = outputs.last_hidden_state
|
|
134
|
+
|
|
135
|
+
if (
|
|
136
|
+
!output ||
|
|
137
|
+
output.type !== 'float32' ||
|
|
138
|
+
output.dims.length !== 3 ||
|
|
139
|
+
output.dims[0] !== 1 ||
|
|
140
|
+
output.dims[1] !== encoded.input_ids.length ||
|
|
141
|
+
output.dims[2] !== MODEL.dimensions
|
|
142
|
+
) {
|
|
143
|
+
throw new Error('Unexpected MiniLM embedding output')
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
vectors.push(
|
|
147
|
+
poolEmbedding(output.data as Float32Array, encoded.attention_mask, MODEL.dimensions),
|
|
148
|
+
)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
return vectors
|
|
152
|
+
},
|
|
153
|
+
async dispose() {
|
|
154
|
+
const current = loading
|
|
155
|
+
|
|
156
|
+
loading = undefined
|
|
157
|
+
|
|
158
|
+
const loaded = await current?.catch(() => undefined)
|
|
159
|
+
|
|
160
|
+
await loaded?.session.release()
|
|
161
|
+
},
|
|
162
|
+
}
|
|
163
|
+
}
|