kci-vec 0.2.30 → 0.2.32

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/AI_GUIDE.md ADDED
@@ -0,0 +1,281 @@
1
+ # kci-vec: guide for AI coding assistants
2
+
3
+ You are adding search to someone's program with kci-vec. This page is the whole of what you need for the common
4
+ cases: pick one row of the table, copy its recipe, change the data. The recipes marked python and js are run by
5
+ the project's tests as they stand (B, D, E, F, G, H); A and C need files or a language model and are not.
6
+ Print this page any time with `kci-vec guide` (Python) or read `node_modules/kci-vec/AI_GUIDE.md` (Node.js).
7
+
8
+ kci-vec is a search index that lives inside the program: no server, no account, nothing leaves the machine. An index
9
+ can be saved encrypted. With nothing else given, a search by vectors or by meaning compares the question with every
10
+ item (the exact answer, nothing is missed); a search by words answers the items that share a word with the question.
11
+
12
+ ## 1. Pick the case
13
+
14
+ | The user has | Language | Use | Recipe |
15
+ |---|---|---|---|
16
+ | a folder of documents, wants no code | - | the command `kci-vec` | A |
17
+ | texts, wants to find them by their words | Python | `TextIndex(..., mode="sparse", sparse="bm25")` | B |
18
+ | texts, wants to find them by meaning | Python | `TextIndex("ja")` or `TextIndex("en")` | C |
19
+ | texts, wants to find them by meaning | Node.js | `TextIndex` | G |
20
+ | texts, and an embedding function or service of their own | Node.js | `new TextIndex({ embed })` | G |
21
+ | vectors already made, with ids, texts, fields | Python | `TextIndex(mode="dense", dense="vectors")` | D |
22
+ | vectors already made, with ids, texts, fields | Node.js | `Store` | F |
23
+ | vectors only, whole-number ids, fine control | Python / Node.js | `KciVec` | E / H |
24
+
25
+ Install: `pip install kci-vec` (Windows x64, Linux x64, macOS: no compiler needed) or `npm install kci-vec`
26
+ (Windows x64, Linux x64, macOS on Apple silicon: no compiler needed; elsewhere it builds with gcc / cc).
27
+
28
+ ## 2. Recipes
29
+
30
+ ### A. A folder of documents, from the command line
31
+
32
+ ```
33
+ pip install kci-vec pypdf
34
+ kci-vec add my_index path/to/folder # reads .txt .md .csv .docx .pptx .xlsx .pdf; run again after files change
35
+ kci-vec search my_index "the question" -k 5
36
+ kci-vec search my_index "the question" --json # for a program: one JSON document on standard output
37
+ kci-vec info my_index --files
38
+ ```
39
+
40
+ Files are found by their words as written. `--ask-key` (or the environment variable `KCI_VEC_KEY`) encrypts the index.
41
+
42
+ ### B. Python: texts, found by their words (no model, nothing downloaded)
43
+
44
+ ```python
45
+ from kci_vec.text import TextIndex
46
+
47
+ ix = TextIndex("en", mode="sparse", sparse="bm25") # "ja" for Japanese texts (no extra package needed)
48
+ ix.add(["Paid leave: 10 days are granted after six months of service.",
49
+ "Expense reports close at the end of the month."],
50
+ ids=["leave", "expense"],
51
+ fields=[{"year": 2025}, {"year": 2024}])
52
+ hits = ix.search("paid leave days", k=5) # [Hit(id, score, text, fields, ...)], best first
53
+ assert hits[0].id == "leave" and hits[0].fields == {"year": 2025}
54
+ hits = ix.search("reports", k=5, where={"year": {"$lte": 2024}})
55
+ assert [h.id for h in hits] == ["expense"]
56
+
57
+ text, fields = ix.get("leave") # one record by its id (KeyError when there is none)
58
+ ix.add(["Paid leave: 12 days are granted after six months."], ids=["leave"], fields=[fields], replace=True)
59
+ assert ix.search("12 days", k=1, where={"year": 2025})[0].id == "leave"
60
+ recent = [i for i in ix.ids() if ix.get(i)[1].get("year", 0) >= 2025] # by the fields alone, without a question
61
+ assert recent == ["leave"]
62
+ ix.set_fields("leave", {"year": 2026, "kind": "hr"}) # the fields alone; the new dict takes the place of all of them
63
+ assert ix.get("leave")[1] == {"year": 2026, "kind": "hr"}
64
+
65
+ ix.save("words_index", key="a passphrase") # a folder (saving into it again overwrites); key=None: not encrypted
66
+ ix = TextIndex.load("words_index", key="a passphrase") # RuntimeError: wrong passphrase, or the files were changed
67
+ assert len(ix) == 2
68
+ ix.delete("expense") # True when it was there
69
+ assert len(ix) == 1
70
+ ```
71
+
72
+ - Found by words: a record that has none of the question's words is not answered. Fewer than k hits, or none, is
73
+ normal; k may be larger than the number of records.
74
+ - `replace=True` puts a whole new record in the place of the old one: give `fields=` again, or the record loses
75
+ its fields. `ix.set_fields(id, {...})` changes the fields alone: the dict you give takes the place of all the
76
+ fields (read them with `get` first to keep the others); `KeyError` when no record has the id.
77
+ - There is no search without a question: to list records by their fields, use `ids()` and `get()` as above.
78
+ - After `load` you may change the index and `save` into the same folder again. Give `key=` at every save: a save
79
+ without it writes the folder unencrypted.
80
+ - `load` of a folder that is not there, or is not an index, raises `RuntimeError` too: check that the folder exists
81
+ when "not made yet" must be told from a wrong passphrase. `delete` of an id that is not there returns False.
82
+ - `add(..., replace=True)`, `delete(id)`, `get(id)`, `ids()`, `where=`, `save`, `load` are the same in B, C and D.
83
+
84
+ ### C. Python: texts, found by meaning (a language model; the first run downloads it)
85
+
86
+ ```
87
+ pip install kci-vec torch transformers # Japanese texts also need: fugashi unidic-lite
88
+ ```
89
+
90
+ ```py
91
+ from kci_vec.text import TextIndex
92
+
93
+ ix = TextIndex("en") # "ja" for Japanese. Meaning and words together (hybrid)
94
+ ix.add(["Paid leave: 10 days are granted after six months of service."], ids=["leave"])
95
+ hits = ix.search("how many vacation days do I get?", k=5)
96
+ ```
97
+
98
+ Everything else is as in B.
99
+
100
+ ### D. Python: your own vectors, with string ids, texts and fields
101
+
102
+ ```python
103
+ import numpy as np
104
+ from kci_vec.text import TextIndex
105
+
106
+ vecs = np.random.default_rng(0).standard_normal((3, 384)).astype(np.float32) # stand-ins for your embeddings
107
+ ix = TextIndex(mode="dense", dense="vectors") # metric="l2" or "ip" when the length of a vector matters
108
+ ix.add(["red apples", "green tea", "black coffee"], ids=["a", "b", "c"], vectors=vecs,
109
+ fields=[{"kind": "fruit"}, {"kind": "drink"}, {"kind": "drink"}])
110
+ hits = ix.search(vector=vecs[1], k=2, where={"kind": "drink"})
111
+ assert hits[0].id == "b"
112
+ ix.add(["green tea, a new text"], ids=["b"], vectors=vecs[1:2], fields=[{"kind": "drink"}], replace=True)
113
+ ix.delete("c")
114
+ ix.save("vectors_index", key="a passphrase")
115
+ ix = TextIndex.load("vectors_index", key="a passphrase")
116
+ assert len(ix) == 2 and ix.get("b") == ("green tea, a new text", {"kind": "drink"})
117
+ ```
118
+
119
+ ### E. Python: vectors only (`KciVec`), whole-number ids
120
+
121
+ ```python
122
+ import numpy as np
123
+ from kci_vec import KciVec
124
+
125
+ emb = np.random.default_rng(0).standard_normal((2000, 64)).astype(np.float32)
126
+ v = KciVec(dim=64) # cosine; metric="l2" or "ip" for the others
127
+ v.add_many(np.arange(2000), emb) # ids: whole numbers
128
+ v.build() # needed before the first search
129
+ hits = v.search(emb[7], k=10) # [(id, score), ...], best first
130
+ assert hits[0][0] == 7
131
+ hits = v.search(emb[7], k=10, filter={3, 7, 42}) # only these ids may be answered
132
+ v.insert(5000, emb[0]); v.delete(5000) # change a built index
133
+ v.save("index.kv", key="a long secret")
134
+ w = KciVec.load("index.kv", key="a long secret", rerank=200)
135
+ assert w.search(emb[7], k=1)[0][0] == 7
136
+ ```
137
+
138
+ ### F. Node.js: your own vectors, with string ids, texts and fields (`Store`)
139
+
140
+ ```js
141
+ const { Store } = require('kci-vec');
142
+
143
+ const s = new Store(); // { metric: 'l2' } or 'ip' when the length of a vector matters
144
+ s.add([{ id: 'manual-12', vector: [0.1, 0.9, 0.2], text: 'How to reset the password', fields: { year: 2024, tags: ['howto', 'it'] } },
145
+ { id: 'memo-3', vector: [0.8, 0.1, 0.3], text: 'Expense reports close at month end', fields: { year: 2025 } }]);
146
+ let hits = s.search([0.2, 0.8, 0.1], 5); // [{ id, score, text, fields }], best first
147
+ console.assert(hits[0].id === 'manual-12');
148
+ hits = s.search([0.2, 0.8, 0.1], 5, { where: { year: { $gte: 2025 } } });
149
+ console.assert(hits.length === 1 && hits[0].id === 'memo-3');
150
+ hits = s.search([0.2, 0.8, 0.1], 5, { where: { year: { $lte: 2024 }, tags: 'howto' } }); // both must hold; tags is a list
151
+ console.assert(hits.length === 1 && hits[0].id === 'manual-12');
152
+ const old = s.get('memo-3'); // { text, fields } of one record, or null
153
+ s.add([{ id: 'memo-3', vector: [0.7, 0.2, 0.3], text: 'a new text', fields: old.fields }], { replace: true });
154
+ s.delete('manual-12'); // true when it was there
155
+ s.save('store_folder', 'a passphrase'); // without the key nothing in the folder is readable
156
+ const again = Store.load('store_folder', 'a passphrase'); // throws: wrong passphrase, or the files were changed
157
+ console.assert(again.size === 1 && again.get('memo-3').fields.year === 2025);
158
+ ```
159
+
160
+ - `Store` needs no `build()`, and none of its calls is async. `ids()` lists the ids.
161
+ - A replace puts a whole new record in the place of the old one: give the vector, the text and the fields again, or
162
+ the record loses them. There is no call that changes the fields alone: `get` the record and `add` it again.
163
+ - `get` gives the text and the fields, not the vector: keep your vectors, or take them from your own data, when you
164
+ replace a record or look for items like one that is in the index (search with its vector for k + 1 and drop its
165
+ own id: it comes first).
166
+ - `new Store({ metric: 'l2' })`: the metric is kept in the saved folder, `Store.load` takes no option for it.
167
+ - Saving into the same folder again overwrites it. Give the passphrase at every save.
168
+
169
+ ### G. Node.js: texts, found by meaning (`TextIndex`)
170
+
171
+ ```
172
+ npm install kci-vec @huggingface/transformers # the second package runs the language model on this machine
173
+ ```
174
+
175
+ ```js
176
+ const { TextIndex } = require('kci-vec');
177
+
178
+ async function main(embed) {
179
+ const ix = new TextIndex(embed ? { embed } : {}); // nothing given: a multilingual model, downloaded at the first use
180
+ await ix.add(['Paid leave: 10 days are granted after six months of service.',
181
+ 'Expense reports close at the end of the month.'],
182
+ { ids: ['leave', 'expense'], fields: [{ year: 2025 }, { year: 2024 }] });
183
+ let hits = await ix.search('paid leave days', 3); // [{ id, score, text, span, fields }], best first
184
+ console.assert(hits[0].id === 'leave');
185
+ hits = await ix.search('paid leave days', 3, { where: { year: { $lte: 2024 } } });
186
+ console.assert(hits.length === 1 && hits[0].id === 'expense');
187
+ const old = ix.get('leave'); // { text, fields } of one record, or null
188
+ await ix.add(['Paid leave: 12 days are granted after six months.'], { ids: ['leave'], fields: [old.fields], replace: true });
189
+ console.assert(ix.get('leave').fields.year === 2025 && ix.size === 2);
190
+ ix.save('text_folder', 'a passphrase'); // not async
191
+ const again = TextIndex.load('text_folder', 'a passphrase', embed ? { embed } : {});
192
+ console.assert(again.size === 2);
193
+ again.delete('expense'); // true when it was there
194
+ console.assert(again.size === 1);
195
+ }
196
+ ```
197
+
198
+ - `add` and `search` are async (the model or your function runs in them); `get`, `delete`, `save`, `load` are not.
199
+ - With an embedding service instead of the local model: `new TextIndex({ embed })` where
200
+ `embed = async (texts, isQuery) => vectors` returns one array of numbers (or `Float32Array`) per text. `isQuery` is
201
+ true for the question of a search and false for the texts of an `add` (some services want to know). The vectors
202
+ are compared by cosine; they need not be of length 1.
203
+ - An index made with your own `embed` needs it again at `load` (`TextIndex.load(dir, key, { embed })`); without it
204
+ `load` throws and says so.
205
+ - A replace puts a whole new record in the place of the old one: give the fields again.
206
+
207
+ ### H. Node.js: vectors only (`KciVec`), whole-number ids
208
+
209
+ ```js
210
+ const { KciVec } = require('kci-vec');
211
+
212
+ const v = new KciVec(3); // 3 dimensions, cosine; { metric: 'l2' } or 'ip' for the others
213
+ v.addMany([1, 2, 3], [[1, 0, 0], [0, 1, 0], [0.9, 0.1, 0]]);
214
+ v.build(); // needed before the first search
215
+ const hits = v.search([1, 0, 0], 2); // [{ id, score }], best first
216
+ console.assert(hits[0].id === 1 && hits[1].id === 3);
217
+ v.save('my.kvec', 'a passphrase');
218
+ const w = KciVec.load('my.kvec', 'a passphrase');
219
+ console.assert(w.search([1, 0, 0], 1)[0].id === 1);
220
+ ```
221
+
222
+ ## 3. Conditions on fields (`where`)
223
+
224
+ Python: `ix.search(..., where={...})`. Node.js: the third argument, `search(question_or_vector, k, { where: {...} })`.
225
+ The condition itself is the same in both. `{"genre": "scifi"}`: the field has that value. Comparisons go inside the
226
+ field: `{"year": {"$gte": 2000, "$lt": 2010}}`, with `$eq $ne $gt $gte $lt $lte $in $nin $contains $exists`.
227
+ Several fields in one object must all hold: `{"year": {"$lte": 2024}, "tags": "howto"}`. Other ways to combine:
228
+ `{"$or": [cond, cond]}`, `{"$and": [cond, cond]}`, `{"$not": cond}`.
229
+
230
+ A value kept in a field is a string, a number, true / false, or a list of those. A field that holds a list matches
231
+ when one of its items does: `{"tags": "howto"}` finds the records whose `tags` has "howto". `$contains` is the same
232
+ for a list, and for a string it looks for a part of it.
233
+
234
+ A field name that no record has is an error (it names the fields that exist). A value that no record has is not:
235
+ the answer is empty.
236
+
237
+ ## 4. The score
238
+
239
+ | Search | Meaning of `score` |
240
+ |---|---|
241
+ | by meaning, or by vectors with cosine (the default) | the cosine: larger = nearer, at most 1 |
242
+ | by vectors with `metric="l2"` (Node.js: `{ metric: 'l2' }`) | the squared distance: smaller = nearer (take the square root for the distance itself) |
243
+ | by vectors with `metric="ip"` | the inner product: larger = nearer |
244
+ | by words, and words with meaning together | larger = better; no fixed range, do not compare across questions |
245
+
246
+ Hits always come best first.
247
+
248
+ ## 5. Things that go wrong, and what to do
249
+
250
+ | What you see | Cause | Do |
251
+ |---|---|---|
252
+ | "not built" on a search (`KciVec`) | `build()` was not called after adding | call `build()` once after `add` / `add_many` |
253
+ | an id is refused as "already" there (`ValueError` in Python) | adding an id twice | pass `replace=True` (Python) / `{ replace: true }` (Node.js), with the fields again |
254
+ | "no record has the field ..." (`ValueError` in Python) | a mistyped field name in `where` | use a name from the error's list |
255
+ | a `where` search misses a record after it was replaced | the replace was made without its fields | give the fields in every replace |
256
+ | `load` fails: "wrong key ...", "saved with a key" (`RuntimeError` in Python, an `Error` in Node.js) | wrong or missing passphrase, or the files were changed | there is no recovery without the passphrase; ask the user for it. A folder or file that is not there fails in the same way: check that it exists first. Node.js also prints a line `kci_vec_load: wrong key` on standard error; Python prints nothing besides the exception |
257
+ | a query of all zeros is refused (cosine) | the vector has no direction | check the embedding step; do not search with an empty text |
258
+ | a warning about `rerank: 0` / no floats | the index was made to save memory and can miss items | leave `rerank` at its default unless the user asked to save memory |
259
+ | Node.js: "the native part could not be loaded" | no ready-made binary for this machine and no compiler | install gcc / cc, then install kci-vec again |
260
+ | Node.js: "@huggingface/transformers ... not installed" | `TextIndex` without an `embed` function needs it | `npm install @huggingface/transformers`, or give `embed` |
261
+
262
+ ## 6. Rules to keep
263
+
264
+ - Do not change the search settings to "make it faster" unless the user asks: the defaults give the exact answer.
265
+ - One writer at a time: do not add or delete while another thread or task is searching the same index.
266
+ - `KciVec` ids are whole numbers; `Store`, and `TextIndex` with `ids=[...]` of strings, take string ids. Do not mix
267
+ the two kinds in one index.
268
+ - The vectors of one index must all come from the same embedding model, and the question's vector too.
269
+ - A saved index is a file (`KciVec`) or a folder (`TextIndex`, `Store`). Never write the passphrase into the source
270
+ code; read it from the environment or ask the user.
271
+ - The index is not the user's database: keep the records (texts, fields) in the user's own data as well, and
272
+ rebuild the index from them when in doubt.
273
+ - A folder saved by `Store` or by the Node.js `TextIndex` (default model) is opened by the Python client, and the
274
+ other way round. An index searched by words (`sparse=`) is Python only.
275
+ - After writing the integration, run it once on a few of the user's real items and show the user the hits.
276
+
277
+ ## 7. More
278
+
279
+ - Python reference: `docs/API.md` in the source repository (https://github.com/KimYuki3/kci-vec-src).
280
+ - Node.js reference: `README.md` and `index.d.ts` in the package.
281
+ - The command line, step by step: `docs/quickstart_cli.md` (English), `docs/quickstart_cli_ja.md` (Japanese).
package/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # kci-vec for Node.js (experimental)
2
2
 
3
+ Using an AI coding assistant? Point it at `AI_GUIDE.md` in this package: one page with a recipe for each case.
4
+
3
5
  Vector search inside your Node.js program. No server, no runtime dependencies; the index can be saved to an
4
6
  encrypted file. With nothing else given, a search misses no row.
5
7
 
@@ -9,10 +11,10 @@ npm install kci-vec
9
11
 
10
12
  | Machine | What the install does |
11
13
  |---|---|
12
- | Windows x64, Linux x64 (glibc 2.28 or later) | uses the ready-made binary in the package: no compiler needed |
13
- | anything else (macOS, ARM, Alpine and other musl Linux, older Linux) | builds the C sources in the package: needs `gcc` or `cc` on the PATH |
14
+ | Windows x64, Linux x64 (glibc 2.28 or later), macOS on Apple silicon (macOS 11 or later) | uses the ready-made binary in the package: no compiler needed |
15
+ | anything else (Intel Mac, ARM Linux, Alpine and other musl Linux, older Linux) | builds the C sources in the package: needs `gcc` or `cc` on the PATH |
14
16
 
15
- On x86-64 the CPU must have AVX2 and FMA (otherwise loading says so). Node.js 18 or later. Not tried on macOS.
17
+ On x86-64 the CPU must have AVX2 and FMA (otherwise loading says so). Node.js 18 or later. Not tried on an Intel Mac or on ARM Linux.
16
18
 
17
19
  ```js
18
20
  const { KciVec } = require('kci-vec');
@@ -65,7 +67,48 @@ const again = Store.load('my_store', 'a passphrase');
65
67
  | `get(id)`, `has(id)`, `delete(id)`, `ids()`, `size`, `dim`, `metric` | |
66
68
  | `save(dir, key)`, `Store.load(dir, key)` | the folder is the one the Python client writes for `TextIndex(mode="dense", dense="vectors")` with string ids: either opens the other's |
67
69
 
68
- No language model runs in the Node client: texts are kept and returned, not read.
70
+ With `Store` the vectors are yours. `TextIndex` (next) makes them from the texts.
71
+
72
+ ## TextIndex: texts in, a question in words, the nearest texts out
73
+
74
+ ```sh
75
+ npm install kci-vec @huggingface/transformers
76
+ ```
77
+
78
+ ```js
79
+ const { TextIndex } = require('kci-vec');
80
+
81
+ const ix = new TextIndex();
82
+ await ix.add(['Paid leave: 10 days are granted after six months of service.',
83
+ 'Expense reports close at the end of the month.'],
84
+ { ids: ['leave', 'expense'], fields: [{ year: 2025 }, { year: 2024 }] });
85
+ const hits = await ix.search('how many days off do I get', 3); // [{ id, score, text, span, fields }], best first
86
+ ix.save('my_index', 'a passphrase'); // a folder; without the key nothing in it is readable
87
+ const again = TextIndex.load('my_index', 'a passphrase');
88
+ ```
89
+
90
+ - The language model (`intfloat/multilingual-e5-small`, MIT; it reads Japanese, English and many other languages) runs
91
+ on this machine through the package `@huggingface/transformers`. The first use downloads it (about 500 MB); after
92
+ that nothing leaves the machine.
93
+ - A long text is cut into parts and every part is indexed, so the end of a long text is found too. A hit's `text` is
94
+ the part that matched, `span` its place in the whole text (`get(id)` gives the whole text).
95
+ - It is a small model: it finds texts that say the same in other words, but not always (a synonym it does not know,
96
+ a question in another language than the text). For better answers give a function of your own, for example one
97
+ that calls an embedding service:
98
+
99
+ ```js
100
+ const ix = new TextIndex({ embed: async (texts, isQuery) => vectorsFromYourModel(texts) }); // one vector per text
101
+ ```
102
+
103
+ | Call | What it does |
104
+ |---|---|
105
+ | `new TextIndex({ model, embed, lang, chunk })` | `model`: another model of the hub in ONNX form. `embed`: your own function instead. `lang`: `'ja'` or `'en'` (taken from the first texts when left out; it sets the length of the parts). `chunk`: that length in characters (0 = never cut) |
106
+ | `await add(texts, { ids, fields, replace })` | `ids` left out: `'1'`, `'2'`, ... An id that is already there is refused unless `replace: true`. A call that throws has added nothing |
107
+ | `await search(question, k, { where, filter })` | best first; a text is answered once, by its best part. `where`: a condition on the fields (below); `filter`: the ids that may be answered |
108
+ | `get(id)`, `has(id)`, `delete(id)`, `ids()`, `size`, `model`, `lang` | |
109
+ | `save(dir, key)`, `TextIndex.load(dir, key, { embed })` | the folder is the one the Python client writes for `TextIndex("en", mode="dense")` with string ids: with the default model either opens the other's. An index made with your own function needs it again at `load` |
110
+
111
+ Searching by words and the two together (hybrid) are in the Python client only.
69
112
 
70
113
  Fields beside the vectors (genre, year, owner ...): keep them yourself, ask by a condition.
71
114
 
@@ -85,7 +128,7 @@ Limits
85
128
  - `knnGraph`, `compact` and `save` block the event loop while they run; the build and the search have async forms.
86
129
  - One index belongs to one JavaScript thread (the main thread or one worker). While `searchAsync` calls are under way the index cannot be changed.
87
130
  - A filter is a set of ids, not a function; the fields themselves are not stored in the index or its file.
88
- - The partitioned lists, the quantized graph and the text layer of the Python client are not here.
131
+ - The partitioned lists, the quantized graph, and the word search and hybrid search of the Python client's text layer are not here.
89
132
  - A file saved here is read by the Python client and the other way round (the same format and keys).
90
133
  - Marked experimental: names and defaults may still change.
91
134
 
@@ -95,6 +138,7 @@ From the source repository (the folder `clients/node`):
95
138
  npm install # fetches node-api-headers (headers for the build) and builds build/kci_vec.node
96
139
  node test.js # needs gcc (MinGW-w64 on Windows) or cc for the build; "node build.js" builds again
97
140
  node test_store.js
141
+ node test_text.js # TextIndex with a small embedding function made for the test (no model needed)
98
142
  node test_fuzz.js # random indexes and changes, every answer against the exact one (about a minute)
99
143
  ```
100
144
 
package/index.d.ts CHANGED
@@ -81,3 +81,33 @@ export class Store {
81
81
  static load(dir: string, key?: string | Uint8Array | null): Store;
82
82
  close(): void;
83
83
  }
84
+
85
+ /** texts in, a question in words in, the texts nearest in meaning out; saved as a folder the Python client also opens */
86
+ export type Embed = (texts: string[], isQuery: boolean) => Promise<Vector[]> | Vector[];
87
+ export interface TextHit { id: string; score: number; /** the part of the text that matched */ text: string; /** its [start, end] in characters */ span: [number, number]; fields: Fields; }
88
+ export class TextIndex {
89
+ /**
90
+ * Nothing given: a language model run by the package @huggingface/transformers (install it beside kci-vec).
91
+ * embed: a function of your own instead. lang: 'ja' | 'en' (taken from the first texts when left out).
92
+ * chunk: the length in characters of the parts a long text is cut into (0 = never cut).
93
+ */
94
+ constructor(opts?: { model?: string; embed?: Embed; lang?: 'ja' | 'en'; chunk?: number; overlap?: number });
95
+ readonly size: number;
96
+ readonly dim: number;
97
+ readonly model: string;
98
+ readonly lang: 'ja' | 'en' | null;
99
+ readonly chunk: number | null;
100
+ ids(): string[];
101
+ has(id: string): boolean;
102
+ get(id: string): { text: string; fields: Fields } | null;
103
+ /** ids left out: '1', '2', ... An id that is already there is refused unless replace is true; a call that throws has added nothing */
104
+ add(texts: string[] | string, opts?: { ids?: string[]; fields?: (Fields | null)[]; replace?: boolean }): Promise<string[]>;
105
+ delete(id: string): boolean;
106
+ /** best first (larger = nearer); a text is answered once, by its best part */
107
+ search(query: string, k?: number, opts?: { where?: Condition; filter?: Iterable<string> }): Promise<TextHit[]>;
108
+ /** key: a passphrase; the index, the ids, the texts and the fields are then encrypted */
109
+ save(dir: string, key?: string | Uint8Array | null): void;
110
+ /** an index made with a function of your own needs it again: { embed } */
111
+ static load(dir: string, key?: string | Uint8Array | null, opts?: { embed?: Embed }): TextIndex;
112
+ close(): void;
113
+ }
package/index.js CHANGED
@@ -271,4 +271,4 @@ class KciVec {
271
271
  close() { if (this.#h) { lib.close(this.#h); this.#h = null; } }
272
272
  }
273
273
 
274
- module.exports = { KciVec, Store: require('./store.js')(KciVec, lib, keyBytes), where: require('./where.js') };
274
+ module.exports = { KciVec, Store: require('./store.js')(KciVec, lib, keyBytes), TextIndex: require('./text.js')(KciVec, lib, keyBytes), where: require('./where.js') };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kci-vec",
3
- "version": "0.2.30",
3
+ "version": "0.2.32",
4
4
  "description": "Embedded vector search for Node.js: exact answers by default, encrypted files",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -25,13 +25,14 @@
25
25
  "scripts": {
26
26
  "install": "node install.js",
27
27
  "build": "node build.js",
28
- "test": "node test.js && node test_store.js",
28
+ "test": "node test.js && node test_store.js && node test_text.js",
29
29
  "prepack": "node pack-src.js"
30
30
  },
31
31
  "files": [
32
32
  "index.js",
33
33
  "where.js",
34
34
  "store.js",
35
+ "text.js",
35
36
  "index.d.ts",
36
37
  "build.js",
37
38
  "install.js",
@@ -40,9 +41,18 @@
40
41
  "src/",
41
42
  "prebuilds/",
42
43
  "README.md",
44
+ "AI_GUIDE.md",
43
45
  "LICENSE"
44
46
  ],
45
47
  "dependencies": {
46
48
  "node-api-headers": "^1.5.0"
49
+ },
50
+ "peerDependencies": {
51
+ "@huggingface/transformers": ">=3"
52
+ },
53
+ "peerDependenciesMeta": {
54
+ "@huggingface/transformers": {
55
+ "optional": true
56
+ }
47
57
  }
48
58
  }
Binary file
package/store.js CHANGED
@@ -223,3 +223,4 @@ module.exports = (KciVec, lib, keyBytes) => class Store {
223
223
  /** Free the index now. */
224
224
  close() { if (this.#vec) { this.#vec.close(); this.#vec = null; } this.#num.clear(); }
225
225
  };
226
+ module.exports.checkFields = checkFields;
package/text.js ADDED
@@ -0,0 +1,420 @@
1
+ 'use strict';
2
+ // TextIndex: texts in, a question in words in, the texts nearest in meaning out.
3
+ // The vectors come from a language model run by the package @huggingface/transformers (installed separately), or
4
+ // from a function of your own: new TextIndex({ embed: async (texts, isQuery) => vectors }).
5
+ // The folder it saves is the one the Python client writes for TextIndex(mode="dense") with string ids; with the
6
+ // default model either client opens the other's folder.
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const where = require('./where.js');
10
+ const { checkFields } = require('./store.js');
11
+
12
+ const MODEL = 'intfloat/multilingual-e5-small'; // the Python client's model for lang "en"; reads Japanese too
13
+ const PREFIX = { [MODEL]: ['query: ', 'passage: '], 'cl-nagoya/ruri-v3-30m': ['検索クエリ: ', '検索文書: '] };
14
+ const CHUNK = { ja: 600, en: 2000 }; // characters of one part with the default model
15
+ const ENDS = '。!?!?\n'; // a part may end after these
16
+ const show = (x) => { try { return JSON.stringify(x); } catch (e) { return String(x); } };
17
+ const plain = (x) => x !== null && typeof x === 'object' && !Array.isArray(x);
18
+ const isSpace = (c) => c !== undefined && /^\s$/u.test(c);
19
+
20
+ // The parts of a long text, as the Python client cuts them: [[start, end], ...] in characters (code points). A part
21
+ // ends at a sentence end when there is one in its second half, else at a space, else at `size`; the last two parts are
22
+ // made about equal; the next part starts at the first sentence end within the last `overlap` characters of the one
23
+ // before. size <= 0 or a short text: one part.
24
+ function splitText(cp, size, overlap) {
25
+ const n = cp.length;
26
+ size = Math.trunc(size);
27
+ if (size <= 0 || n <= size) return [[0, n]];
28
+ overlap = overlap == null ? Math.floor(size / 8) : Math.max(0, Math.min(Math.trunc(overlap), Math.floor(size / 2)));
29
+ const isEnd = (i) => { const c = cp[i - 1]; return ENDS.includes(c) || ('.;:'.includes(c) && isSpace(cp[i])); };
30
+ const out = [];
31
+ let start = 0;
32
+ while (n - start > size) {
33
+ const rem = n - start;
34
+ let lim = start + size;
35
+ if (rem < 2 * size - overlap) lim = start + Math.min(size, Math.floor((rem + overlap + 1) / 2) + Math.floor(size / 8));
36
+ const half = start + Math.floor((lim - start) / 2);
37
+ let end = 0;
38
+ for (let i = lim; i > half; i--) if (isEnd(i)) { end = i; break; }
39
+ if (!end) for (let i = lim; i > half; i--) if (isSpace(cp[i - 1])) { end = i; break; }
40
+ if (!end) end = lim;
41
+ out.push([start, end]);
42
+ let nxt = end;
43
+ for (let i = Math.max(end - overlap, start + 1); i < end; i++) if (isEnd(i)) { nxt = i; break; }
44
+ start = nxt;
45
+ }
46
+ out.push([start, n]);
47
+ return out;
48
+ }
49
+
50
+ // 'ja' when a tenth or more of the letters are kana or Chinese characters, else 'en' (as the kci-vec command decides)
51
+ function guessLang(texts) {
52
+ let cjk = 0, all = 0;
53
+ for (const t of texts) {
54
+ for (const c of t) {
55
+ const u = c.codePointAt(0);
56
+ if (/\s/u.test(c)) continue;
57
+ all++;
58
+ if ((u >= 0x3040 && u <= 0x30ff) || (u >= 0x4e00 && u <= 0x9fff)) cjk++;
59
+ if (all >= 20000) break;
60
+ }
61
+ if (all >= 20000) break;
62
+ }
63
+ return all && cjk * 10 >= all ? 'ja' : 'en';
64
+ }
65
+
66
+ // A sentence-embedding model from the Hugging Face hub, run here: the mean of the token vectors, length 1 (what the
67
+ // Python client computes). Loaded at the first use; the first use of a model downloads it.
68
+ function hfEmbedder(name, prefixes) {
69
+ const [qp, dp] = prefixes || PREFIX[name] || ['', ''];
70
+ let ex = null;
71
+ const load = async () => {
72
+ if (ex) return ex;
73
+ let tf;
74
+ try { tf = await import('@huggingface/transformers'); } catch (e) {
75
+ throw new Error('TextIndex: the language model runs on the package @huggingface/transformers, which is not installed here '
76
+ + '(npm install @huggingface/transformers). Or give a function of your own: new TextIndex({ embed: async (texts, isQuery) => vectors })');
77
+ }
78
+ try { ex = await tf.pipeline('feature-extraction', name, { dtype: 'fp32' }); } catch (e) {
79
+ throw new Error(`TextIndex: the model ${show(name)} could not be loaded (${String(e && e.message).split('\n')[0]}). `
80
+ + 'It has to be on the Hugging Face hub in ONNX form; the first use needs the network');
81
+ }
82
+ return ex;
83
+ };
84
+ const fn = async (texts, isQuery) => {
85
+ const e = await load(), pre = isQuery ? qp : dp, out = [];
86
+ for (let i = 0; i < texts.length; i += 16) {
87
+ const t = await e(texts.slice(i, i + 16).map((s) => pre + s), { pooling: 'mean', normalize: true });
88
+ const d = t.dims[1];
89
+ for (let j = 0; j < t.dims[0]; j++) out.push(Float32Array.from(t.data.subarray(j * d, (j + 1) * d)));
90
+ }
91
+ return out;
92
+ };
93
+ fn.modelName = name;
94
+ fn.prefixes = [qp, dp];
95
+ // what the model reads of one text: past maxTokens it reads nothing, and says nothing
96
+ fn.maxTokens = async () => Math.min(Number((await load()).tokenizer.model_max_length) || 512, 512);
97
+ fn.tokens = async (text) => (await load()).tokenizer(dp + text).input_ids.dims[1];
98
+ return fn;
99
+ }
100
+
101
+ module.exports = (KciVec, lib, keyBytes) => class TextIndex {
102
+ #vec = null; #embed; #model; #lang; #chunk; #overlap; #meta = null;
103
+ #num = new Map(); #name = new Map(); // string id -> number inside, and back
104
+ #texts = new Map(); #fields = new Map(); // number inside -> text, fields
105
+ #rows = new Map(); #docRows = new Map(); // row of the index -> [number inside, start, end]; number inside -> its rows
106
+ #next = 0; #rowNext = 0; #auto = 0;
107
+ #queue = Promise.resolve(); // add() calls run one after another
108
+
109
+ /**
110
+ * new TextIndex({ model, embed, lang, chunk, overlap }). Nothing given: the model intfloat/multilingual-e5-small.
111
+ * embed: a function of your own, async (texts, isQuery) => one vector per text (then nothing is cut unless chunk is
112
+ * given). lang: 'ja' or 'en' (taken from the first texts when left out); it sets the length of the parts long
113
+ * texts are cut into. chunk: that length in characters (0 = never cut).
114
+ */
115
+ constructor(opts = {}) {
116
+ if (!plain(opts)) throw new TypeError('TextIndex: the options must be an object such as { lang: \'ja\' }');
117
+ if (opts.embed !== undefined && typeof opts.embed !== 'function') throw new TypeError('TextIndex: embed must be a function: async (texts, isQuery) => vectors');
118
+ if (opts.embed && opts.model !== undefined) throw new RangeError('TextIndex: give model or embed, not both');
119
+ if (opts.model !== undefined && (typeof opts.model !== 'string' || !opts.model)) throw new TypeError('TextIndex: model must be the name of a model on the Hugging Face hub');
120
+ if (opts.lang !== undefined && opts.lang !== 'ja' && opts.lang !== 'en') throw new RangeError("TextIndex: lang must be 'ja' or 'en'");
121
+ for (const key of ['chunk', 'overlap']) {
122
+ if (opts[key] !== undefined && opts[key] !== null && !(Number.isInteger(opts[key]) && opts[key] >= 0)) throw new RangeError(`TextIndex: ${key} must be a whole number from 0`);
123
+ }
124
+ this.#embed = opts.embed || hfEmbedder(opts.model || MODEL, opts.prefixes);
125
+ this.#model = opts.embed ? 'custom' : this.#embed.modelName;
126
+ this.#lang = opts.lang || null;
127
+ this.#chunk = opts.chunk ?? (opts.embed ? 0 : null); // null: by the language, at the first add
128
+ this.#overlap = opts.overlap ?? null;
129
+ }
130
+
131
+ get size() { return this.#num.size; }
132
+ get dim() { return this.#vec ? this.#vec.dim : 0; }
133
+ get model() { return this.#model; }
134
+ get lang() { return this.#lang; }
135
+ get chunk() { return this.#chunk; }
136
+ ids() { return Array.from(this.#num.keys()); }
137
+ has(id) { return this.#num.has(id); }
138
+ /** { text, fields } of an id, or null. */
139
+ get(id) {
140
+ const d = this.#num.get(id);
141
+ return d === undefined ? null : { text: this.#texts.get(d) ?? '', fields: { ...(this.#fields.get(d) || {}) } };
142
+ }
143
+
144
+ #ready() { if (this.#vec && !this.#vec.isBuilt) this.#vec.build(); }
145
+
146
+ async #vectors(texts, isQuery, what) {
147
+ const vs = await this.#embed(texts, isQuery);
148
+ if (!Array.isArray(vs) || vs.length !== texts.length) throw new Error(`${what}: the embed function must return one vector per text (${texts.length} texts, ${Array.isArray(vs) ? vs.length + ' vectors' : typeof vs})`);
149
+ const dim = this.dim || (vs[0] && vs[0].length);
150
+ return vs.map((v, i) => {
151
+ if (!(v instanceof Float32Array) && !(v instanceof Float64Array) && !Array.isArray(v)) throw new TypeError(`${what}: vector ${i} from the embed function is not an array of numbers`);
152
+ const f = Float32Array.from(v);
153
+ if (!f.length || f.length !== dim) throw new RangeError(`${what}: vector ${i} from the embed function has ${f.length} numbers, the others ${dim}`);
154
+ if (!f.every(Number.isFinite)) throw new RangeError(`${what}: vector ${i} from the embed function has a NaN or an infinity`);
155
+ if (!f.some((x) => x !== 0)) throw new RangeError(`${what}: vector ${i} from the embed function is all zeros`);
156
+ return f;
157
+ });
158
+ }
159
+
160
+ // the parts of one text; with a model that says how much it reads, a part it would not read to the end is cut again
161
+ async #parts(cp) {
162
+ const spans = splitText(cp, this.#chunk, this.#overlap);
163
+ if (typeof this.#embed.tokens !== 'function') return spans;
164
+ const max = await this.#embed.maxTokens(), out = [];
165
+ const fit = async (a, e) => {
166
+ if (e - a + 8 <= max || e - a < 2 || await this.#embed.tokens(cp.slice(a, e).join('')) <= max) { out.push([a, e]); return; }
167
+ for (const [x, y] of splitText(cp.slice(a, e), Math.ceil((e - a) / 2), 0)) await fit(a + x, a + y);
168
+ };
169
+ for (const [a, e] of spans) await fit(a, e);
170
+ return out;
171
+ }
172
+
173
+ /**
174
+ * Add texts: await ix.add(['...', '...'], { ids: ['a', 'b'], fields: [{ year: 2024 }, null], replace: false }).
175
+ * ids: one string per text (left out: '1', '2', ...). An id that is already there is refused unless replace is
176
+ * true. A long text is cut into parts and every part is indexed. Everything is checked and every vector is made
177
+ * first: a call that throws has added nothing. Returns the ids.
178
+ */
179
+ add(texts, opts = {}) {
180
+ const run = this.#queue.then(() => this.#add(texts, opts));
181
+ this.#queue = run.catch(() => {});
182
+ return run;
183
+ }
184
+
185
+ async #add(texts, opts) {
186
+ if (typeof texts === 'string') texts = [texts];
187
+ if (!Array.isArray(texts)) throw new TypeError('add: give an array of texts');
188
+ if (!plain(opts)) throw new TypeError('add: the options must be an object such as { ids: [...] }');
189
+ if (!texts.length) return [];
190
+ for (const key of ['ids', 'fields']) {
191
+ if (opts[key] != null && (!Array.isArray(opts[key]) || opts[key].length !== texts.length)) throw new RangeError(`add: ${key} must be an array with one entry per text (${texts.length})`);
192
+ }
193
+ const seen = new Set(), docs = [];
194
+ let auto = this.#auto;
195
+ texts.forEach((t, i) => {
196
+ const what = `add (text ${i})`;
197
+ if (typeof t !== 'string') throw new TypeError(`${what}: a text must be a string, not ${show(t)}`);
198
+ if (!t.trim()) throw new RangeError(`${what}: the text is empty`);
199
+ let id;
200
+ if (opts.ids) {
201
+ id = opts.ids[i];
202
+ if (typeof id !== 'string' || !id) throw new TypeError(`${what}: the id must be a string that is not empty, not ${show(id)}`);
203
+ } else {
204
+ do { id = String(++auto); } while (this.#num.has(id) || seen.has(id));
205
+ }
206
+ if (seen.has(id)) throw new RangeError(`${what}: the id ${show(id)} is given twice in this call`);
207
+ seen.add(id);
208
+ if (this.#num.has(id) && !opts.replace) throw new RangeError(`${what}: the id ${show(id)} is already in the index ({ replace: true } replaces it)`);
209
+ const f = opts.fields ? opts.fields[i] : null;
210
+ if (f !== undefined && f !== null) checkFields(f, what);
211
+ docs.push({ id, text: t, fields: f ? JSON.parse(JSON.stringify(f)) : null });
212
+ });
213
+ const lang = this.#lang || guessLang(texts);
214
+ const chunk0 = this.#chunk;
215
+ if (this.#chunk === null) this.#chunk = CHUNK[lang];
216
+ let vs;
217
+ const flat = [];
218
+ try {
219
+ for (const d of docs) {
220
+ const cp = Array.from(d.text);
221
+ d.spans = await this.#parts(cp);
222
+ for (const [a, e] of d.spans) flat.push(cp.slice(a, e).join(''));
223
+ }
224
+ vs = await this.#vectors(flat, false, 'add');
225
+ } catch (e) { this.#chunk = chunk0; throw e; }
226
+ // from here on nothing waits and nothing is refused
227
+ this.#lang = lang; this.#auto = auto;
228
+ if (!this.#vec) this.#vec = new KciVec(vs[0].length, { metric: 'cosine', rerank: 200 });
229
+ const old = docs.filter((d) => this.#num.has(d.id));
230
+ if (old.length) { this.#ready(); for (const d of old) this.#drop(this.#num.get(d.id)); }
231
+ const built = this.#vec.isBuilt;
232
+ let n = 0;
233
+ for (const doc of docs) {
234
+ let d = this.#num.get(doc.id);
235
+ if (d === undefined) { d = this.#next++; this.#num.set(doc.id, d); this.#name.set(d, doc.id); }
236
+ const mine = [];
237
+ for (const [a, e] of doc.spans) {
238
+ const row = this.#rowNext++;
239
+ if (built) this.#vec.insert(row, vs[n++]); else this.#vec.add(row, vs[n++]);
240
+ this.#rows.set(row, [d, a, e]); mine.push(row);
241
+ }
242
+ this.#docRows.set(d, mine); this.#texts.set(d, doc.text);
243
+ if (doc.fields && Object.keys(doc.fields).length) this.#fields.set(d, doc.fields); else this.#fields.delete(d);
244
+ }
245
+ return docs.map((d) => d.id);
246
+ }
247
+
248
+ #drop(d) { // the rows of one text out of the index (the text's number stays for a replace)
249
+ for (const row of this.#docRows.get(d) || []) { this.#vec.delete(row); this.#rows.delete(row); }
250
+ this.#docRows.delete(d);
251
+ }
252
+
253
+ /** Take a text out. true when it was there. */
254
+ delete(id) {
255
+ const d = this.#num.get(id);
256
+ if (d === undefined) return false;
257
+ this.#ready();
258
+ this.#drop(d);
259
+ this.#num.delete(id); this.#name.delete(d); this.#texts.delete(d); this.#fields.delete(d);
260
+ return true;
261
+ }
262
+
263
+ /**
264
+ * The k texts nearest in meaning to the question: await ix.search('...', 5, { where, filter }) ->
265
+ * [{ id, score, text, span, fields }], best first. text is the part of the text that matched and span its
266
+ * [start, end] in characters; a text is answered once, by its best part. where: a condition on the fields;
267
+ * filter: the ids that may be answered. A field name that no text has throws.
268
+ */
269
+ async search(query, k = 5, opts = {}) {
270
+ if (typeof query !== 'string') throw new TypeError('search: the question must be a string');
271
+ if (!query.trim()) throw new RangeError('search: the question is empty');
272
+ if (typeof k !== 'number' || !Number.isInteger(k) || k < 1) throw new RangeError(`search: k must be a whole number from 1, not ${String(k)}`);
273
+ if (!plain(opts)) throw new TypeError('search: the options must be an object such as { where: {...} }');
274
+ const pass = () => { // the numbers inside that may be answered, or null for all
275
+ let ds = null;
276
+ if (opts.filter != null) {
277
+ if (typeof opts.filter === 'string' || typeof opts.filter[Symbol.iterator] !== 'function') throw new TypeError('search: filter must be an array or a Set of ids');
278
+ ds = new Set();
279
+ for (const id of opts.filter) { const d = this.#num.get(id); if (d !== undefined) ds.add(d); }
280
+ }
281
+ if (opts.where != null) {
282
+ const by = new Map();
283
+ for (const d of this.#name.keys()) by.set(d, this.#fields.get(d) || {});
284
+ const ok = new Set(where.ids(by, opts.where));
285
+ ds = ds === null ? ok : new Set(Array.from(ds).filter((d) => ok.has(d)));
286
+ }
287
+ return ds;
288
+ };
289
+ pass(); // a wrong filter or field name: said before the model runs
290
+ if (!this.#vec || !this.#num.size) return [];
291
+ const q = (await this.#vectors([query], true, 'search'))[0];
292
+ const ds = pass(); // again: texts may have come or gone while the model ran
293
+ if (!this.#vec || !this.#num.size || (ds !== null && !ds.size)) return [];
294
+ if (q.length !== this.dim) throw new RangeError(`search: the question's vector has ${q.length} numbers, those in the index ${this.dim}`);
295
+ let rows = null, total = this.#rows.size;
296
+ if (ds !== null) { rows = []; for (const d of ds) for (const r of this.#docRows.get(d) || []) rows.push(r); total = rows.length; }
297
+ if (!total) return [];
298
+ this.#ready();
299
+ const want = Math.min(k, ds === null ? this.#num.size : ds.size);
300
+ for (let kk = Math.min(total, want * 3); ; kk = Math.min(total, kk * 4)) {
301
+ const hits = this.#vec.search(q, kk, rows === null ? {} : { filter: rows });
302
+ const best = new Map();
303
+ for (const h of hits) {
304
+ const r = this.#rows.get(Number(h.id));
305
+ if (r && !best.has(r[0])) best.set(r[0], [h.score, r[1], r[2]]);
306
+ }
307
+ if (best.size >= want || kk >= total) {
308
+ return Array.from(best.entries()).slice(0, k).map(([d, [score, a, e]]) => ({
309
+ id: this.#name.get(d), score, text: Array.from(this.#texts.get(d) ?? '').slice(a, e).join(''), span: [a, e], fields: { ...(this.#fields.get(d) || {}) },
310
+ }));
311
+ }
312
+ }
313
+ }
314
+
315
+ /**
316
+ * Write the index into the folder dir. key (a passphrase): the index, the ids, the texts and the fields are
317
+ * encrypted; without it they are readable. meta.json stays readable either way (settings and counts, no text, no id).
318
+ */
319
+ save(dir, key) {
320
+ if (typeof dir !== 'string' || !dir) throw new TypeError('save: the folder must be a string');
321
+ if (!this.#num.size) throw new Error('save: the index is empty');
322
+ const kb = keyBytes(key);
323
+ this.#ready();
324
+ fs.mkdirSync(dir, { recursive: true });
325
+ this.#vec.save(path.join(dir, 'dense.kvec'), kb);
326
+ const put = (base, obj) => {
327
+ for (const ext of ['.json', '.kct']) fs.rmSync(path.join(dir, base + ext), { force: true }); // never leave an older copy, a plain one least of all
328
+ if (obj === null) return;
329
+ const raw = new Uint8Array(Buffer.from(JSON.stringify(obj), 'utf8'));
330
+ fs.writeFileSync(path.join(dir, base + (kb ? '.kct' : '.json')), kb ? lib.seal(raw, kb) : raw);
331
+ };
332
+ const byD = (m) => Object.fromEntries(Array.from(m.entries()).sort((a, b) => a[0] - b[0]).map(([d, x]) => [String(d), x]));
333
+ put('texts', byD(this.#texts));
334
+ put('fields', this.#fields.size ? byD(this.#fields) : null);
335
+ put('names', byD(this.#name));
336
+ const chunk = this.#chunk ?? 0;
337
+ const meta = {
338
+ w_dense: 0.4, sparse: null, sparse_dim: null, dedup: false, phrase: false, phrase_depth: 1000, phrase_stop: [], phrase_common: null, ...(this.#meta || {}),
339
+ // the Python client picks its model by lang: "en" is the default model here, whatever the language of the texts
340
+ format: 4, names: true, fields: this.#fields.size > 0, lang: this.#model === 'cl-nagoya/ruri-v3-30m' ? 'ja' : this.#model === MODEL ? 'en' : (this.#lang || 'en'),
341
+ mode: 'dense', blocks: false, sparse_blocks: false, next: this.#next,
342
+ ids: Array.from(this.#name.keys()).sort((a, b) => a - b), texts: true, encrypted: !!kb, dense: this.#model,
343
+ chunk, dense_chunk: chunk, overlap: this.#overlap, row_next: this.#rowNext, sparse_state: false,
344
+ node: { lang: this.#lang, auto: this.#auto, prefixes: this.#embed.prefixes || null },
345
+ rows: Array.from(this.#rows.entries()).sort((a, b) => a[0] - b[0]).map(([row, [d, a, e]]) => [row, d, a, e, 'b']),
346
+ };
347
+ fs.writeFileSync(path.join(dir, 'meta.json'), JSON.stringify(meta));
348
+ }
349
+
350
+ /**
351
+ * Open a saved index: TextIndex.load(dir, key, { embed }). Also one saved by the Python client with mode="dense",
352
+ * a language model and string ids. An index made with a function of your own needs that function again.
353
+ */
354
+ static load(dir, key, opts = {}) {
355
+ if (typeof dir !== 'string' || !dir) throw new TypeError('load: the folder must be a string');
356
+ if (!plain(opts)) throw new TypeError('load: the options must be an object such as { embed }');
357
+ let meta;
358
+ try { meta = JSON.parse(fs.readFileSync(path.join(dir, 'meta.json'), 'utf8')); } catch (e) {
359
+ throw new Error(`load: ${show(dir)} is not a saved index (meta.json ${e.code === 'ENOENT' ? 'is missing' : 'cannot be read'})`);
360
+ }
361
+ if (!plain(meta) || !Array.isArray(meta.ids) || !Array.isArray(meta.rows)) throw new Error('load: meta.json is damaged');
362
+ if (!(meta.format <= 5)) throw new Error(`load: this folder was written by a newer version (format ${show(meta.format)})`);
363
+ if (meta.dense === 'vectors') throw new Error('load: this folder holds vectors of your own: open it with Store.load');
364
+ if (meta.mode !== 'dense') throw new Error(`load: this index searches by words too (mode ${show(meta.mode)}): the Python client opens it; the Node client searches by meaning only`);
365
+ if (meta.ids.length && !meta.names) throw new Error('load: this index has whole-number ids (the Python client opens it); the Node client keeps string ids');
366
+ if (meta.dedup) throw new Error('load: this index was made with dedup (the Python client opens it)');
367
+ const custom = typeof meta.dense !== 'string' || meta.dense === 'custom';
368
+ if (opts.embed !== undefined && typeof opts.embed !== 'function') throw new TypeError('load: embed must be a function: async (texts, isQuery) => vectors');
369
+ if (custom && !opts.embed) throw new Error('load: this index was made with an embed function of your own: give it again, TextIndex.load(dir, key, { embed })');
370
+ const kb = meta.encrypted ? keyBytes(key) : null;
371
+ if (meta.encrypted && !kb) throw new Error('load: this index was saved with a key; give the key');
372
+ const node = plain(meta.node) ? meta.node : {};
373
+ const ix = opts.embed ? new TextIndex({ embed: opts.embed }) : new TextIndex({ model: meta.dense, prefixes: Array.isArray(node.prefixes) ? node.prefixes : undefined });
374
+ ix.#model = custom ? 'custom' : meta.dense;
375
+ ix.#lang = node.lang === 'ja' || node.lang === 'en' ? node.lang : (meta.lang === 'ja' ? 'ja' : 'en');
376
+ ix.#chunk = Number(meta.dense_chunk ?? meta.chunk) || 0;
377
+ ix.#overlap = Number.isInteger(meta.overlap) ? meta.overlap : null;
378
+ ix.#vec = KciVec.load(path.join(dir, 'dense.kvec'), kb, { rerank: 200 });
379
+ if (ix.#vec.metric !== 'cosine') throw new Error('load: this index does not compare by cosine');
380
+ const get = (base, need) => {
381
+ const f = path.join(dir, base + (kb ? '.kct' : '.json'));
382
+ if (!fs.existsSync(f)) { if (need) throw new Error(`load: ${base + (kb ? '.kct' : '.json')} is missing`); return {}; }
383
+ const raw = fs.readFileSync(f);
384
+ let obj;
385
+ try { obj = JSON.parse(Buffer.from(kb ? lib.unseal(new Uint8Array(raw), kb) : raw).toString('utf8')); } catch (e) {
386
+ throw new Error(`load: ${path.basename(f)} cannot be read (${kb ? 'wrong key, or ' : ''}damaged)`);
387
+ }
388
+ if (!plain(obj)) throw new Error(`load: ${path.basename(f)} is damaged`);
389
+ return obj;
390
+ };
391
+ if (!meta.texts) throw new Error('load: this index was saved without its texts (the Python client opens it)');
392
+ const names = get('names', meta.ids.length > 0), texts = get('texts', true), fields = meta.fields ? get('fields', true) : {};
393
+ const live = new Set(meta.ids.map(Number));
394
+ for (const [d0, nm] of Object.entries(names)) {
395
+ const d = Number(d0);
396
+ if (!live.has(d) || typeof nm !== 'string') continue;
397
+ ix.#num.set(nm, d); ix.#name.set(d, nm); ix.#texts.set(d, typeof texts[d0] === 'string' ? texts[d0] : '');
398
+ if (plain(fields[d0])) ix.#fields.set(d, fields[d0]);
399
+ }
400
+ for (const r of meta.rows) {
401
+ const row = Number(r[0]), d = Number(r[1]);
402
+ if (!ix.#name.has(d) || ix.#rows.has(row) || r[4] === 's') continue;
403
+ const n = Array.from(ix.#texts.get(d)).length;
404
+ ix.#rows.set(row, [d, Number(r[2]) || 0, r[3] == null ? n : Number(r[3])]);
405
+ if (!ix.#docRows.has(d)) ix.#docRows.set(d, []);
406
+ ix.#docRows.get(d).push(row);
407
+ }
408
+ for (const d of ix.#name.keys()) if (!ix.#docRows.has(d)) throw new Error('load: meta.json is damaged (an id without its vector)');
409
+ ix.#next = Number(meta.next) || 0; ix.#rowNext = Number(meta.row_next ?? meta.next) || 0; ix.#auto = Number(node.auto) || 0;
410
+ for (const d of ix.#name.keys()) ix.#next = Math.max(ix.#next, d + 1);
411
+ for (const row of ix.#rows.keys()) ix.#rowNext = Math.max(ix.#rowNext, row + 1);
412
+ const { ids, rows, ...rest } = meta;
413
+ ix.#meta = rest;
414
+ return ix;
415
+ }
416
+
417
+ /** Free the index now. */
418
+ close() { if (this.#vec) { this.#vec.close(); this.#vec = null; } this.#num.clear(); this.#rows.clear(); this.#docRows.clear(); }
419
+ };
420
+ module.exports.splitText = splitText;