Elffuss BraidHub

kikocis/lancedb public

main · 7.4 KiBRenderedRawPermalink
1# Langchain
2![Illustration](../assets/langchain.png)
3
4## Quick Start
5You can load your document data using langchain's loaders, for this example we are using `TextLoader` and `OpenAIEmbeddings` as the embedding model. Checkout Complete example here - [LangChain demo](../notebooks/langchain_example.ipynb)
6```python
7import os
8from langchain.document_loaders import TextLoader
9from langchain.vectorstores import LanceDB
10from langchain_openai import OpenAIEmbeddings
11from langchain_text_splitters import CharacterTextSplitter
12
13os.environ["OPENAI_API_KEY"] = "sk-..."
14
15loader = TextLoader("../../modules/state_of_the_union.txt") # Replace with your data path
16documents = loader.load()
17
18documents = CharacterTextSplitter().split_documents(documents)
19embeddings = OpenAIEmbeddings()
20
21docsearch = LanceDB.from_documents(documents, embeddings)
22query = "What did the president say about Ketanji Brown Jackson"
23docs = docsearch.similarity_search(query)
24print(docs[0].page_content)
25```
26
27## Documentation
28In the above example `LanceDB` vector store class object is created using `from_documents()` method which is a `classmethod` and returns the initialized class object.
29You can also use `LanceDB.from_texts(texts: List[str],embedding: Embeddings)` class method.
30
31The exhaustive list of parameters for `LanceDB` vector store are :
32- `connection`: (Optional) `lancedb.db.LanceDBConnection` connection object to use. If not provided, a new connection will be created.
33- `embedding`: Langchain embedding model.
34- `vector_key`: (Optional) Column name to use for vector's in the table. Defaults to `'vector'`.
35- `id_key`: (Optional) Column name to use for id's in the table. Defaults to `'id'`.
36- `text_key`: (Optional) Column name to use for text in the table. Defaults to `'text'`.
37- `table_name`: (Optional) Name of your table in the database. Defaults to `'vectorstore'`.
38- `api_key`: (Optional) API key to use for LanceDB cloud database. Defaults to `None`.
39- `region`: (Optional) Region to use for LanceDB cloud database. Only for LanceDB Cloud, defaults to `None`.
40- `mode`: (Optional) Mode to use for adding data to the table. Defaults to `'overwrite'`.
41- `reranker`: (Optional) The reranker to use for LanceDB.
42- `relevance_score_fn`: (Optional[Callable[[float], float]]) Langchain relevance score function to be used. Defaults to `None`.
43
44```python
45db_url = "db://lang_test" # url of db you created
46api_key = "xxxxx" # your API key
47region="us-east-1-dev" # your selected region
48
49vector_store = LanceDB(
50 uri=db_url,
51 api_key=api_key, #(dont include for local API)
52 region=region, #(dont include for local API)
53 embedding=embeddings,
54 table_name='langchain_test' #Optional
55 )
56```
57
58### Methods
59
60##### add_texts()
61- `texts`: `Iterable` of strings to add to the vectorstore.
62- `metadatas`: Optional `list[dict()]` of metadatas associated with the texts.
63- `ids`: Optional `list` of ids to associate with the texts.
64- `kwargs`: `Any`
65
66This method adds texts and stores respective embeddings automatically.
67
68```python
69vector_store.add_texts(texts = ['test_123'], metadatas =[{'source' :'wiki'}])
70
71#Additionaly, to explore the table you can load it into a df or save it in a csv file:
72
73tbl = vector_store.get_table()
74print("tbl:", tbl)
75pd_df = tbl.to_pandas()
76pd_df.to_csv("docsearch.csv", index=False)
77
78# you can also create a new vector store object using an older connection object:
79vector_store = LanceDB(connection=tbl, embedding=embeddings)
80```
81##### create_index()
82- `col_name`: `Optional[str] = None`
83- `vector_col`: `Optional[str] = None`
84- `num_partitions`: `Optional[int] = 256`
85- `num_sub_vectors`: `Optional[int] = 96`
86- `index_cache_size`: `Optional[int] = None`
87
88This method creates an index for the vector store. For index creation make sure your table has enough data in it. An ANN index is ususally not needed for datasets ~100K vectors. For large-scale (>1M) or higher dimension vectors, it is beneficial to create an ANN index.
89
90```python
91# for creating vector index
92vector_store.create_index(vector_col='vector', metric = 'cosine')
93
94# for creating scalar index(for non-vector columns)
95vector_store.create_index(col_name='text')
96
97```
98
99##### similarity_search()
100- `query`: `str`
101- `k`: `Optional[int] = None`
102- `filter`: `Optional[Dict[str, str]] = None`
103- `fts`: `Optional[bool] = False`
104- `name`: `Optional[str] = None`
105- `kwargs`: `Any`
106
107Return documents most similar to the query without relevance scores
108
109```python
110docs = docsearch.similarity_search(query)
111print(docs[0].page_content)
112```
113
114##### similarity_search_by_vector()
115- `embedding`: `List[float]`
116- `k`: `Optional[int] = None`
117- `filter`: `Optional[Dict[str, str]] = None`
118- `name`: `Optional[str] = None`
119- `kwargs`: `Any`
120
121Returns documents most similar to the query vector.
122
123```python
124docs = docsearch.similarity_search_by_vector(query)
125print(docs[0].page_content)
126```
127
128##### similarity_search_with_score()
129- `query`: `str`
130- `k`: `Optional[int] = None`
131- `filter`: `Optional[Dict[str, str]] = None`
132- `kwargs`: `Any`
133
134Returns documents most similar to the query string with relevance scores, gets called by base class's `similarity_search_with_relevance_scores` which selects relevance score based on our `_select_relevance_score_fn`.
135
136```python
137docs = docsearch.similarity_search_with_relevance_scores(query)
138print("relevance score - ", docs[0][1])
139print("text- ", docs[0][0].page_content[:1000])
140```
141
142##### similarity_search_by_vector_with_relevance_scores()
143- `embedding`: `List[float]`
144- `k`: `Optional[int] = None`
145- `filter`: `Optional[Dict[str, str]] = None`
146- `name`: `Optional[str] = None`
147- `kwargs`: `Any`
148
149Return documents most similar to the query vector with relevance scores.
150Relevance score
151
152```python
153docs = docsearch.similarity_search_by_vector_with_relevance_scores(query_embedding)
154print("relevance score - ", docs[0][1])
155print("text- ", docs[0][0].page_content[:1000])
156```
157
158##### max_marginal_relevance_search()
159- `query`: `str`
160- `k`: `Optional[int] = None`
161- `fetch_k` : Number of Documents to fetch to pass to MMR algorithm, `Optional[int] = None`
162- `lambda_mult`: Number between 0 and 1 that determines the degree
163 of diversity among the results with 0 corresponding
164 to maximum diversity and 1 to minimum diversity.
165 Defaults to 0.5. `float = 0.5`
166- `filter`: `Optional[Dict[str, str]] = None`
167- `kwargs`: `Any`
168
169Returns docs selected using the maximal marginal relevance(MMR).
170Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents.
171
172Similarly, `max_marginal_relevance_search_by_vector()` function returns docs most similar to the embedding passed to the function using MMR. instead of a string query you need to pass the embedding to be searched for.
173
174```python
175result = docsearch.max_marginal_relevance_search(
176 query="text"
177 )
178result_texts = [doc.page_content for doc in result]
179print(result_texts)
180
181## search by vector :
182result = docsearch.max_marginal_relevance_search_by_vector(
183 embeddings.embed_query("text")
184 )
185result_texts = [doc.page_content for doc in result]
186print(result_texts)
187```
188
189##### add_images()
190- `uris` : File path to the image. `List[str]`.
191- `metadatas` : Optional list of metadatas. `(Optional[List[dict]], optional)`
192- `ids` : Optional list of IDs. `(Optional[List[str]], optional)`
193
194Adds images by automatically creating their embeddings and adds them to the vectorstore.
195
196```python
197vec_store.add_images(uris=image_uris)
198# here image_uris are local fs paths to the images.
199```
200
201