Elffuss BraidHub

kikocis/lancedb public

e822b4e34fb7 · 7.7 KiBRenderedRawPermalink
1Representing multi-modal data as vector embeddings is becoming a standard practice. Embedding functions can themselves be thought of as key part of the data processing pipeline that each request has to be passed through. The assumption here is: after initial setup, these components and the underlying methodology are not expected to change for a particular project.
2
3For this purpose, LanceDB introduces an **embedding functions API**, that allow you simply set up once, during the configuration stage of your project. After this, the table remembers it, effectively making the embedding functions *disappear in the background* so you don't have to worry about manually passing callables, and instead, simply focus on the rest of your data engineering pipeline.
4
5!!! Note "Embedding functions on LanceDB cloud"
6 When using embedding functions with LanceDB cloud, the embeddings will be generated on the source device and sent to the cloud. This means that the source device must have the necessary resources to generate the embeddings.
7
8!!! warning
9 Using the embedding function registry means that you don't have to explicitly generate the embeddings yourself.
10 However, if your embedding function changes, you'll have to re-configure your table with the new embedding function
11 and regenerate the embeddings. In the future, we plan to support the ability to change the embedding function via
12 table metadata and have LanceDB automatically take care of regenerating the embeddings.
13
14
15## 1. Define the embedding function
16
17=== "Python"
18 In the LanceDB python SDK, we define a global embedding function registry with
19 many different embedding models and even more coming soon.
20 Here's let's an implementation of CLIP as example.
21
22 ```python
23 from lancedb.embeddings import get_registry
24
25 registry = get_registry()
26 clip = registry.get("open-clip").create()
27 ```
28
29 You can also define your own embedding function by implementing the `EmbeddingFunction`
30 abstract base interface. It subclasses Pydantic Model which can be utilized to write complex schemas simply as we'll see next!
31
32=== "TypeScript"
33 In the TypeScript SDK, the choices are more limited. For now, only the OpenAI
34 embedding function is available.
35
36 ```javascript
37 import * as lancedb from '@lancedb/lancedb'
38 import { getRegistry } from '@lancedb/lancedb/embeddings'
39
40 // You need to provide an OpenAI API key
41 const apiKey = "sk-..."
42 // The embedding function will create embeddings for the 'text' column
43 const func = getRegistry().get("openai").create({apiKey})
44 ```
45=== "Rust"
46 In the Rust SDK, the choices are more limited. For now, only the OpenAI
47 embedding function is available. But unlike the Python and TypeScript SDKs, you need manually register the OpenAI embedding function.
48
49 ```toml
50 // Make sure to include the `openai` feature
51 [dependencies]
52 lancedb = {version = "*", features = ["openai"]}
53 ```
54
55 ```rust
56 --8<-- "rust/lancedb/examples/openai.rs:imports"
57 --8<-- "rust/lancedb/examples/openai.rs:openai_embeddings"
58 ```
59
60## 2. Define the data model or schema
61
62=== "Python"
63 The embedding function defined above abstracts away all the details about the models and dimensions required to define the schema. You can simply set a field as **source** or **vector** column. Here's how:
64
65 ```python
66 class Pets(LanceModel):
67 vector: Vector(clip.ndims()) = clip.VectorField()
68 image_uri: str = clip.SourceField()
69 ```
70
71 `VectorField` tells LanceDB to use the clip embedding function to generate query embeddings for the `vector` column and `SourceField` ensures that when adding data, we automatically use the specified embedding function to encode `image_uri`.
72
73=== "TypeScript"
74
75 For the TypeScript SDK, a schema can be inferred from input data, or an explicit
76 Arrow schema can be provided.
77
78## 3. Create table and add data
79
80Now that we have chosen/defined our embedding function and the schema,
81we can create the table and ingest data without needing to explicitly generate
82the embeddings at all:
83
84=== "Python"
85 ```python
86 db = lancedb.connect("~/lancedb")
87 table = db.create_table("pets", schema=Pets)
88
89 table.add([{"image_uri": u} for u in uris])
90 ```
91
92=== "TypeScript"
93
94 === "@lancedb/lancedb"
95
96 ```ts
97 --8<-- "nodejs/examples/embedding.ts:imports"
98 --8<-- "nodejs/examples/embedding.ts:embedding_function"
99 ```
100
101 === "vectordb (deprecated)"
102
103 ```ts
104 const db = await lancedb.connect("data/sample-lancedb");
105 const data = [
106 { text: "pepperoni"},
107 { text: "pineapple"}
108 ]
109
110 const table = await db.createTable("vectors", data, embedding)
111 ```
112
113## 4. Querying your table
114Not only can you forget about the embeddings during ingestion, you also don't
115need to worry about it when you query the table:
116
117=== "Python"
118
119 Our OpenCLIP query embedding function supports querying via both text and images:
120
121 ```python
122 results = (
123 table.search("dog")
124 .limit(10)
125 .to_pandas()
126 )
127 ```
128
129 Or we can search using an image:
130
131 ```python
132 p = Path("path/to/images/samoyed_100.jpg")
133 query_image = Image.open(p)
134 results = (
135 table.search(query_image)
136 .limit(10)
137 .to_pandas()
138 )
139 ```
140
141 Both of the above snippet returns a pandas DataFrame with the 10 closest vectors to the query.
142
143=== "TypeScript"
144
145 === "@lancedb/lancedb"
146
147 ```ts
148 const results = await table.search("What's the best pizza topping?")
149 .limit(10)
150 .toArray()
151 ```
152
153 === "vectordb (deprecated)
154
155 ```ts
156 const results = await table
157 .search("What's the best pizza topping?")
158 .limit(10)
159 .execute()
160 ```
161
162 The above snippet returns an array of records with the top 10 nearest neighbors to the query.
163
164---
165
166## Rate limit Handling
167`EmbeddingFunction` class wraps the calls for source and query embedding generation inside a rate limit handler that retries the requests with exponential backoff after successive failures. By default, the maximum retires is set to 7. You can tune it by setting it to a different number, or disable it by setting it to 0.
168
169An example of how to do this is shown below:
170
171```python
172clip = registry.get("open-clip").create() # Defaults to 7 max retries
173clip = registry.get("open-clip").create(max_retries=10) # Increase max retries to 10
174clip = registry.get("open-clip").create(max_retries=0) # Retries disabled
175```
176
177!!! note
178 Embedding functions can also fail due to other errors that have nothing to do with rate limits.
179 This is why the error is also logged.
180
181## Some fun with Pydantic
182
183LanceDB is integrated with Pydantic, which was used in the example above to define the schema in Python. It's also used behind the scenes by the embedding function API to ingest useful information as table metadata.
184
185You can also use the integration for adding utility operations in the schema. For example, in our multi-modal example, you can search images using text or another image. Let's define a utility function to plot the image.
186
187```python
188class Pets(LanceModel):
189 vector: Vector(clip.ndims()) = clip.VectorField()
190 image_uri: str = clip.SourceField()
191
192 @property
193 def image(self):
194 return Image.open(self.image_uri)
195```
196Now, you can covert your search results to a Pydantic model and use this property.
197
198```python
199rs = table.search(query_image).limit(3).to_pydantic(Pets)
200rs[2].image
201```
202
203![](../assets/dog_clip_output.png)
204
205Now that you have the basic idea about LanceDB embedding functions and the embedding function registry,
206let's dive deeper into defining your own [custom functions](./custom_embedding_function.md).