Elffuss BraidHub

kikocis/lancedb public

main · 2.8 KiBRenderedRawPermalink
1The legacy `with_embeddings` API is for Python only and is deprecated.
2
3### Hugging Face
4
5The most popular open source option is to use the [sentence-transformers](https://www.sbert.net/)
6library, which can be installed via pip.
7
8```bash
9pip install sentence-transformers
10```
11
12The example below shows how to use the `paraphrase-albert-small-v2` model to generate embeddings
13for a given document.
14
15```python
16from sentence_transformers import SentenceTransformer
17
18name="paraphrase-albert-small-v2"
19model = SentenceTransformer(name)
20
21# used for both training and querying
22def embed_func(batch):
23 return [model.encode(sentence) for sentence in batch]
24```
25
26
27### OpenAI
28
29Another popular alternative is to use an external API like OpenAI's [embeddings API](https://platform.openai.com/docs/guides/embeddings/what-are-embeddings).
30
31```python
32import openai
33import os
34
35# Configuring the environment variable OPENAI_API_KEY
36if "OPENAI_API_KEY" not in os.environ:
37# OR set the key here as a variable
38openai.api_key = "sk-..."
39
40client = openai.OpenAI()
41
42def embed_func(c):
43 rs = client.embeddings.create(input=c, model="text-embedding-ada-002")
44 return [record.embedding for record in rs["data"]]
45```
46
47
48## Applying an embedding function to data
49
50Using an embedding function, you can apply it to raw data
51to generate embeddings for each record.
52
53Say you have a pandas DataFrame with a `text` column that you want embedded,
54you can use the `with_embeddings` function to generate embeddings and add them to
55an existing table.
56
57```python
58 import pandas as pd
59 from lancedb.embeddings import with_embeddings
60
61 df = pd.DataFrame(
62 [
63 {"text": "pepperoni"},
64 {"text": "pineapple"}
65 ]
66 )
67 data = with_embeddings(embed_func, df)
68
69 # The output is used to create / append to a table
70 tbl = db.create_table("my_table", data=data)
71```
72
73If your data is in a different column, you can specify the `column` kwarg to `with_embeddings`.
74
75By default, LanceDB calls the function with batches of 1000 rows. This can be configured
76using the `batch_size` parameter to `with_embeddings`.
77
78LanceDB automatically wraps the function with retry and rate-limit logic to ensure the OpenAI
79API call is reliable.
80
81## Querying using an embedding function
82
83!!! warning
84 At query time, you **must** use the same embedding function you used to vectorize your data.
85 If you use a different embedding function, the embeddings will not reside in the same vector
86 space and the results will be nonsensical.
87
88=== "Python"
89 ```python
90 query = "What's the best pizza topping?"
91 query_vector = embed_func([query])[0]
92 results = (
93 tbl.search(query_vector)
94 .limit(10)
95 .to_pandas()
96 )
97 ```
98
99 The above snippet returns a pandas DataFrame with the 10 closest vectors to the query.