You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
from langchain_deeplake import DeeplakeVectorStore
15
15
```
16
+
17
+
18
+
## How to Use Deep Lake as a Vector Store in LangChain
19
+
Deep Lake can be used as a VectorStore in [LangChain](https://github.com/langchain-ai/langchain) for building Apps that require filtering and vector search. In this tutorial, we will show how to create a Deep Lake Vector Store in LangChain and use it to build a Q&A App about the [Twitter OSS recommendation algorithm](https://github.com/twitter/the-algorithm). This tutorial requires installation of:
First, let's import necessary packages and make sure the Activeloop and OpenAI keys are in the environmental variables `ACTIVELOOP_TOKEN`, `OPENAI_API_KEY`.
28
+
29
+
30
+
31
+
32
+
```python
33
+
import os
34
+
import getpass
35
+
from langchain_openai import OpenAIEmbeddings
36
+
from langchain_deeplake.vectorstores import DeeplakeVectorStore
37
+
from langchain_community.document_loaders import TextLoader
38
+
from langchain_text_splitters import CharacterTextSplitter
39
+
from langchain.chains import RetrievalQA
40
+
from langchain_openai import ChatOpenAI
41
+
```
42
+
43
+
Next, we set up environmental variables
44
+
```python
45
+
if"OPENAI_API_KEY"notin os.environ:
46
+
os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")
Text files are typically split into chunks before creating embeddings. In general, more chunks increases the relevancy of data that is fed into the language model, since granular data can be selected with higher precision. However, since an embedding will be created for each chunk, more chunks increase the computational complexity.
First, we specify a path for storing the Deep Lake dataset containing the embeddings and their metadata.
87
+
88
+
```python
89
+
dataset_path ='al://<org-id>/twitter_algorithm'
90
+
```
91
+
92
+
Next, we specify an OpenAI algorithm for creating the embeddings, and create the VectorStore. This process creates an embedding for each element in the texts lists and stores it in Deep Lake format at the specified path.
93
+
94
+
```python
95
+
embeddings = OpenAIEmbeddings()
96
+
```
97
+
98
+
99
+
```python
100
+
db = DeeplakeVectorStore.from_documents(dataset_path=dataset_path, embedding=embeddings, documents=texts, overwrite=True)
101
+
```
102
+
103
+
The Deep Lake Vector Store has 4 columns including the `texts`, `embeddings`, `ids`, and `metadata`.
104
+
105
+
```python
106
+
ds.dataset.summary()
107
+
```
108
+
109
+
```bash
110
+
Dataset length: 31305
111
+
Columns:
112
+
documents : text
113
+
embeddings: embedding(1536, clustered)
114
+
ids : text
115
+
metadata : dict
116
+
```
117
+
118
+
## Use the Vector Store in a Q&A App
119
+
120
+
We can now use the VectorStore in Q&A app, where the embeddings will be used to filter relevant documents (`texts`) that are fed into an LLM in order to answer a question.
121
+
122
+
If we were on another machine, we would load the existing Vector Store without recalculating the embeddings:
123
+
124
+
```python
125
+
db = DeeplakeVectorStore(dataset_path=dataset_path, read_only=True, embedding_function=embeddings)
126
+
127
+
```
128
+
129
+
We have to create a `retriever` object and specify the search parameters.
130
+
131
+
```python
132
+
retriever = db.as_retriever()
133
+
retriever.search_kwargs['distance_metric'] ='cos'
134
+
retriever.search_kwargs['k'] =20
135
+
```
136
+
137
+
Finally, let's create an `RetrievalQA` chain in LangChain and run it:
qa.run('What programming language is most of the SimClusters written in?')
146
+
```
147
+
148
+
This returns:
149
+
```
150
+
Most of the SimClusters code is written in Scala as indicated by the packages such as `com.twitter.simclustersann.modules`, `com.twitter.simclusters_v2.scio.common`, `com.twitter.simclusters_v2.summingbird.storm`, and references to Scala-based GCP jobs.
151
+
```
152
+
153
+
154
+
## Accessing the Low Level Deep Lake API (Advanced)
155
+
When using a Deep Lake Vector Store in LangChain, the underlying Vector Store and its low-level Deep Lake dataset can be accessed via:
156
+
157
+
```python
158
+
# LangChain Vector Store
159
+
db = DeeplakeVectorStore(dataset_path=dataset_path)
160
+
161
+
# Deep Lake Dataset object
162
+
ds = db.dataset
163
+
```
164
+
165
+
## SelfQueryRetriever with Deep Lake
166
+
167
+
Deep Lake supports the [SelfQueryRetriever](https://api.python.langchain.com/en/latest/retrievers/langchain.retrievers.self_query.base.SelfQueryRetriever.html) implementation in LangChain, which translates a user prompt into a metadata filters.
168
+
169
+
170
+
>This section of the tutorial requires installation of additional packages:
171
+
> `pip install deeplake lark`
172
+
173
+
First let's create a Deep Lake Vector Store with relevant data using the documents below.
174
+
175
+
```python
176
+
from langchain_core.documents import Document
177
+
178
+
docs = [
179
+
Document(
180
+
page_content="A bunch of scientists bring back dinosaurs and mayhem breaks loose",
page_content="Toys come alive and have a blast doing so",
197
+
metadata={"year": 1995, "genre": "animated"},
198
+
),
199
+
Document(
200
+
page_content="Three men walk into the Zone, three men walk out of the Zone",
201
+
metadata={
202
+
"year": 1979,
203
+
"rating": 9.9,
204
+
"director": "Andrei Tarkovsky",
205
+
"genre": "science fiction",
206
+
"rating": 9.9,
207
+
},
208
+
),
209
+
]
210
+
```
211
+
212
+
Since this feature uses Deep Lake's [Tensor Query Language](https://docs.deeplake.ai/latest/advanced/tql/) under the hood, the Vector Store must be stored in or connected to Deep Lake, which requires [registration with Activeloop](https://app.activeloop.ai/levongh/home):
Next, let's instantiate our retriever by providing information about the metadata fields that our documents support and a short description of the document contents.
224
+
225
+
```python
226
+
from langchain.llms import OpenAI
227
+
from langchain.retrievers.self_query.base import SelfQueryRetriever
228
+
from langchain.chains.query_constructor.base import AttributeInfo
229
+
230
+
metadata_field_info = [
231
+
AttributeInfo(
232
+
name="genre",
233
+
description="The genre of the movie",
234
+
type="string or list[string]",
235
+
),
236
+
AttributeInfo(
237
+
name="year",
238
+
description="The year the movie was released",
239
+
type="integer",
240
+
),
241
+
AttributeInfo(
242
+
name="director",
243
+
description="The name of the movie director",
244
+
type="string",
245
+
),
246
+
AttributeInfo(
247
+
name="rating", description="A 1-10 rating for the movie", type="float"
248
+
),
249
+
]
250
+
251
+
document_content_description ="Brief summary of a movie"
retriever.get_relevant_documents("What are some movies about dinosaurs")
264
+
```
265
+
266
+
Output:
267
+
```
268
+
[Document(metadata={'genre': 'science fiction', 'rating': 7.7, 'year': 1993}, page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose'),
269
+
Document(metadata={'genre': 'science fiction', 'rating': 7.7, 'year': 1993}, page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose'),
270
+
Document(metadata={'genre': 'animated', 'year': 1995}, page_content='Toys come alive and have a blast doing so'),
271
+
Document(metadata={'genre': 'animated', 'year': 1995}, page_content='Toys come alive and have a blast doing so')]
272
+
```
273
+
274
+
Now we can run a query to find movies that are above a certain ranking:
275
+
276
+
```python
277
+
# This example only specifies a filter
278
+
retriever.get_relevant_documents("I want to watch a movie rated higher than 8.5")
279
+
```
280
+
281
+
Output:
282
+
```
283
+
[Document(metadata={'director': 'Satoshi Kon', 'rating': 8.6, 'year': 2006}, page_content='A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea'),
284
+
Document(metadata={'director': 'Andrei Tarkovsky', 'genre': 'science fiction', 'rating': 9.9, 'year': 1979}, page_content='Three men walk into the Zone, three men walk out of the Zone'),
285
+
Document(metadata={'director': 'Satoshi Kon', 'rating': 8.6, 'year': 2006}, page_content='A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea'),
286
+
Document(metadata={'director': 'Andrei Tarkovsky', 'genre': 'science fiction', 'rating': 9.9, 'year': 1979}, page_content='Three men walk into the Zone, three men walk out of the Zone')]
287
+
```
288
+
289
+
290
+
Congrats! You just used the Deep Lake Vector Store in LangChain to create a Q&A App! 🎉
0 commit comments