Elffuss BraidHub

kikocis/lancedb public

main · 9.2 KiBRawPermalink
1// Copyright 2024 Lance Developers.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15import * as tmp from "tmp";
16
17import { connect } from "../lancedb";
18import {
19 Field,
20 FixedSizeList,
21 Float,
22 Float16,
23 Float32,
24 Float64,
25 Schema,
26 Utf8,
27} from "../lancedb/arrow";
28import { EmbeddingFunction, LanceSchema } from "../lancedb/embedding";
29import { getRegistry, register } from "../lancedb/embedding/registry";
30
31describe("embedding functions", () => {
32 let tmpDir: tmp.DirResult;
33 beforeEach(() => {
34 tmpDir = tmp.dirSync({ unsafeCleanup: true });
35 });
36 afterEach(() => {
37 tmpDir.removeCallback();
38 getRegistry().reset();
39 });
40
41 it("should be able to create a table with an embedding function", async () => {
42 class MockEmbeddingFunction extends EmbeddingFunction<string> {
43 toJSON(): object {
44 return {};
45 }
46 ndims() {
47 return 3;
48 }
49 embeddingDataType(): Float {
50 return new Float32();
51 }
52 async computeQueryEmbeddings(_data: string) {
53 return [1, 2, 3];
54 }
55 async computeSourceEmbeddings(data: string[]) {
56 return Array.from({ length: data.length }).fill([
57 1, 2, 3,
58 ]) as number[][];
59 }
60 }
61 const func = new MockEmbeddingFunction();
62 const db = await connect(tmpDir.name);
63 const table = await db.createTable(
64 "test",
65 [
66 { id: 1, text: "hello" },
67 { id: 2, text: "world" },
68 ],
69 {
70 embeddingFunction: {
71 function: func,
72 sourceColumn: "text",
73 },
74 },
75 );
76 // biome-ignore lint/suspicious/noExplicitAny: test
77 const arr = (await table.query().toArray()) as any;
78 expect(arr[0].vector).toBeDefined();
79
80 // we round trip through JSON to make sure the vector properly gets converted to an array
81 // otherwise it'll be a TypedArray or Vector
82 const vector0 = JSON.parse(JSON.stringify(arr[0].vector));
83 expect(vector0).toEqual([1, 2, 3]);
84 });
85
86 it("should be able to create an empty table with an embedding function", async () => {
87 @register()
88 class MockEmbeddingFunction extends EmbeddingFunction<string> {
89 toJSON(): object {
90 return {};
91 }
92 ndims() {
93 return 3;
94 }
95 embeddingDataType(): Float {
96 return new Float32();
97 }
98 async computeQueryEmbeddings(_data: string) {
99 return [1, 2, 3];
100 }
101 async computeSourceEmbeddings(data: string[]) {
102 return Array.from({ length: data.length }).fill([
103 1, 2, 3,
104 ]) as number[][];
105 }
106 }
107 const schema = new Schema([
108 new Field("text", new Utf8(), true),
109 new Field(
110 "vector",
111 new FixedSizeList(3, new Field("item", new Float32(), true)),
112 true,
113 ),
114 ]);
115
116 const func = new MockEmbeddingFunction();
117 const db = await connect(tmpDir.name);
118 const table = await db.createEmptyTable("test", schema, {
119 embeddingFunction: {
120 function: func,
121 sourceColumn: "text",
122 },
123 });
124 const outSchema = await table.schema();
125 expect(outSchema.metadata.get("embedding_functions")).toBeDefined();
126 await table.add([{ text: "hello world" }]);
127
128 // biome-ignore lint/suspicious/noExplicitAny: test
129 const arr = (await table.query().toArray()) as any;
130 expect(arr[0].vector).toBeDefined();
131
132 // we round trip through JSON to make sure the vector properly gets converted to an array
133 // otherwise it'll be a TypedArray or Vector
134 const vector0 = JSON.parse(JSON.stringify(arr[0].vector));
135 expect(vector0).toEqual([1, 2, 3]);
136 });
137 it("should error when appending to a table with an unregistered embedding function", async () => {
138 @register("mock")
139 class MockEmbeddingFunction extends EmbeddingFunction<string> {
140 toJSON(): object {
141 return {};
142 }
143 ndims() {
144 return 3;
145 }
146 embeddingDataType(): Float {
147 return new Float32();
148 }
149 async computeQueryEmbeddings(_data: string) {
150 return [1, 2, 3];
151 }
152 async computeSourceEmbeddings(data: string[]) {
153 return Array.from({ length: data.length }).fill([
154 1, 2, 3,
155 ]) as number[][];
156 }
157 }
158 const func = getRegistry().get<MockEmbeddingFunction>("mock")!.create();
159
160 const schema = LanceSchema({
161 id: new Float64(),
162 text: func.sourceField(new Utf8()),
163 vector: func.vectorField(),
164 });
165
166 const db = await connect(tmpDir.name);
167 await db.createTable(
168 "test",
169 [
170 { id: 1, text: "hello" },
171 { id: 2, text: "world" },
172 ],
173 {
174 schema,
175 },
176 );
177
178 getRegistry().reset();
179 const db2 = await connect(tmpDir.name);
180
181 const tbl = await db2.openTable("test");
182
183 expect(tbl.add([{ id: 3, text: "hello" }])).rejects.toThrow(
184 `Function "mock" not found in registry`,
185 );
186 });
187 test.each([new Float16(), new Float32(), new Float64()])(
188 "should be able to provide manual embeddings with multiple float datatype",
189 async (floatType) => {
190 class MockEmbeddingFunction extends EmbeddingFunction<string> {
191 toJSON(): object {
192 return {};
193 }
194 ndims() {
195 return 3;
196 }
197 embeddingDataType(): Float {
198 return floatType;
199 }
200 async computeQueryEmbeddings(_data: string) {
201 return [1, 2, 3];
202 }
203 async computeSourceEmbeddings(data: string[]) {
204 return Array.from({ length: data.length }).fill([
205 1, 2, 3,
206 ]) as number[][];
207 }
208 }
209 const data = [{ text: "hello" }, { text: "hello world" }];
210
211 const schema = new Schema([
212 new Field("vector", new FixedSizeList(3, new Field("item", floatType))),
213 new Field("text", new Utf8()),
214 ]);
215 const func = new MockEmbeddingFunction();
216
217 const name = "test";
218 const db = await connect(tmpDir.name);
219
220 const table = await db.createTable(name, data, {
221 schema,
222 embeddingFunction: {
223 sourceColumn: "text",
224 function: func,
225 },
226 });
227 const res = await table.query().toArray();
228
229 expect([...res[0].vector]).toEqual([1, 2, 3]);
230 },
231 );
232
233 test.each([new Float16(), new Float32(), new Float64()])(
234 "should be able to provide auto embeddings with multiple float datatypes",
235 async (floatType) => {
236 @register("test1")
237 class MockEmbeddingFunctionWithoutNDims extends EmbeddingFunction<string> {
238 toJSON(): object {
239 return {};
240 }
241
242 embeddingDataType(): Float {
243 return floatType;
244 }
245 async computeQueryEmbeddings(_data: string) {
246 return [1, 2, 3];
247 }
248 async computeSourceEmbeddings(data: string[]) {
249 return Array.from({ length: data.length }).fill([
250 1, 2, 3,
251 ]) as number[][];
252 }
253 }
254 @register("test")
255 class MockEmbeddingFunction extends EmbeddingFunction<string> {
256 toJSON(): object {
257 return {};
258 }
259 ndims() {
260 return 3;
261 }
262 embeddingDataType(): Float {
263 return floatType;
264 }
265 async computeQueryEmbeddings(_data: string) {
266 return [1, 2, 3];
267 }
268 async computeSourceEmbeddings(data: string[]) {
269 return Array.from({ length: data.length }).fill([
270 1, 2, 3,
271 ]) as number[][];
272 }
273 }
274 const func = getRegistry().get<MockEmbeddingFunction>("test")!.create();
275 const func2 = getRegistry()
276 .get<MockEmbeddingFunctionWithoutNDims>("test1")!
277 .create();
278
279 const schema = LanceSchema({
280 text: func.sourceField(new Utf8()),
281 vector: func.vectorField(floatType),
282 });
283
284 const schema2 = LanceSchema({
285 text: func2.sourceField(new Utf8()),
286 vector: func2.vectorField({ datatype: floatType, dims: 3 }),
287 });
288 const schema3 = LanceSchema({
289 text: func2.sourceField(new Utf8()),
290 vector: func.vectorField({
291 datatype: new FixedSizeList(3, new Field("item", floatType, true)),
292 dims: 3,
293 }),
294 });
295
296 const expectedSchema = new Schema([
297 new Field("text", new Utf8(), true),
298 new Field(
299 "vector",
300 new FixedSizeList(3, new Field("item", floatType, true)),
301 true,
302 ),
303 ]);
304 const stringSchema = JSON.stringify(schema, null, 2);
305 const stringSchema2 = JSON.stringify(schema2, null, 2);
306 const stringSchema3 = JSON.stringify(schema3, null, 2);
307 const stringExpectedSchema = JSON.stringify(expectedSchema, null, 2);
308
309 expect(stringSchema).toEqual(stringExpectedSchema);
310 expect(stringSchema2).toEqual(stringExpectedSchema);
311 expect(stringSchema3).toEqual(stringExpectedSchema);
312 },
313 );
314});