@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/image.js ADDED
@@ -0,0 +1,202 @@
1
+ import { and, at, col, eq, exists, join, lit, not, populated, select, table, val } from "@yaks/sql";
2
+ import { admitted } from "./native.js";
3
+ import { scored } from "./score.js";
4
+ import { pack, unit, unpack } from "./vector.js";
5
+ let IMAGES = 'image_embedding';
6
+ /** Whether a store has vectors already, without creating an index. */ export let hasImages = (db)=>populated(db, IMAGES);
7
+ /** The image vector space of one store. Vectors live in derived storage and
8
+ * never in a bundle, journal entry or call result. Text sweeps own their
9
+ * separate index, including when both sources describe the same entity. */ export let imageIndex = (db, model)=>{
10
+ let images = IMAGES, i = at('i'), e = at('e');
11
+ let from = table(images, 'i');
12
+ let joins = [
13
+ join(table('entity', 'e'), eq(e('id'), i('owner')))
14
+ ];
15
+ let gone = table('tombstone', 't');
16
+ let live = not(exists(select({
17
+ cols: [
18
+ lit(1)
19
+ ],
20
+ from: gone,
21
+ where: eq(col('entity', 't'), i('owner'))
22
+ })));
23
+ let matching = eq(i('model'), val(model));
24
+ let ready = -1;
25
+ let ensure = ()=>{
26
+ let now = db.revision('schema');
27
+ if (ready == now) return;
28
+ db.query({
29
+ t: 'create table',
30
+ name: images,
31
+ ifNot: true,
32
+ cols: [
33
+ {
34
+ name: 'owner',
35
+ type: 'integer',
36
+ notNull: true,
37
+ ref: {
38
+ table: 'entity',
39
+ cols: [
40
+ 'id'
41
+ ]
42
+ }
43
+ },
44
+ {
45
+ name: 'model',
46
+ type: 'text',
47
+ notNull: true
48
+ },
49
+ {
50
+ name: 'vec',
51
+ type: 'blob',
52
+ notNull: true
53
+ }
54
+ ],
55
+ keys: [
56
+ {
57
+ pk: [
58
+ 'owner',
59
+ 'model'
60
+ ]
61
+ }
62
+ ]
63
+ });
64
+ db.query({
65
+ t: 'create trigger',
66
+ name: 'image_embedding_tombstone',
67
+ ifNot: true,
68
+ timing: 'after',
69
+ event: 'insert',
70
+ on: 'tombstone',
71
+ body: [
72
+ {
73
+ t: 'delete',
74
+ from: images,
75
+ where: eq(col('owner'), col('entity', 'new'))
76
+ }
77
+ ]
78
+ });
79
+ ready = db.revision('schema');
80
+ };
81
+ let every = (eid, within)=>{
82
+ ensure();
83
+ return db.query(select({
84
+ cols: [
85
+ i('owner'),
86
+ e('eid'),
87
+ i('vec')
88
+ ],
89
+ from,
90
+ joins,
91
+ where: and(matching, live, ...eid ? [
92
+ eq(e('eid'), val(eid))
93
+ ] : [], ...within ? [
94
+ admitted(within, i('owner'))
95
+ ] : [])
96
+ }));
97
+ };
98
+ let owners = (eid)=>select({
99
+ cols: [
100
+ col('id')
101
+ ],
102
+ from: table('entity'),
103
+ where: eq(col('eid'), val(eid))
104
+ });
105
+ let putAll = async (vectors)=>await db.atomic(()=>{
106
+ ensure();
107
+ let saved = new Set();
108
+ for (let [eid, vector] of vectors){
109
+ let owned = owners(eid);
110
+ let rows = db.query({
111
+ t: 'insert',
112
+ into: images,
113
+ cols: [
114
+ 'owner',
115
+ 'model',
116
+ 'vec'
117
+ ],
118
+ q: {
119
+ ...owned,
120
+ cols: [
121
+ col('id'),
122
+ val(model),
123
+ val(pack(unit(vector)))
124
+ ],
125
+ where: and(owned.where, not(exists(select({
126
+ cols: [
127
+ lit(1)
128
+ ],
129
+ from: gone,
130
+ where: eq(col('entity', 't'), col('id', 'entity'))
131
+ }))))
132
+ },
133
+ upsert: [
134
+ {
135
+ on: [
136
+ col('owner'),
137
+ col('model')
138
+ ],
139
+ set: {
140
+ vec: col('vec', 'excluded')
141
+ }
142
+ }
143
+ ],
144
+ returning: [
145
+ col('owner')
146
+ ]
147
+ });
148
+ if (rows.length) saved.add(eid);
149
+ }
150
+ return saved;
151
+ });
152
+ return {
153
+ get: (eid, within)=>{
154
+ let [row] = every(eid, within);
155
+ return row ? unpack(row.vec) : null;
156
+ },
157
+ nearest: (query, limit, within)=>{
158
+ let rows = every(undefined, within);
159
+ let ids = new Map(rows.map((row)=>[
160
+ Number(row.owner),
161
+ String(row.eid)
162
+ ]));
163
+ let ranked = scored(query, rows.map((row)=>({
164
+ owner: Number(row.owner),
165
+ vector: unpack(row.vec)
166
+ })), {
167
+ limit
168
+ });
169
+ return ranked.map((row)=>({
170
+ ...row,
171
+ entity: ids.get(row.owner)
172
+ }));
173
+ },
174
+ put: async (eid, vector)=>(await putAll(new Map([
175
+ [
176
+ eid,
177
+ vector
178
+ ]
179
+ ]))).has(eid),
180
+ putAll,
181
+ drop: (eid)=>{
182
+ ensure();
183
+ let [row] = db.query(owners(eid));
184
+ if (row) {
185
+ db.query({
186
+ t: 'delete',
187
+ from: images,
188
+ where: and(eq(col('owner'), val(Number(row.id))), eq(col('model'), val(model)))
189
+ });
190
+ }
191
+ },
192
+ clear: ()=>{
193
+ ensure();
194
+ db.query({
195
+ t: 'delete',
196
+ from: images,
197
+ where: eq(col('model'), val(model))
198
+ });
199
+ }
200
+ };
201
+ };
202
+ //# sourceMappingURL=image.js.map
package/image.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"image.js","sources":["./image.ts"],"names":[],"mappings":"AACA,SACE,GAAG,EACH,EA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 at,
5
+ col,
6
+ eq,
7
+ exists,
8
+ join,
9
+ lit,
10
+ not,
11
+ populated,
12
+ select,
13
+ type Statements,
14
+ table,
15
+ val,
16
+ } from '@yaks/sql'
17
+ import { admitted } from './native.js'
18
+ import type { Near, Rank, Screen } from './near.ts'
19
+ import { scored } from './score.js'
20
+ import { pack, unit, unpack } from './vector.js'
21
+
22
+ /** Bytes of an image with the media type its embedder consumes. */
23
+ export type ImageInput = { bytes: Uint8Array; mediaType: string }
24
+
25
+ export type ImageIndex = {
26
+ get: (eid: Eid, within?: Screen) => Float32Array | null
27
+ nearest: Rank
28
+ put: (eid: Eid, vector: Float32Array) => Promise<boolean>
29
+ putAll: (vectors: Map<Eid, Float32Array>) => Promise<Set<Eid>>
30
+ drop: (eid: Eid) => void
31
+ clear: () => void
32
+ }
33
+
34
+ let IMAGES = 'image_embedding'
35
+
36
+ /** Whether a store has vectors already, without creating an index. */
37
+ export let hasImages = (db: Pick<Statements, 'query'>): boolean =>
38
+ populated(db, IMAGES)
39
+
40
+ /** The image vector space of one store. Vectors live in derived storage and
41
+ * never in a bundle, journal entry or call result. Text sweeps own their
42
+ * separate index, including when both sources describe the same entity. */
43
+ export let imageIndex = (db: Statements, model: string): ImageIndex => {
44
+ let images = IMAGES, i = at('i'), e = at('e')
45
+ let from = table(images, 'i')
46
+ let joins = [join(table('entity', 'e'), eq(e('id'), i('owner')))]
47
+ let gone = table('tombstone', 't')
48
+ let live = not(exists(select({
49
+ cols: [lit(1)],
50
+ from: gone,
51
+ where: eq(col('entity', 't'), i('owner')),
52
+ })))
53
+ let matching = eq(i('model'), val(model))
54
+ let ready = -1
55
+ let ensure = () => {
56
+ let now = db.revision('schema')
57
+ if (ready == now) return
58
+ db.query({
59
+ t: 'create table',
60
+ name: images,
61
+ ifNot: true,
62
+ cols: [
63
+ {
64
+ name: 'owner',
65
+ type: 'integer',
66
+ notNull: true,
67
+ ref: { table: 'entity', cols: ['id'] },
68
+ },
69
+ { name: 'model', type: 'text', notNull: true },
70
+ { name: 'vec', type: 'blob', notNull: true },
71
+ ],
72
+ keys: [{ pk: ['owner', 'model'] }],
73
+ })
74
+ db.query({
75
+ t: 'create trigger',
76
+ name: 'image_embedding_tombstone',
77
+ ifNot: true,
78
+ timing: 'after',
79
+ event: 'insert',
80
+ on: 'tombstone',
81
+ body: [{
82
+ t: 'delete',
83
+ from: images,
84
+ where: eq(col('owner'), col('entity', 'new')),
85
+ }],
86
+ })
87
+ ready = db.revision('schema')
88
+ }
89
+ let every = (eid?: Eid, within?: Screen) => {
90
+ ensure()
91
+ return db.query(select({
92
+ cols: [i('owner'), e('eid'), i('vec')],
93
+ from,
94
+ joins,
95
+ where: and(
96
+ matching,
97
+ live,
98
+ ...eid ? [eq(e('eid'), val(eid))] : [],
99
+ ...within ? [admitted(within, i('owner'))] : [],
100
+ ),
101
+ }))
102
+ }
103
+ let owners = (eid: Eid) =>
104
+ select({
105
+ cols: [col('id')],
106
+ from: table('entity'),
107
+ where: eq(col('eid'), val(eid)),
108
+ })
109
+ let putAll = async (vectors: Map<Eid, Float32Array>) =>
110
+ await db.atomic(() => {
111
+ ensure()
112
+ let saved = new Set<Eid>()
113
+ for (let [eid, vector] of vectors) {
114
+ let owned = owners(eid)
115
+ let rows = db.query({
116
+ t: 'insert',
117
+ into: images,
118
+ cols: ['owner', 'model', 'vec'],
119
+ q: {
120
+ ...owned,
121
+ cols: [col('id'), val(model), val(pack(unit(vector)))],
122
+ where: and(
123
+ owned.where!,
124
+ not(exists(select({
125
+ cols: [lit(1)],
126
+ from: gone,
127
+ where: eq(col('entity', 't'), col('id', 'entity')),
128
+ }))),
129
+ ),
130
+ },
131
+ upsert: [{
132
+ on: [col('owner'), col('model')],
133
+ set: { vec: col('vec', 'excluded') },
134
+ }],
135
+ returning: [col('owner')],
136
+ })
137
+ if (rows.length) saved.add(eid)
138
+ }
139
+ return saved
140
+ })
141
+ return {
142
+ get: (eid, within) => {
143
+ let [row] = every(eid, within)
144
+ return row ? unpack(row.vec as Uint8Array) : null
145
+ },
146
+ nearest: (query, limit, within): Near[] => {
147
+ let rows = every(undefined, within)
148
+ let ids = new Map(rows.map((row) => [Number(row.owner), String(row.eid)]))
149
+ let ranked = scored(
150
+ query,
151
+ rows.map((row) => ({
152
+ owner: Number(row.owner),
153
+ vector: unpack(row.vec as Uint8Array),
154
+ })),
155
+ { limit },
156
+ )
157
+ return ranked.map((row) => ({ ...row, entity: ids.get(row.owner)! }))
158
+ },
159
+ put: async (eid, vector) =>
160
+ (await putAll(new Map([[eid, vector]]))).has(eid),
161
+ putAll,
162
+ drop: (eid) => {
163
+ ensure()
164
+ let [row] = db.query(owners(eid))
165
+ if (row) {
166
+ db.query({
167
+ t: 'delete',
168
+ from: images,
169
+ where: and(
170
+ eq(col('owner'), val(Number(row.id))),
171
+ eq(col('model'), val(model)),
172
+ ),
173
+ })
174
+ }
175
+ },
176
+ clear: () => {
177
+ ensure()
178
+ db.query({
179
+ t: 'delete',
180
+ from: images,
181
+ where: eq(col('model'), val(model)),
182
+ })
183
+ },
184
+ }
185
+ }
package/mod.js ADDED
@@ -0,0 +1,105 @@
1
+ /**
2
+ * @yaks/embedding — semantic search for a yaks graph: the entities nearest in
3
+ * meaning, beside the literal matches full-text gives.
4
+ *
5
+ * Full-text search finds the word you typed. This finds the book you meant. A
6
+ * vector is stored for every entity that has text, and `.near=<entity>` ranks
7
+ * the graph by how close each one is to that entity's vector — which is how
8
+ * "more like this", "related reading" and "you may already have written this"
9
+ * are all the same query.
10
+ *
11
+ * It is generic over the text, exactly as {@link https://jsr.io/@yaks/fts |
12
+ * @yaks/fts} is: a vocabulary declares components, some of their properties
13
+ * hold prose, and {@link fields} chooses which of them a vector is made from.
14
+ * An entity gets one vector, made from all of its text fields joined together —
15
+ * a vector is a point in a space of meanings, and an entity is one thing.
16
+ *
17
+ * Six small pieces, each usable alone:
18
+ *
19
+ * - {@link fields} reads the embedded properties off a
20
+ * {@link https://jsr.io/@yaks/vocab | @yaks/vocab} schema;
21
+ * - {@link schema} returns the statements for the table the vectors live in,
22
+ * its update queue, and the generation of vectors held in memory;
23
+ * - {@link sweep} embeds what changed and drops what left, off the write path,
24
+ * reading what moved from a queue the database's own triggers keep
25
+ * ({@link watch});
26
+ * - {@link nearest} ranks the stored vectors against a query vector;
27
+ * - {@link meaning} embeds a new phrase and returns nearby entities with
28
+ * excerpts from the text that made their vectors;
29
+ * - {@link semantic} — the {@link https://jsr.io/@yaks/sql | @yaks/sql}
30
+ * extension — compiles `.near=<entity>` and `.order=similar` into that
31
+ * ranking, so a neighbourhood combines with ordinary filters in one query.
32
+ *
33
+ * ```ts
34
+ * import { loadVocab } from '@yaks/vocab'
35
+ * import { graph } from '@yaks/graph'
36
+ * import { statements, storage } from '@yaks/sqlite'
37
+ * import { open } from '@yaks/sqlite/db'
38
+ * import {
39
+ * fields,
40
+ * hashEmbedder,
41
+ * schema,
42
+ * semantic,
43
+ * sweep,
44
+ * } from '@yaks/embedding'
45
+ *
46
+ * let title = { type: 'string', search: true }
47
+ * let price = { type: 'number' }
48
+ * let shop = loadVocab([{
49
+ * $defs: { book: { component: true, properties: { title, price } } },
50
+ * }])
51
+ * let driver = open(':memory:')
52
+ * let db = statements(driver)
53
+ * for (let stmt of storage(driver, shop).ddl()) db.query(stmt)
54
+ * graph({ storage: storage(driver, shop), vocab: shop }).apply([
55
+ * { entity: { eid: 'book-1' }, book: { title: 'The Hobbit', price: 12 } },
56
+ * { entity: { eid: 'book-2' }, book: { title: 'Farmer Giles', price: 9 } },
57
+ * ])
58
+ *
59
+ * let text = fields(shop) // every text property the vocabulary declares
60
+ * for (let stmt of schema()) db.query(stmt)
61
+ *
62
+ * let embedder = hashEmbedder() // swap in a model when you have one
63
+ * await sweep(db, text, embedder) // keeps the vectors in step with the text
64
+ *
65
+ * // the books most like this one, still under the rest of the query's filters
66
+ * let near = semantic(db, embedder)
67
+ * let store = storage(driver, shop, { extend: [near] })
68
+ * let hits = near.rank(store.read('.near=book-1&.order=similar .book.price<20'))
69
+ * // each with a `rank.score`
70
+ * ```
71
+ *
72
+ * The embedder is injected — {@link hashEmbedder} is the deterministic,
73
+ * offline one shipped here and {@link remote} is one over HTTP, so tests and
74
+ * early development never reach a network. `.near` reads a stored vector
75
+ * synchronously; searching new words embeds them asynchronously.
76
+ *
77
+ * As a plugin, `./graph` creates the vector table, registers the `.near`
78
+ * compiler and answers phrase searches; `./service` settles the queue. A
79
+ * provider and a model are named beside the plugin in the config, and a
80
+ * provider reached over HTTP is a `provider` row serving the `model` row
81
+ * (@yaks/model). It declares no component — no client ever writes a vector.
82
+ *
83
+ * It assumes the storage layout @yaks/sql's SQLite dialect reads and
84
+ * {@link https://jsr.io/@yaks/sqlite | @yaks/sqlite} creates: an `entity`
85
+ * table of integer ids, one table per component keyed by an `entity` owner,
86
+ * and a `tombstone` table listing deleted entities.
87
+ *
88
+ * @module
89
+ */ export * from "./vector.js";
90
+ export * from "./embedder.js";
91
+ export * from "./remote.js";
92
+ export * from "./fields.js";
93
+ export * from "./ddl.js";
94
+ export * from "./sweep.js";
95
+ export * from "./sleeper.js";
96
+ export * from "./outage.js";
97
+ export * from "./owed.js";
98
+ export * from "./near.js";
99
+ export { absorb, FOLLOW, HELD, RESCORE, SHARED } from "./held.js";
100
+ export { install as installNative, prepare, state } from "./native.js";
101
+ export * from "./search.js";
102
+ export * from "./compile.js";
103
+ export { scored } from "./score.js";
104
+ export * from "./image.js";
105
+ //# sourceMappingURL=mod.js.map
package/mod.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","sources":["./mod.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwFC,GAED,4BAA2B;AAC3B,8BAA6B;AAC7B,4BAA2B;AAC3B,4BAA2B;AAC3B,yBAAwB;AACxB,2BAA0B;AAC1B,6BAA4B;AAC5B,4BAA2B;AAC3B,0BAAyB;AACzB,0BAAyB;AACzB,SAAS,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,oBAAmB;AACjE,SAEE,WAAW,aAAa,EACxB,OAAO,EAEP,KAAK,sBACa;AACpB,4BAA2B;AAC3B,6BAA4B;AAE5B,SAAsB,MAAM,qBAAiC;AAC7D,2BAA0B"}
package/mod.ts ADDED
@@ -0,0 +1,113 @@
1
+ /**
2
+ * @yaks/embedding — semantic search for a yaks graph: the entities nearest in
3
+ * meaning, beside the literal matches full-text gives.
4
+ *
5
+ * Full-text search finds the word you typed. This finds the book you meant. A
6
+ * vector is stored for every entity that has text, and `.near=<entity>` ranks
7
+ * the graph by how close each one is to that entity's vector — which is how
8
+ * "more like this", "related reading" and "you may already have written this"
9
+ * are all the same query.
10
+ *
11
+ * It is generic over the text, exactly as {@link https://jsr.io/@yaks/fts |
12
+ * @yaks/fts} is: a vocabulary declares components, some of their properties
13
+ * hold prose, and {@link fields} chooses which of them a vector is made from.
14
+ * An entity gets one vector, made from all of its text fields joined together —
15
+ * a vector is a point in a space of meanings, and an entity is one thing.
16
+ *
17
+ * Six small pieces, each usable alone:
18
+ *
19
+ * - {@link fields} reads the embedded properties off a
20
+ * {@link https://jsr.io/@yaks/vocab | @yaks/vocab} schema;
21
+ * - {@link schema} returns the statements for the table the vectors live in,
22
+ * its update queue, and the generation of vectors held in memory;
23
+ * - {@link sweep} embeds what changed and drops what left, off the write path,
24
+ * reading what moved from a queue the database's own triggers keep
25
+ * ({@link watch});
26
+ * - {@link nearest} ranks the stored vectors against a query vector;
27
+ * - {@link meaning} embeds a new phrase and returns nearby entities with
28
+ * excerpts from the text that made their vectors;
29
+ * - {@link semantic} — the {@link https://jsr.io/@yaks/sql | @yaks/sql}
30
+ * extension — compiles `.near=<entity>` and `.order=similar` into that
31
+ * ranking, so a neighbourhood combines with ordinary filters in one query.
32
+ *
33
+ * ```ts
34
+ * import { loadVocab } from '@yaks/vocab'
35
+ * import { graph } from '@yaks/graph'
36
+ * import { statements, storage } from '@yaks/sqlite'
37
+ * import { open } from '@yaks/sqlite/db'
38
+ * import {
39
+ * fields,
40
+ * hashEmbedder,
41
+ * schema,
42
+ * semantic,
43
+ * sweep,
44
+ * } from '@yaks/embedding'
45
+ *
46
+ * let title = { type: 'string', search: true }
47
+ * let price = { type: 'number' }
48
+ * let shop = loadVocab([{
49
+ * $defs: { book: { component: true, properties: { title, price } } },
50
+ * }])
51
+ * let driver = open(':memory:')
52
+ * let db = statements(driver)
53
+ * for (let stmt of storage(driver, shop).ddl()) db.query(stmt)
54
+ * graph({ storage: storage(driver, shop), vocab: shop }).apply([
55
+ * { entity: { eid: 'book-1' }, book: { title: 'The Hobbit', price: 12 } },
56
+ * { entity: { eid: 'book-2' }, book: { title: 'Farmer Giles', price: 9 } },
57
+ * ])
58
+ *
59
+ * let text = fields(shop) // every text property the vocabulary declares
60
+ * for (let stmt of schema()) db.query(stmt)
61
+ *
62
+ * let embedder = hashEmbedder() // swap in a model when you have one
63
+ * await sweep(db, text, embedder) // keeps the vectors in step with the text
64
+ *
65
+ * // the books most like this one, still under the rest of the query's filters
66
+ * let near = semantic(db, embedder)
67
+ * let store = storage(driver, shop, { extend: [near] })
68
+ * let hits = near.rank(store.read('.near=book-1&.order=similar .book.price<20'))
69
+ * // each with a `rank.score`
70
+ * ```
71
+ *
72
+ * The embedder is injected — {@link hashEmbedder} is the deterministic,
73
+ * offline one shipped here and {@link remote} is one over HTTP, so tests and
74
+ * early development never reach a network. `.near` reads a stored vector
75
+ * synchronously; searching new words embeds them asynchronously.
76
+ *
77
+ * As a plugin, `./graph` creates the vector table, registers the `.near`
78
+ * compiler and answers phrase searches; `./service` settles the queue. A
79
+ * provider and a model are named beside the plugin in the config, and a
80
+ * provider reached over HTTP is a `provider` row serving the `model` row
81
+ * (@yaks/model). It declares no component — no client ever writes a vector.
82
+ *
83
+ * It assumes the storage layout @yaks/sql's SQLite dialect reads and
84
+ * {@link https://jsr.io/@yaks/sqlite | @yaks/sqlite} creates: an `entity`
85
+ * table of integer ids, one table per component keyed by an `entity` owner,
86
+ * and a `tombstone` table listing deleted entities.
87
+ *
88
+ * @module
89
+ */
90
+
91
+ export * from './vector.js'
92
+ export * from './embedder.js'
93
+ export * from './remote.js'
94
+ export * from './fields.js'
95
+ export * from './ddl.js'
96
+ export * from './sweep.js'
97
+ export * from './sleeper.js'
98
+ export * from './outage.js'
99
+ export * from './owed.js'
100
+ export * from './near.js'
101
+ export { absorb, FOLLOW, HELD, RESCORE, SHARED } from './held.js'
102
+ export {
103
+ type Build,
104
+ install as installNative,
105
+ prepare,
106
+ type State,
107
+ state,
108
+ } from './native.js'
109
+ export * from './search.js'
110
+ export * from './compile.js'
111
+
112
+ export { type Scored, scored, type Vector } from './score.js'
113
+ export * from './image.js'