@yaks/embedding 0.0.0-stage → 0.2.36

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.
Files changed (132) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +549 -2
  3. package/_dist/compile.d.ts +34 -0
  4. package/_dist/compile.d.ts.map +1 -0
  5. package/_dist/ddl.d.ts +31 -0
  6. package/_dist/ddl.d.ts.map +1 -0
  7. package/_dist/embedder.d.ts +55 -0
  8. package/_dist/embedder.d.ts.map +1 -0
  9. package/_dist/fields.d.ts +70 -0
  10. package/_dist/fields.d.ts.map +1 -0
  11. package/_dist/graph.d.ts +63 -0
  12. package/_dist/graph.d.ts.map +1 -0
  13. package/_dist/held.d.ts +16 -0
  14. package/_dist/held.d.ts.map +1 -0
  15. package/_dist/image.d.ts +20 -0
  16. package/_dist/image.d.ts.map +1 -0
  17. package/_dist/mod.d.ts +105 -0
  18. package/_dist/mod.d.ts.map +1 -0
  19. package/_dist/native.d.ts +20 -0
  20. package/_dist/native.d.ts.map +1 -0
  21. package/_dist/near.d.ts +35 -0
  22. package/_dist/near.d.ts.map +1 -0
  23. package/_dist/neighbours.d.ts +29 -0
  24. package/_dist/neighbours.d.ts.map +1 -0
  25. package/_dist/options.d.ts +37 -0
  26. package/_dist/options.d.ts.map +1 -0
  27. package/_dist/outage.d.ts +64 -0
  28. package/_dist/outage.d.ts.map +1 -0
  29. package/_dist/owed.d.ts +79 -0
  30. package/_dist/owed.d.ts.map +1 -0
  31. package/_dist/remote.d.ts +116 -0
  32. package/_dist/remote.d.ts.map +1 -0
  33. package/_dist/score.d.ts +10 -0
  34. package/_dist/score.d.ts.map +1 -0
  35. package/_dist/search.d.ts +24 -0
  36. package/_dist/search.d.ts.map +1 -0
  37. package/_dist/service.d.ts +23 -0
  38. package/_dist/service.d.ts.map +1 -0
  39. package/_dist/sleeper.d.ts +37 -0
  40. package/_dist/sleeper.d.ts.map +1 -0
  41. package/_dist/sweep.d.ts +71 -0
  42. package/_dist/sweep.d.ts.map +1 -0
  43. package/_dist/tools.d.ts +14 -0
  44. package/_dist/tools.d.ts.map +1 -0
  45. package/_dist/vector.d.ts +30 -0
  46. package/_dist/vector.d.ts.map +1 -0
  47. package/_dist/vocab.d.ts +6 -0
  48. package/_dist/vocab.d.ts.map +1 -0
  49. package/coded.js +98 -0
  50. package/coded.js.map +1 -0
  51. package/coded.ts +85 -0
  52. package/compile.js +145 -0
  53. package/compile.js.map +1 -0
  54. package/compile.ts +206 -0
  55. package/ddl.js +476 -0
  56. package/ddl.js.map +1 -0
  57. package/ddl.ts +346 -0
  58. package/deno.json +1 -0
  59. package/embedder.js +85 -0
  60. package/embedder.js.map +1 -0
  61. package/embedder.ts +113 -0
  62. package/fields.js +178 -0
  63. package/fields.js.map +1 -0
  64. package/fields.ts +259 -0
  65. package/fill.js +177 -0
  66. package/fill.js.map +1 -0
  67. package/fill.ts +144 -0
  68. package/graph.js +113 -0
  69. package/graph.js.map +1 -0
  70. package/graph.ts +167 -0
  71. package/held.js +680 -0
  72. package/held.js.map +1 -0
  73. package/held.ts +726 -0
  74. package/image.js +202 -0
  75. package/image.js.map +1 -0
  76. package/image.ts +185 -0
  77. package/mod.js +105 -0
  78. package/mod.js.map +1 -0
  79. package/mod.ts +113 -0
  80. package/native.js +236 -0
  81. package/native.js.map +1 -0
  82. package/native.ts +288 -0
  83. package/near.js +123 -0
  84. package/near.js.map +1 -0
  85. package/near.ts +192 -0
  86. package/neighbours.js +223 -0
  87. package/neighbours.js.map +1 -0
  88. package/neighbours.ts +303 -0
  89. package/options.js +187 -0
  90. package/options.js.map +1 -0
  91. package/options.ts +269 -0
  92. package/outage.js +128 -0
  93. package/outage.js.map +1 -0
  94. package/outage.ts +132 -0
  95. package/owed.js +287 -0
  96. package/owed.js.map +1 -0
  97. package/owed.ts +346 -0
  98. package/package.json +45 -4
  99. package/remote.js +264 -0
  100. package/remote.js.map +1 -0
  101. package/remote.ts +391 -0
  102. package/score.js +46 -0
  103. package/score.js.map +1 -0
  104. package/score.ts +60 -0
  105. package/search.js +65 -0
  106. package/search.js.map +1 -0
  107. package/search.ts +118 -0
  108. package/service.js +107 -0
  109. package/service.js.map +1 -0
  110. package/service.ts +133 -0
  111. package/sleeper.js +107 -0
  112. package/sleeper.js.map +1 -0
  113. package/sleeper.ts +166 -0
  114. package/sparse.js +36 -0
  115. package/sparse.js.map +1 -0
  116. package/sparse.ts +49 -0
  117. package/sweep.js +374 -0
  118. package/sweep.js.map +1 -0
  119. package/sweep.ts +446 -0
  120. package/tools.js +57 -0
  121. package/tools.js.map +1 -0
  122. package/tools.ts +88 -0
  123. package/vector.js +78 -0
  124. package/vector.js.map +1 -0
  125. package/vector.ts +96 -0
  126. package/visibility.js +83 -0
  127. package/visibility.js.map +1 -0
  128. package/visibility.ts +111 -0
  129. package/vocab.js +22 -0
  130. package/vocab.js.map +1 -0
  131. package/vocab.json +19 -0
  132. package/vocab.ts +22 -0
