| 1 | // --8<-- [start:imports] |
| 2 | import * as lancedb from "@lancedb/lancedb"; |
| 3 | import { LanceSchema, getRegistry, register } from "@lancedb/lancedb/embedding"; |
| 4 | import { EmbeddingFunction } from "@lancedb/lancedb/embedding"; |
| 5 | import { type Float, Float32, Utf8 } from "apache-arrow"; |
| 6 | // --8<-- [end:imports] |
| 7 | |
| 8 | { |
| 9 | // --8<-- [start:openai_embeddings] |
| 10 | |
| 11 | const db = await lancedb.connect("/tmp/db"); |
| 12 | const func = getRegistry() |
| 13 | .get("openai") |
| 14 | ?.create({ model: "text-embedding-ada-002" }) as EmbeddingFunction; |
| 15 | |
| 16 | const wordsSchema = LanceSchema({ |
| 17 | text: func.sourceField(new Utf8()), |
| 18 | vector: func.vectorField(), |
| 19 | }); |
| 20 | const tbl = await db.createEmptyTable("words", wordsSchema, { |
| 21 | mode: "overwrite", |
| 22 | }); |
| 23 | await tbl.add([{ text: "hello world" }, { text: "goodbye world" }]); |
| 24 | |
| 25 | const query = "greetings"; |
| 26 | const actual = (await (await tbl.search(query)).limit(1).toArray())[0]; |
| 27 | |
| 28 | // --8<-- [end:openai_embeddings] |
| 29 | console.log("result = ", actual.text); |
| 30 | } |
| 31 | |
| 32 | { |
| 33 | // --8<-- [start:embedding_function] |
| 34 | const db = await lancedb.connect("/tmp/db"); |
| 35 | |
| 36 | @register("my_embedding") |
| 37 | class MyEmbeddingFunction extends EmbeddingFunction<string> { |
| 38 | toJSON(): object { |
| 39 | return {}; |
| 40 | } |
| 41 | ndims() { |
| 42 | return 3; |
| 43 | } |
| 44 | embeddingDataType(): Float { |
| 45 | return new Float32(); |
| 46 | } |
| 47 | async computeQueryEmbeddings(_data: string) { |
| 48 | // This is a placeholder for a real embedding function |
| 49 | return [1, 2, 3]; |
| 50 | } |
| 51 | async computeSourceEmbeddings(data: string[]) { |
| 52 | // This is a placeholder for a real embedding function |
| 53 | return Array.from({ length: data.length }).fill([1, 2, 3]) as number[][]; |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | const func = new MyEmbeddingFunction(); |
| 58 | |
| 59 | const data = [{ text: "pepperoni" }, { text: "pineapple" }]; |
| 60 | |
| 61 | // Option 1: manually specify the embedding function |
| 62 | const table = await db.createTable("vectors", data, { |
| 63 | embeddingFunction: { |
| 64 | function: func, |
| 65 | sourceColumn: "text", |
| 66 | vectorColumn: "vector", |
| 67 | }, |
| 68 | mode: "overwrite", |
| 69 | }); |
| 70 | |
| 71 | // Option 2: provide the embedding function through a schema |
| 72 | |
| 73 | const schema = LanceSchema({ |
| 74 | text: func.sourceField(new Utf8()), |
| 75 | vector: func.vectorField(), |
| 76 | }); |
| 77 | |
| 78 | const table2 = await db.createTable("vectors2", data, { |
| 79 | schema, |
| 80 | mode: "overwrite", |
| 81 | }); |
| 82 | // --8<-- [end:embedding_function] |
| 83 | } |