package/remote.ts ADDED
@@ -0,0 +1,391 @@
1
+ // An embedder over HTTP — the one transport shipped here, because a model worth
2
+ // using is almost always behind a URL.
3
+ //
4
+ // It holds no credential and reads no environment: the endpoint, the model and
5
+ // the token are arguments, which is what lets the same code run on a server
6
+ // (where the token arrives from the process), in a Worker (where it arrives on
7
+ // `env`), and in a test (where it is made up and the `fetch` is a stub).
8
+ //
9
+ // Two APIs, one declaration. Ollama answers `/api/embed` with
10
+ // `{embeddings: [[…]]}`, and an OpenAI-compatible server answers
11
+ // `/v1/embeddings` with `{data: [{embedding: […]}]}`; `api` names which, and
12
+ // nothing else here differs. Which server speaks which is the provider row's
13
+ // to say (./options.ts), not this file's.
14
+ //
15
+ // A failure — an error status, an unexpected body, a timeout — is first sent
16
+ // again after each pause of {@link retries}, since a provider's own failure (a
17
+ // 503, Workers AI's "3048: Unknown internal error") usually passes in seconds
18
+ // ({@link retrying}). One that outlasts them is thrown once as
19
+ // {@link Unanswered}, the model and the call in its context, because the sweep is what decides what an unreachable
20
+ // embedder means (it stops, and the corpus stays stale), and a vector
21
+ // invented here to avoid the error would be worse than no vector at all. A status saying the input itself
22
+ // was refused throws {@link Refused}, which the sweep treats as one text it
23
+ // cannot embed rather than a model it cannot reach. A server may refuse a text
24
+ // past its model's context rather than truncate it, as Ollama does for some
25
+ // texts on a 512-token model, so a text refused alone is asked again as its
26
+ // opening half, down to {@link SHORTEST} characters.
27
+ //
28
+ // Calls made together are sent together. Both servers take an array of inputs,
29
+ // and a batch of 64 costs a local model about a seventh of the time per vector
30
+ // that 64 single requests do, so every `embed()` made together (the sweep makes
31
+ // a batch's calls at once, in one synchronous run) waits for the microtasks
32
+ // already queued and rides in one request — split by {@link parts} into
33
+ // requests no longer than a server takes. A microtask rather than a timer: a
34
+ // bare setTimeout(0) takes about 2 ms under Deno 2.9, and every search's one
35
+ // embedding waited on it.
36
+
37
+ import { type Embedder, Refused, Unanswered, Withheld } from './embedder.js'
38
+ import { unit } from './vector.js'
39
+
40
+ /** The slice of `fetch` this file uses — the web one, and a Worker's. */
41
+ export type Fetch = (
42
+ input: string,
43
+ init?: {
44
+ method?: string
45
+ headers?: Record<string, string>
46
+ body?: string
47
+ signal?: AbortSignal
48
+ },
49
+ ) => Promise<{ ok: boolean; status: number; text: () => Promise<string> }>
50
+
51
+ /** The APIs spoken here: Ollama's own, and OpenAI-compatible. */
52
+ export type Api = 'ollama' | 'openai'
53
+
54
+ /** A hosted or local embedding endpoint: a provider, and the model asked of
55
+ * it. */
56
+ export type Remote = {
57
+ /** which API the server speaks: Ollama's own, or OpenAI-compatible */
58
+ api: Api
59
+ /** what the server calls the model, sent with every request */
60
+ model: string
61
+ /** the space the vectors live in (default {@link space} of the model): the
62
+ * model's own name, whoever serves it, where the provider calls it
63
+ * something else */
64
+ space?: string
65
+ /** the server's root, without a path (`https://ollama.example`) */
66
+ base: string
67
+ /** a bearer token; a server on your own network may need none */
68
+ key?: string
69
+ /** Matryoshka width: keep this many leading coordinates (see {@link cut}) */
70
+ dim?: number
71
+ /** how long to wait for one request (default 30s) */
72
+ timeout?: number
73
+ /** the fetch to call through (default: the global one) */
74
+ fetch?: Fetch
75
+ /** pauses before resending a failed call, in milliseconds */
76
+ waits?: readonly number[]
77
+ } & Load
78
+
79
+ // Where each server takes an embedding request, and where it puts the answer.
80
+ let PATH = { ollama: '/api/embed', openai: '/v1/embeddings' }
81
+
82
+ /**
83
+ * How much of a text is sent by default. A model embeds a bounded context, and
84
+ * a server asked for more refuses the request rather than truncating it — which
85
+ * would stop a sweep at the same long document on every pass. So a long text
86
+ * is cut to its opening, which is what the model would have read of it anyway.
87
+ * qwen3-embedding refuses somewhere past 35,000 characters of markdown.
88
+ */
89
+ export let CHARS = 30_000
90
+
91
+ /** The most inputs one request carries by default. */
92
+ export let COUNT = 64
93
+
94
+ /** The most characters one request carries by default: a batch of long texts
95
+ * is split before a server spends the whole timeout on it. */
96
+ export let LOAD = 128_000
97
+
98
+ /** The shortest text asked again after a refusal: one refused at this
99
+ * length is refused for more than its length. */
100
+ export let SHORTEST = 256
101
+
102
+ /** The pauses before a call that failed on the provider's side is sent again,
103
+ * one per resend: about eight seconds in all, which a passing failure rarely
104
+ * outlasts. */
105
+ export const retries: { readonly waits: readonly number[] } = Object.freeze({
106
+ waits: Object.freeze([500, 2_000, 6_000]),
107
+ })
108
+
109
+ // The statuses that mean the input was refused, not the request: malformed,
110
+ // too large, or unprocessable.
111
+ let REFUSED = [400, 413, 422]
112
+
113
+ let vectorsOf = (api: Api, body: unknown): number[][] | undefined => {
114
+ let said = body as {
115
+ embeddings?: number[][]
116
+ data?: { embedding?: number[]; index?: number }[]
117
+ }
118
+ return api == 'ollama' ? said.embeddings : said.data
119
+ ?.toSorted((a, b) => (a.index ?? 0) - (b.index ?? 0))
120
+ .map((d) => d.embedding ?? [])
121
+ }
122
+
123
+ /**
124
+ * Texts split into runs of at most `count` of them and `load` characters,
125
+ * in order. A text longer than `load` rides alone.
126
+ *
127
+ * ```ts
128
+ * import { assertEquals } from '@std/assert'
129
+ * assertEquals(parts(['ab', 'cd', 'e', 'fghij'], 2, 4), [['ab', 'cd'], ['e'], ['fghij']])
130
+ * ```
131
+ */
132
+ export let parts = (
133
+ texts: string[],
134
+ count: number,
135
+ load: number,
136
+ measure: (text: string) => number = (text) => text.length,
137
+ ): string[][] => {
138
+ let runs: string[][] = []
139
+ let size = Infinity
140
+ for (let t of texts) {
141
+ let weight = measure(t)
142
+ let run = runs.at(-1)
143
+ if (!run || run.length >= count || size + weight > load) {
144
+ runs.push([t])
145
+ size = weight
146
+ } else {
147
+ run.push(t)
148
+ size += weight
149
+ }
150
+ }
151
+ return runs
152
+ }
153
+
154
+ /**
155
+ * Matryoshka truncation: an MRL-trained model's leading coordinates are
156
+ * themselves a valid smaller embedding, so a corpus is kept at one width
157
+ * without a second model — and renormalized, so a cosine stays a cosine.
158
+ * A model that answers narrower than asked is a misconfiguration, not a
159
+ * vector to pad.
160
+ */
161
+ export let cut = (v: Float32Array, dim: number): Float32Array => {
162
+ if (v.length < dim) {
163
+ throw new Error(
164
+ `@yaks/embedding: the model answered ${v.length} dimensions, fewer than the ${dim} asked for`,
165
+ )
166
+ }
167
+ return unit(v.slice(0, dim))
168
+ }
169
+
170
+ /** The space an embedder's vectors live in: the model, and its width when
171
+ * {@link cut}, since two widths of one model are two spaces. */
172
+ export let space = (said: { model: string; dim?: number }): string =>
173
+ said.dim ? `${said.model}#${said.dim}` : said.model
174
+
175
+ /** How many texts ride one request, and how much of each is sent. */
176
+ export type Load = {
177
+ /** the most characters sent for one vector (default {@link CHARS}) */
178
+ chars?: number
179
+ /** the most inputs one request carries (default {@link COUNT}) */
180
+ count?: number
181
+ /** the most characters one request carries (default {@link LOAD}) */
182
+ load?: number
183
+ /** measure of one input in the request, in the same units as `load` */
184
+ measure?: (text: string) => number
185
+ }
186
+
187
+ /**
188
+ * A provider's answer as vectors, one per input and in order, each cut to
189
+ * `dim` where one is asked for. An answer short of a vector is a provider
190
+ * that did not do what it says, and throws.
191
+ */
192
+ export let answered = (
193
+ who: string,
194
+ input: string[],
195
+ got: number[][] | undefined,
196
+ dim?: number,
197
+ ): Float32Array[] => {
198
+ if (got?.length != input.length || got.some((v) => !v?.length)) {
199
+ throw new Error(
200
+ `@yaks/embedding: ${who} answered no vector for ${input.length} ` +
201
+ `input${input.length == 1 ? '' : 's'} — ${
202
+ JSON.stringify(got).slice(0, 200)
203
+ }`,
204
+ )
205
+ }
206
+ return got.map((v) => {
207
+ let vec = Float32Array.from(v)
208
+ return dim ? cut(vec, dim) : vec
209
+ })
210
+ }
211
+
212
+ /** An {@link Embedder} whose every answer comes later: one that asks a
213
+ * provider, so a caller may treat each `embed()` as a promise. */
214
+ export type Batched = Omit<Embedder, 'embed'> & {
215
+ embed: (text: string) => Promise<Float32Array>
216
+ }
217
+
218
+ /**
219
+ * An {@link Embedder} over a provider that answers many texts at once. Every
220
+ * `embed()` made together, before the microtasks already queued have run,
221
+ * rides one call of `ask`, split by {@link parts} into calls no larger than
222
+ * `load` allows. A refused batch is retried one text at a time, so each
223
+ * caller gets its own vector or refusal. `ask` answers a vector per text,
224
+ * in order ({@link answered}).
225
+ */
226
+ export let batched = (
227
+ model: string,
228
+ ask: Ask,
229
+ load: Load = {},
230
+ ): Batched => {
231
+ type Wait = {
232
+ text: string
233
+ ok: (v: Float32Array) => void
234
+ no: (e: unknown) => void
235
+ }
236
+ let waiting: Wait[] = []
237
+ // Send what was asked for together, a run at a time.
238
+ let flush = async (): Promise<void> => {
239
+ let all = waiting
240
+ waiting = []
241
+ let at = 0
242
+ for (
243
+ let run of parts(
244
+ all.map((w) => w.text),
245
+ load.count ?? COUNT,
246
+ load.load ?? LOAD,
247
+ load.measure,
248
+ )
249
+ ) {
250
+ let mine = all.slice(at, at += run.length)
251
+ try {
252
+ let got = await ask(run)
253
+ mine.forEach((w, i) => w.ok(got[i]))
254
+ } catch (error) {
255
+ // A refused batch reveals neither which text failed nor whether
256
+ // their combined size failed. Isolate each answer for every reader.
257
+ if (error instanceof Refused && mine.length > 1) {
258
+ for (let w of mine) {
259
+ try {
260
+ w.ok((await ask([w.text]))[0])
261
+ } catch (failure) {
262
+ w.no(failure)
263
+ }
264
+ }
265
+ } else {
266
+ for (let w of mine) w.no(error)
267
+ }
268
+ }
269
+ }
270
+ }
271
+ return {
272
+ model,
273
+ embed: (text) =>
274
+ new Promise((ok, no) => {
275
+ if (!waiting.length) queueMicrotask(flush)
276
+ waiting.push({ text: text.slice(0, load.chars ?? CHARS), ok, no })
277
+ }),
278
+ }
279
+ }
280
+
281
+ /** What asks a provider: texts in, a vector each out, in order. */
282
+ export type Ask = (input: string[]) => Promise<Float32Array[]>
283
+
284
+ /**
285
+ * `ask`, sent again after each of `waits` (default {@link retries}) while it
286
+ * fails other than {@link Refused}, since a refused input is refused every
287
+ * time. A failure that outlasts them throws once, as {@link Unanswered}.
288
+ *
289
+ * ```ts
290
+ * import { assertEquals, assertRejects } from '@std/assert'
291
+ * import { Unanswered } from './embedder.ts'
292
+ * let sent = 0
293
+ * let flaky = retrying('workers-ai', '@cf/m', () =>
294
+ * ++sent < 3 ? Promise.reject(Error('3048: Unknown internal error'))
295
+ * : Promise.resolve([new Float32Array([1])]), [0, 0])
296
+ * assertEquals([[...(await flaky(['x']))[0]], sent], [[1], 3])
297
+ * let down = retrying('workers-ai', '@cf/m', () =>
298
+ * Promise.reject(Error('4009: An internal server error occured.')), [0])
299
+ * let error = await assertRejects(() => down(['x', 'y']), Unanswered,
300
+ * '@yaks/embedding: workers-ai did not answer')
301
+ * assertEquals((error as Unanswered).context,
302
+ * { model: '@cf/m', texts: '2', tries: '2' })
303
+ * ```
304
+ */
305
+ export let retrying = (
306
+ provider: string,
307
+ model: string,
308
+ ask: Ask,
309
+ waits: readonly number[] = retries.waits,
310
+ wait = (ms: number): Promise<void> => new Promise((go) => setTimeout(go, ms)),
311
+ ): Ask =>
312
+ async (input) => {
313
+ for (let sent = 1;; sent++) {
314
+ try {
315
+ return await ask(input)
316
+ } catch (error) {
317
+ if (error instanceof Refused || error instanceof Withheld) throw error
318
+ if (sent > waits.length) {
319
+ let texts = String(input.length), tries = String(sent)
320
+ throw new Unanswered(provider, { model, texts, tries }, error)
321
+ }
322
+ let pause = waits[sent - 1]
323
+ if (pause > 0) await wait(pause)
324
+ }
325
+ }
326
+ }
327
+
328
+ /** `ask`, where one text asked alone and {@link Refused} is asked again as
329
+ * its opening half, up to `retries` times and down to `shortest`: a
330
+ * model that will not take a whole text still embeds what it can read of it. */
331
+ export let halving = (
332
+ ask: Ask,
333
+ { retries = Infinity, shortest = SHORTEST } = {},
334
+ ): Ask => {
335
+ let fit = async (input: string[], left: number): Promise<Float32Array[]> => {
336
+ try {
337
+ return await ask(input)
338
+ } catch (error) {
339
+ let [text] = input
340
+ if (
341
+ !(error instanceof Refused) || input.length > 1 ||
342
+ !left || text.length <= shortest
343
+ ) throw error
344
+ let half = text.length >> 1
345
+ if (/[\uDC00-\uDFFF]/.test(text[half])) half--
346
+ if (!half) throw error
347
+ return fit([text.slice(0, half)], left - 1)
348
+ }
349
+ }
350
+ return (input) => fit(input, retries)
351
+ }
352
+
353
+ /** An {@link Embedder} that asks a server for every vector, batching the
354
+ * calls made together. */
355
+ export let remote = (said: Remote): Batched => {
356
+ let root = said.base.trim().replace(/\/+$/, '')
357
+ let go: Fetch = said.fetch ?? (fetch as unknown as Fetch)
358
+ // One request: texts in, a vector each out, in order.
359
+ let ask: Ask = async (input) => {
360
+ let headers: Record<string, string> = {
361
+ 'content-type': 'application/json',
362
+ }
363
+ if (said.key) headers.authorization = `Bearer ${said.key}`
364
+ let res = await go(`${root}${PATH[said.api]}`, {
365
+ method: 'POST',
366
+ headers,
367
+ body: JSON.stringify({ model: said.model, input }),
368
+ signal: AbortSignal.timeout(said.timeout ?? 30_000),
369
+ })
370
+ let raw = await res.text()
371
+ if (!res.ok) {
372
+ let Fault = REFUSED.includes(res.status) ? Refused : Error
373
+ throw new Fault(
374
+ `@yaks/embedding: ${said.api} answered ${res.status} — ${
375
+ raw.slice(0, 200)
376
+ }`,
377
+ )
378
+ }
379
+ return answered(
380
+ said.api,
381
+ input,
382
+ vectorsOf(said.api, JSON.parse(raw)),
383
+ said.dim,
384
+ )
385
+ }
386
+ return batched(
387
+ said.space ?? space(said),
388
+ halving(retrying(said.api, said.model, ask, said.waits)),
389
+ said,
390
+ )
391
+ }
package/score.js ADDED
@@ -0,0 +1,46 @@
1
+ // Exact cosine ordering over vectors, independent of their storage.
2
+ import { cosine } from "./vector.js";
3
+ // Keep only the best `limit` scores. The root is the worst retained score;
4
+ // for equal scores, the higher owner id is worse, so a tie resolves the same
5
+ // way whichever vectors were read and in whatever order.
6
+ let worse = (a, b)=>a.similarity < b.similarity || a.similarity == b.similarity && a.owner > b.owner;
7
+ let push = (heap, hit)=>{
8
+ let i = heap.length;
9
+ heap.push(hit);
10
+ while(i){
11
+ let p = i - 1 >> 1;
12
+ if (!worse(hit, heap[p])) break;
13
+ heap[i] = heap[p];
14
+ i = p;
15
+ }
16
+ heap[i] = hit;
17
+ };
18
+ let replace = (heap, hit)=>{
19
+ let i = 0;
20
+ while(2 * i + 1 < heap.length){
21
+ let child = 2 * i + 1;
22
+ if (child + 1 < heap.length && worse(heap[child + 1], heap[child])) {
23
+ child++;
24
+ }
25
+ if (!worse(heap[child], hit)) break;
26
+ heap[i] = heap[child];
27
+ i = child;
28
+ }
29
+ heap[i] = hit;
30
+ };
31
+ /** The nearest vectors, bounded by count and similarity; ties keep the lower owner. */ export let scored = (query, vectors, { limit = 8, floor = 0, without } = {})=>{
32
+ if (limit <= 0) return [];
33
+ let heap = [];
34
+ for (let { owner, vector } of vectors){
35
+ if (owner == without) continue;
36
+ let hit = {
37
+ owner,
38
+ similarity: cosine(query, vector)
39
+ };
40
+ if (!(hit.similarity >= floor)) continue;
41
+ if (heap.length < limit) push(heap, hit);
42
+ else if (worse(heap[0], hit)) replace(heap, hit);
43
+ }
44
+ return heap.sort((a, b)=>b.similarity - a.similarity || a.owner - b.owner);
45
+ };
46
+ //# sourceMappingURL=score.js.map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AAM,EAAE,IAAI,QAAS;IACrC,IAAI,SAAS,SAAS;IACtB,IAAI,MAAM;MAAE;MAAO,YAAY,OAAO,OAAO;IAAQ;IACrD,IAAI,CAAC,CAAC,IAAI,UAAU,IAAI,KAAK,GAAG;IAChC,IAAI,KAAK,MAAM,GAAG,OAAO,KAAK,MAAM;SAC/B,IAAI,MAAM,IAAI,CAAC,EAAE,EAAE,MAAM,QAAQ,MAAM;EAC9C;EACA,OAAO,KAAK,IAAI,CAAC,CAAC,GAAG,IAAM,EAAE,UAAU,GAAG,EAAE,UAAU,IAAI,EAAE,KAAK,GAAG,EAAE,KAAK;AAC7E,EAAC"}
package/score.ts ADDED
@@ -0,0 +1,60 @@
1
+ // Exact cosine ordering over vectors, independent of their storage.
2
+ import { cosine } from './vector.js'
3
+
4
+ export type Vector = { owner: number; vector: Float32Array | Int8Array }
5
+ export type Scored = { owner: number; similarity: number }
6
+
7
+ // Keep only the best `limit` scores. The root is the worst retained score;
8
+ // for equal scores, the higher owner id is worse, so a tie resolves the same
9
+ // way whichever vectors were read and in whatever order.
10
+ let worse = (a: Scored, b: Scored) =>
11
+ a.similarity < b.similarity ||
12
+ (a.similarity == b.similarity && a.owner > b.owner)
13
+
14
+ let push = (heap: Scored[], hit: Scored) => {
15
+ let i = heap.length
16
+ heap.push(hit)
17
+ while (i) {
18
+ let p = (i - 1) >> 1
19
+ if (!worse(hit, heap[p])) break
20
+ heap[i] = heap[p]
21
+ i = p
22
+ }
23
+ heap[i] = hit
24
+ }
25
+
26
+ let replace = (heap: Scored[], hit: Scored) => {
27
+ let i = 0
28
+ while (2 * i + 1 < heap.length) {
29
+ let child = 2 * i + 1
30
+ if (child + 1 < heap.length && worse(heap[child + 1], heap[child])) {
31
+ child++
32
+ }
33
+ if (!worse(heap[child], hit)) break
34
+ heap[i] = heap[child]
35
+ i = child
36
+ }
37
+ heap[i] = hit
38
+ }
39
+
40
+ /** The nearest vectors, bounded by count and similarity; ties keep the lower owner. */
41
+ export let scored = (
42
+ query: Float32Array,
43
+ vectors: Iterable<Vector>,
44
+ { limit = 8, floor = 0, without }: {
45
+ limit?: number
46
+ floor?: number
47
+ without?: number
48
+ } = {},
49
+ ): Scored[] => {
50
+ if (limit <= 0) return []
51
+ let heap: Scored[] = []
52
+ for (let { owner, vector } of vectors) {
53
+ if (owner == without) continue
54
+ let hit = { owner, similarity: cosine(query, vector) }
55
+ if (!(hit.similarity >= floor)) continue
56
+ if (heap.length < limit) push(heap, hit)
57
+ else if (worse(heap[0], hit)) replace(heap, hit)
58
+ }
59
+ return heap.sort((a, b) => b.similarity - a.similarity || a.owner - b.owner)
60
+ }
package/search.js ADDED
@@ -0,0 +1,65 @@
1
+ // A person's words in, the nearest stored texts out. The embedder makes the
2
+ // query vector; the stored vectors and their source text stay in this package.
3
+ import { absentFrom } from "@yaks/sql";
4
+ import { present, tablesIn } from "./fields.js";
5
+ import { nearest } from "./near.js";
6
+ import { sources } from "./sweep.js";
7
+ import { screened, visibleVectors } from "./visibility.js";
8
+ import { context, during } from "@yaks/trace";
9
+ // One step of a search, as a phase of the span it runs under (./graph.ts
10
+ // `meaning`), so a search that runs long says which step it was in. The
11
+ // context is the one the search began in, which an await would otherwise
12
+ // lose where the host installs no carrier.
13
+ let phase = (at, name, run)=>at ? during(at.channel.begin({
14
+ kind: 'phase',
15
+ name,
16
+ package: '@yaks/embedding',
17
+ parent: at.parent
18
+ }), run) : run();
19
+ /** A short piece of the text that made an entity's vector. */ export let excerpt = (text, size = 180)=>{
20
+ let line = '', gap = false;
21
+ for(let i = 0; i < text.length; i++){
22
+ if (/\s/.test(text[i])) {
23
+ gap = !!line;
24
+ continue;
25
+ }
26
+ if (gap) line += ' ';
27
+ gap = false;
28
+ line += text[i];
29
+ if (line.length > size) break;
30
+ }
31
+ if (line.length <= size) return line;
32
+ let cut = line.slice(0, size).replace(/\s+\S*$/, '');
33
+ return `${cut || line.slice(0, size)}…`;
34
+ };
35
+ /** Search stored vectors with new words, then read only the hits' source text.
36
+ * `fields` must be the configured fields, resolved through any derived text
37
+ * expressions that fed the stored vectors. */ export let meaning = async (db, fields, embedder, words, opts = {})=>{
38
+ if (!words.trim() || !fields.length || (opts.limit ?? 20) <= 0) return [];
39
+ let at = context();
40
+ if (opts.visibility && !opts.vocab) {
41
+ throw new Error('meaning search with visibility requires a vocabulary');
42
+ }
43
+ // A component no table stands for yet is worn by nobody (@yaks/sqlite
44
+ // makes one on its first write).
45
+ let v = opts.vocab;
46
+ let visible = v ? visibleVectors(v, present(db, fields), opts.visibility, absentFrom(v, tablesIn(db))) : undefined;
47
+ let vector = await phase(at, 'embed', ()=>embedder.embed(words));
48
+ let found = phase(at, 'rank', ()=>nearest(db, vector, {
49
+ model: embedder.model,
50
+ limit: opts.limit ?? 20,
51
+ floor: opts.floor,
52
+ within: screened(opts.screen?.(), visible)
53
+ }));
54
+ if (!found.length) return [];
55
+ let text = phase(at, 'excerpts', ()=>new Map(sources(db, fields, found.map((h)=>h.owner)).map((s)=>[
56
+ s.owner,
57
+ excerpt(s.text)
58
+ ])));
59
+ return found.map((h)=>({
60
+ entity: h.entity,
61
+ similarity: h.similarity,
62
+ excerpt: text.get(h.owner) ?? ''
63
+ }));
64
+ };
65
+ //# sourceMappingURL=search.js.map
package/search.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"search.js","sources":["./search.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,+EAA+E;AAG/E,SACE,UAAU,yBAIiB;AAG7B,SAAqB,OAAO,EAAE,QAAQ,sBAAqB;AAC3D,SAAS,OAAO,oBAAmB;AACnC,SAAS,OAAO,qBAAoB;AACpC,SAAS,QAAQ,EAAE,cAAc,0BAAyB;AAC1D,SAAuB,OAAO,EAAE,MAAM,2BAAgC;AAEtE,yEAAyE;AACzE,wEAAwE;AACxE,yEAAyE;AACzE,2CAA2C;AAC3C,IAAI,QAAQ,CAAI,IAAyB,MAAc,MACrD,KACI,OACA,GAAG,OAAO,CAAC,KAAK,CAAC;IACf,M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,IAAI;MACrB,OAAO,KAAK,KAAK;MACjB,QAAQ,SAAS,KAAK,MAAM,MAAM;IACpC;EACF,IAAI,CAAC,MAAM,MAAM,EAAE,OAAO,EAAE;EAC5B,IAAI,OAAO,MAAM,IAAI,YAAY,IAC/B,IAAI,IACF,QAAQ,IAAI,QAAQ,MAAM,GAAG,CAAC,CAAC,IAAM,EAAE,KAAK,GACzC,GAAG,CAAC,CAAC,IAAM;QAAC,EAAE,KAAK;QAAE,QAAQ,EAAE,IAAI;OAAE;EAE5C,OAAO,MAAM,GAAG,CAAC,CAAC,IAAM,CAAC;MACvB,QAAQ,EAAE,MAAM;MAChB,YAAY,EAAE,UAAU;MACxB,SAAS,KAAK,GAAG,CAAC,EAAE,KAAK,KAAK;IAChC,CAAC;AACH,EAAC"}
package/search.ts ADDED
@@ -0,0 +1,118 @@
1
+ // A person's words in, the nearest stored texts out. The embedder makes the
2
+ // query vector; the stored vectors and their source text stay in this package.
3
+
4
+ import type { Eid } from 'jsr:@yaks/graph@0.2.36'
5
+ import {
6
+ absentFrom,
7
+ type BindOpts,
8
+ type Screen,
9
+ type Statements,
10
+ } from '@yaks/sql'
11
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
12
+ import type { Embedder } from './embedder.ts'
13
+ import { type Field, present, tablesIn } from './fields.js'
14
+ import { nearest } from './near.js'
15
+ import { sources } from './sweep.js'
16
+ import { screened, visibleVectors } from './visibility.js'
17
+ import { type Context, context, during } from '@yaks/trace'
18
+
19
+ // One step of a search, as a phase of the span it runs under (./graph.ts
20
+ // `meaning`), so a search that runs long says which step it was in. The
21
+ // context is the one the search began in, which an await would otherwise
22
+ // lose where the host installs no carrier.
23
+ let phase = <T>(at: Context | undefined, name: string, run: () => T): T =>
24
+ at
25
+ ? during(
26
+ at.channel.begin({
27
+ kind: 'phase',
28
+ name,
29
+ package: '@yaks/embedding',
30
+ parent: at.parent,
31
+ }),
32
+ run,
33
+ )
34
+ : run()
35
+
36
+ /** One match by meaning. Its excerpt is unmarked: the words need not occur. */
37
+ export type Hit = {
38
+ entity: Eid
39
+ similarity: number
40
+ excerpt: string
41
+ }
42
+
43
+ export type MeaningOpts = {
44
+ /** Vocabulary and visibility of the person asking, when the read is scoped. */
45
+ vocab?: Vocab
46
+ visibility?: BindOpts['visibility']
47
+ limit?: number
48
+ floor?: number
49
+ /** the entities a hit must be among, as a statement selecting their ids
50
+ * (@yaks/sql `Screen`): asked for once the words are embedded, so it is
51
+ * compiled against the rows the search then reads */
52
+ screen?: Screen
53
+ }
54
+
55
+ /** A short piece of the text that made an entity's vector. */
56
+ export let excerpt = (text: string, size = 180): string => {
57
+ let line = '', gap = false
58
+ for (let i = 0; i < text.length; i++) {
59
+ if (/\s/.test(text[i])) {
60
+ gap = !!line
61
+ continue
62
+ }
63
+ if (gap) line += ' '
64
+ gap = false
65
+ line += text[i]
66
+ if (line.length > size) break
67
+ }
68
+ if (line.length <= size) return line
69
+ let cut = line.slice(0, size).replace(/\s+\S*$/, '')
70
+ return `${cut || line.slice(0, size)}…`
71
+ }
72
+
73
+ /** Search stored vectors with new words, then read only the hits' source text.
74
+ * `fields` must be the configured fields, resolved through any derived text
75
+ * expressions that fed the stored vectors. */
76
+ export let meaning = async (
77
+ db: Statements,
78
+ fields: Field[],
79
+ embedder: Embedder,
80
+ words: string,
81
+ opts: MeaningOpts = {},
82
+ ): Promise<Hit[]> => {
83
+ if (!words.trim() || !fields.length || (opts.limit ?? 20) <= 0) return []
84
+ let at = context()
85
+ if (opts.visibility && !opts.vocab) {
86
+ throw new Error('meaning search with visibility requires a vocabulary')
87
+ }
88
+ // A component no table stands for yet is worn by nobody (@yaks/sqlite
89
+ // makes one on its first write).
90
+ let v = opts.vocab
91
+ let visible = v
92
+ ? visibleVectors(
93
+ v,
94
+ present(db, fields),
95
+ opts.visibility,
96
+ absentFrom(v, tablesIn(db)),
97
+ )
98
+ : undefined
99
+ let vector = await phase(at, 'embed', () => embedder.embed(words))
100
+ let found = phase(at, 'rank', () =>
101
+ nearest(db, vector, {
102
+ model: embedder.model,
103
+ limit: opts.limit ?? 20,
104
+ floor: opts.floor,
105
+ within: screened(opts.screen?.(), visible),
106
+ }))
107
+ if (!found.length) return []
108
+ let text = phase(at, 'excerpts', () =>
109
+ new Map(
110
+ sources(db, fields, found.map((h) => h.owner))
111
+ .map((s) => [s.owner, excerpt(s.text)]),
112
+ ))
113
+ return found.map((h) => ({
114
+ entity: h.entity,
115
+ similarity: h.similarity,
116
+ excerpt: text.get(h.owner) ?? '',
117
+ }))
118
+ }