langchain-ydb 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,216 @@
1
+ Metadata-Version: 2.3
2
+ Name: langchain-ydb
3
+ Version: 0.0.1
4
+ Summary: An integration package connecting YDB and LangChain
5
+ Requires-Python: >=3.9,<4.0
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: Programming Language :: Python :: 3.9
8
+ Classifier: Programming Language :: Python :: 3.10
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Requires-Dist: langchain-core (>=0.2.13,<0.4.0)
13
+ Requires-Dist: ydb-dbapi (>=0.1.11,<0.2.0)
14
+ Description-Content-Type: text/markdown
15
+
16
+ # langchain-ydb
17
+ ---
18
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/ydb-platform/langchain-ydb/blob/main/LICENSE)
19
+ [![Functional tests](https://github.com/ydb-platform/langchain-ydb/actions/workflows/tests.yml/badge.svg)](https://github.com/ydb-platform/langchain-ydb/actions/workflows/tests.yml)
20
+ [![Lint checks](https://github.com/ydb-platform/langchain-ydb/actions/workflows/lint.yml/badge.svg)](https://github.com/ydb-platform/langchain-ydb/actions/workflows/lint.yml)
21
+
22
+ LangChain's YDB integration (langchain-ydb) provides vector capabilities for working with [YDB](https://ydb.tech/).
23
+
24
+ ## Getting Started
25
+
26
+ ### Setting Up YDB
27
+
28
+ Launch a YDB Docker container with:
29
+
30
+ ```shell
31
+ docker run -d -p 2136:2136 --name ydb-langchain -e YDB_USE_IN_MEMORY_PDISKS=true -h localhost ydbplatform/local-ydb:trunk
32
+ ```
33
+
34
+ ### Installing the Package
35
+
36
+ Install `langchain-ydb` package with:
37
+
38
+ ```bash
39
+ pip install -U langchain-ydb
40
+ ```
41
+
42
+ VectorStore works along with an embedding model, here using `langchain-openai` as example.
43
+
44
+ ```shell
45
+ pip install langchain-openai
46
+ export OPENAI_API_KEY=...
47
+ ```
48
+
49
+ ## Work with YDB Vector Store
50
+
51
+ ### Creating a Vector Store
52
+
53
+ ```python
54
+ from langchain_openai import OpenAIEmbeddings
55
+ from langchain_ydb.vectorstores import YDB, YDBSearchStrategy, YDBSettings
56
+
57
+
58
+ settings = YDBSettings(
59
+ table="ydb_example",
60
+ strategy=YDBSearchStrategy.COSINE_SIMILARITY,
61
+ )
62
+ vector_store = YDB(
63
+ OpenAIEmbeddings(),
64
+ config=settings,
65
+ )
66
+ ```
67
+
68
+ ### Add items to vector store
69
+
70
+ Once you have created your vector store, you can interact with it by adding and deleting different items.
71
+
72
+ Prepare documents to work with:
73
+
74
+ ```python
75
+ from uuid import uuid4
76
+
77
+ from langchain_core.documents import Document
78
+
79
+ document_1 = Document(
80
+ page_content="I had chocalate chip pancakes and scrambled eggs for breakfast this morning.",
81
+ metadata={"source": "tweet"},
82
+ )
83
+
84
+ document_2 = Document(
85
+ page_content="The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees.",
86
+ metadata={"source": "news"},
87
+ )
88
+
89
+ document_3 = Document(
90
+ page_content="Building an exciting new project with LangChain - come check it out!",
91
+ metadata={"source": "tweet"},
92
+ )
93
+
94
+ document_4 = Document(
95
+ page_content="Robbers broke into the city bank and stole $1 million in cash.",
96
+ metadata={"source": "news"},
97
+ )
98
+
99
+ document_5 = Document(
100
+ page_content="Wow! That was an amazing movie. I can't wait to see it again.",
101
+ metadata={"source": "tweet"},
102
+ )
103
+
104
+ document_6 = Document(
105
+ page_content="Is the new iPhone worth the price? Read this review to find out.",
106
+ metadata={"source": "website"},
107
+ )
108
+
109
+ document_7 = Document(
110
+ page_content="The top 10 soccer players in the world right now.",
111
+ metadata={"source": "website"},
112
+ )
113
+
114
+ document_8 = Document(
115
+ page_content="LangGraph is the best framework for building stateful, agentic applications!",
116
+ metadata={"source": "tweet"},
117
+ )
118
+
119
+ document_9 = Document(
120
+ page_content="The stock market is down 500 points today due to fears of a recession.",
121
+ metadata={"source": "news"},
122
+ )
123
+
124
+ document_10 = Document(
125
+ page_content="I have a bad feeling I am going to get deleted :(",
126
+ metadata={"source": "tweet"},
127
+ )
128
+
129
+ documents = [
130
+ document_1,
131
+ document_2,
132
+ document_3,
133
+ document_4,
134
+ document_5,
135
+ document_6,
136
+ document_7,
137
+ document_8,
138
+ document_9,
139
+ document_10,
140
+ ]
141
+ uuids = [str(uuid4()) for _ in range(len(documents))]
142
+ ```
143
+
144
+ You can add items to your vector store by using the `add_documents` function.
145
+
146
+ ```python
147
+ vector_store.add_documents(documents=documents, ids=uuids)
148
+ ```
149
+
150
+ ### Delete items from vector store
151
+
152
+ You can delete items from your vector store by ID using the `delete` function.
153
+
154
+ ```python
155
+ vector_store.delete(ids=[uuids[-1]])
156
+ ```
157
+
158
+ ### Query vector store
159
+
160
+ Once your vector store has been created and relevant documents have been added, you will likely want to query it during the execution of your chain or agent.
161
+
162
+ #### Query directly
163
+
164
+ **Similarity search**:
165
+
166
+ A simple similarity search can be performed as follows:
167
+
168
+ ```python
169
+ results = vector_store.similarity_search(
170
+ "LangChain provides abstractions to make working with LLMs easy", k=2
171
+ )
172
+ for res in results:
173
+ print(f"* {res.page_content} [{res.metadata}]")
174
+ ```
175
+
176
+ **Similarity search with score**
177
+
178
+ You can also perform a search with a score:
179
+
180
+ ```python
181
+ results = vector_store.similarity_search_with_score("Will it be hot tomorrow?", k=3)
182
+ for res, score in results:
183
+ print(f"* [SIM={score:.3f}] {res.page_content} [{res.metadata}]")
184
+ ```
185
+
186
+ #### Filtering
187
+
188
+ You can search with filters as described below:
189
+
190
+ ```python
191
+ results = vector_store.similarity_search_with_score(
192
+ "What did I eat for breakfast?",
193
+ k=4,
194
+ filter={"source": "tweet"},
195
+ )
196
+ for res, _ in results:
197
+ print(f"* {res.page_content} [{res.metadata}]")
198
+ ```
199
+
200
+ #### Query by turning into retriever
201
+
202
+ You can also transform the vector store into a retriever for easier usage in your chains.
203
+
204
+ Here's how to transform your vector store into a retriever and then invoke the retriever with a simple query and filter.
205
+
206
+ ```python
207
+ retriever = vector_store.as_retriever(
208
+ search_kwargs={"k": 2},
209
+ )
210
+ results = retriever.invoke(
211
+ "Stealing from the bank is a crime", filter={"source": "news"}
212
+ )
213
+ for res in results:
214
+ print(f"* {res.page_content} [{res.metadata}]")
215
+ ```
216
+
@@ -0,0 +1,200 @@
1
+ # langchain-ydb
2
+ ---
3
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/ydb-platform/langchain-ydb/blob/main/LICENSE)
4
+ [![Functional tests](https://github.com/ydb-platform/langchain-ydb/actions/workflows/tests.yml/badge.svg)](https://github.com/ydb-platform/langchain-ydb/actions/workflows/tests.yml)
5
+ [![Lint checks](https://github.com/ydb-platform/langchain-ydb/actions/workflows/lint.yml/badge.svg)](https://github.com/ydb-platform/langchain-ydb/actions/workflows/lint.yml)
6
+
7
+ LangChain's YDB integration (langchain-ydb) provides vector capabilities for working with [YDB](https://ydb.tech/).
8
+
9
+ ## Getting Started
10
+
11
+ ### Setting Up YDB
12
+
13
+ Launch a YDB Docker container with:
14
+
15
+ ```shell
16
+ docker run -d -p 2136:2136 --name ydb-langchain -e YDB_USE_IN_MEMORY_PDISKS=true -h localhost ydbplatform/local-ydb:trunk
17
+ ```
18
+
19
+ ### Installing the Package
20
+
21
+ Install `langchain-ydb` package with:
22
+
23
+ ```bash
24
+ pip install -U langchain-ydb
25
+ ```
26
+
27
+ VectorStore works along with an embedding model, here using `langchain-openai` as example.
28
+
29
+ ```shell
30
+ pip install langchain-openai
31
+ export OPENAI_API_KEY=...
32
+ ```
33
+
34
+ ## Work with YDB Vector Store
35
+
36
+ ### Creating a Vector Store
37
+
38
+ ```python
39
+ from langchain_openai import OpenAIEmbeddings
40
+ from langchain_ydb.vectorstores import YDB, YDBSearchStrategy, YDBSettings
41
+
42
+
43
+ settings = YDBSettings(
44
+ table="ydb_example",
45
+ strategy=YDBSearchStrategy.COSINE_SIMILARITY,
46
+ )
47
+ vector_store = YDB(
48
+ OpenAIEmbeddings(),
49
+ config=settings,
50
+ )
51
+ ```
52
+
53
+ ### Add items to vector store
54
+
55
+ Once you have created your vector store, you can interact with it by adding and deleting different items.
56
+
57
+ Prepare documents to work with:
58
+
59
+ ```python
60
+ from uuid import uuid4
61
+
62
+ from langchain_core.documents import Document
63
+
64
+ document_1 = Document(
65
+ page_content="I had chocalate chip pancakes and scrambled eggs for breakfast this morning.",
66
+ metadata={"source": "tweet"},
67
+ )
68
+
69
+ document_2 = Document(
70
+ page_content="The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees.",
71
+ metadata={"source": "news"},
72
+ )
73
+
74
+ document_3 = Document(
75
+ page_content="Building an exciting new project with LangChain - come check it out!",
76
+ metadata={"source": "tweet"},
77
+ )
78
+
79
+ document_4 = Document(
80
+ page_content="Robbers broke into the city bank and stole $1 million in cash.",
81
+ metadata={"source": "news"},
82
+ )
83
+
84
+ document_5 = Document(
85
+ page_content="Wow! That was an amazing movie. I can't wait to see it again.",
86
+ metadata={"source": "tweet"},
87
+ )
88
+
89
+ document_6 = Document(
90
+ page_content="Is the new iPhone worth the price? Read this review to find out.",
91
+ metadata={"source": "website"},
92
+ )
93
+
94
+ document_7 = Document(
95
+ page_content="The top 10 soccer players in the world right now.",
96
+ metadata={"source": "website"},
97
+ )
98
+
99
+ document_8 = Document(
100
+ page_content="LangGraph is the best framework for building stateful, agentic applications!",
101
+ metadata={"source": "tweet"},
102
+ )
103
+
104
+ document_9 = Document(
105
+ page_content="The stock market is down 500 points today due to fears of a recession.",
106
+ metadata={"source": "news"},
107
+ )
108
+
109
+ document_10 = Document(
110
+ page_content="I have a bad feeling I am going to get deleted :(",
111
+ metadata={"source": "tweet"},
112
+ )
113
+
114
+ documents = [
115
+ document_1,
116
+ document_2,
117
+ document_3,
118
+ document_4,
119
+ document_5,
120
+ document_6,
121
+ document_7,
122
+ document_8,
123
+ document_9,
124
+ document_10,
125
+ ]
126
+ uuids = [str(uuid4()) for _ in range(len(documents))]
127
+ ```
128
+
129
+ You can add items to your vector store by using the `add_documents` function.
130
+
131
+ ```python
132
+ vector_store.add_documents(documents=documents, ids=uuids)
133
+ ```
134
+
135
+ ### Delete items from vector store
136
+
137
+ You can delete items from your vector store by ID using the `delete` function.
138
+
139
+ ```python
140
+ vector_store.delete(ids=[uuids[-1]])
141
+ ```
142
+
143
+ ### Query vector store
144
+
145
+ Once your vector store has been created and relevant documents have been added, you will likely want to query it during the execution of your chain or agent.
146
+
147
+ #### Query directly
148
+
149
+ **Similarity search**:
150
+
151
+ A simple similarity search can be performed as follows:
152
+
153
+ ```python
154
+ results = vector_store.similarity_search(
155
+ "LangChain provides abstractions to make working with LLMs easy", k=2
156
+ )
157
+ for res in results:
158
+ print(f"* {res.page_content} [{res.metadata}]")
159
+ ```
160
+
161
+ **Similarity search with score**
162
+
163
+ You can also perform a search with a score:
164
+
165
+ ```python
166
+ results = vector_store.similarity_search_with_score("Will it be hot tomorrow?", k=3)
167
+ for res, score in results:
168
+ print(f"* [SIM={score:.3f}] {res.page_content} [{res.metadata}]")
169
+ ```
170
+
171
+ #### Filtering
172
+
173
+ You can search with filters as described below:
174
+
175
+ ```python
176
+ results = vector_store.similarity_search_with_score(
177
+ "What did I eat for breakfast?",
178
+ k=4,
179
+ filter={"source": "tweet"},
180
+ )
181
+ for res, _ in results:
182
+ print(f"* {res.page_content} [{res.metadata}]")
183
+ ```
184
+
185
+ #### Query by turning into retriever
186
+
187
+ You can also transform the vector store into a retriever for easier usage in your chains.
188
+
189
+ Here's how to transform your vector store into a retriever and then invoke the retriever with a simple query and filter.
190
+
191
+ ```python
192
+ retriever = vector_store.as_retriever(
193
+ search_kwargs={"k": 2},
194
+ )
195
+ results = retriever.invoke(
196
+ "Stealing from the bank is a crime", filter={"source": "news"}
197
+ )
198
+ for res in results:
199
+ print(f"* {res.page_content} [{res.metadata}]")
200
+ ```
@@ -0,0 +1,7 @@
1
+ from importlib import metadata
2
+
3
+ try:
4
+ __version__ = metadata.version(__package__)
5
+ except metadata.PackageNotFoundError:
6
+ # Case where package metadata is not available.
7
+ __version__ = ""
File without changes
@@ -0,0 +1,464 @@
1
+ from __future__ import annotations
2
+
3
+ import enum
4
+ import json
5
+ import logging
6
+ from dataclasses import dataclass, field
7
+ from hashlib import sha1
8
+ from typing import Any, Dict, Iterable, List, Optional
9
+
10
+ from langchain_core.documents import Document
11
+ from langchain_core.embeddings import Embeddings
12
+ from langchain_core.vectorstores import VectorStore
13
+
14
+ logger = logging.getLogger()
15
+
16
+
17
+ class YDBSearchStrategy(str, enum.Enum):
18
+ """Enumerator of the search strategies."""
19
+
20
+ INNER_PRODUCT_SIMILARITY = "InnerProductSimilarity"
21
+ COSINE_SIMILARITY = "CosineSimilarity"
22
+ COSINE_DISTANCE = "CosineDistance"
23
+ MANHATTAN_DISTANCE = "ManhattanDistance"
24
+ EUCLIDEAN_DISTANCE = "EuclideanDistance"
25
+
26
+ def __str__(self) -> str:
27
+ return self.value
28
+
29
+
30
+ DEFAULT_SEARCH_STRATEGY = YDBSearchStrategy.COSINE_SIMILARITY
31
+
32
+
33
+ def _get_default_column_map_dict() -> Dict[str, str]:
34
+ return {
35
+ "id": "id",
36
+ "document": "document",
37
+ "embedding": "embedding",
38
+ "metadata": "metadata",
39
+ }
40
+
41
+
42
+ @dataclass
43
+ class YDBSettings:
44
+ """`YDB` client configuration.
45
+
46
+ Attribute:
47
+ host (str) : An URL to connect to YDB. Defaults to 'localhost'.
48
+ port (int) : URL port to connect with GRPC. Defaults to 2136.
49
+ username (str) : Username to login. Defaults to None.
50
+ password (str) : Password to login. Defaults to None.
51
+ secure (bool) : Connect to server over secure connection. Defaults to False.
52
+ database (str) : Database name to find the table. Defaults to '/local'.
53
+ table (str) : Table name to operate on. Defaults to 'langchain_store'.
54
+ column_map (Dict) : Column type map to project column name onto langchain
55
+ semantics. Must have keys: `text`, `id`, `vector`,
56
+ must be same size to number of columns. For example:
57
+ .. code-block:: python
58
+
59
+ {
60
+ 'id': 'text_id',
61
+ 'embedding': 'text_embedding',
62
+ 'document': 'text_plain',
63
+ 'metadata': 'metadata_dictionary_in_json',
64
+ }
65
+
66
+ Defaults to identity map.
67
+ strategy (str) : Strategy to perform search,
68
+ supported are ('InnerProductSimilarity', 'CosineSimilarity',
69
+ 'CosineDistance', 'ManhattanDistance',
70
+ 'EuclideanDistance'). Defaults to 'CosineSimilarity'.
71
+ Enum `YDBSearchStrategy` contains all of them.
72
+ drop_existing_table (bool) : Flag to drop existing table while init.
73
+ Defaults to False.
74
+ """
75
+
76
+ host: str = "localhost"
77
+ port: int = 2136
78
+
79
+ username: Optional[str] = None
80
+ password: Optional[str] = None
81
+
82
+ secure: bool = False
83
+
84
+ database: str = "/local"
85
+ table: str = "langchain_store"
86
+
87
+ column_map: Dict[str, str] = field(default_factory=_get_default_column_map_dict)
88
+
89
+ strategy: str = DEFAULT_SEARCH_STRATEGY
90
+
91
+ drop_existing_table: bool = False
92
+
93
+
94
+ class YDB(VectorStore):
95
+ """`YDB` vector store.
96
+
97
+ To use, you should have the ``ydb-dbapi`` python package installed.
98
+ """
99
+
100
+ def __init__(
101
+ self,
102
+ embedding: Embeddings,
103
+ config: Optional[YDBSettings] = None,
104
+ **kwargs: Any,
105
+ ) -> None:
106
+ """YDB Wrapper to LangChain
107
+
108
+ Args:
109
+ embedding (Embeddings): embedding function to use
110
+ config (YDBSettings): Configuration to YDB DBAPI
111
+ kwargs (any): Other keyword arguments will pass into ydb-dbapi
112
+ """
113
+ try:
114
+ import ydb
115
+ import ydb_dbapi
116
+
117
+ self._ydb_lib = ydb
118
+ except ImportError:
119
+ raise ImportError(
120
+ "Could not import ydb-dbapi python package. "
121
+ "Please install it with `pip install ydb-dbapi`."
122
+ )
123
+
124
+ try:
125
+ from tqdm import tqdm
126
+
127
+ self.pgbar = tqdm
128
+ except ImportError:
129
+ # Just in case if tqdm is not installed
130
+ self.pgbar = lambda x, **kwargs: x
131
+
132
+ super().__init__()
133
+ if config is not None:
134
+ self.config = config
135
+ else:
136
+ self.config = YDBSettings()
137
+
138
+ assert self.config
139
+ assert self.config.host and self.config.port
140
+ assert self.config.database and self.config.table
141
+ assert self.config.column_map and self.config.strategy
142
+
143
+ self.sort_order = (
144
+ "DESC" if self.config.strategy.endswith("Similarity") else "ASC"
145
+ )
146
+
147
+ self.embedding_function = embedding
148
+
149
+ # Create a connection to ydb
150
+ self.connection = ydb_dbapi.connect(
151
+ host=self.config.host,
152
+ port=self.config.port,
153
+ database=self.config.database,
154
+ username=self.config.username,
155
+ password=self.config.password,
156
+ protocol="grpcs" if self.config.secure else "grpc",
157
+ **kwargs,
158
+ )
159
+
160
+ if self.config.drop_existing_table:
161
+ self.drop()
162
+
163
+ self._execute_query(self._prepare_scheme_query(), ddl=True)
164
+
165
+ self._insert_query = self._prepare_insert_query()
166
+
167
+ @property
168
+ def embeddings(self) -> Optional[Embeddings]:
169
+ """Access the query embedding object if available."""
170
+ return self.embedding_function
171
+
172
+ def _execute_query(
173
+ self,
174
+ query: str,
175
+ params: Optional[dict] = None,
176
+ ddl: bool = False,
177
+ ) -> List:
178
+ with self.connection.cursor() as cursor:
179
+ if ddl:
180
+ cursor.execute_scheme(query, params)
181
+ else:
182
+ cursor.execute(query, params)
183
+
184
+ if cursor.description is None:
185
+ return []
186
+
187
+ columns = [col[0] for col in cursor.description]
188
+
189
+ return [dict(zip(columns, row)) for row in cursor.fetchall()]
190
+
191
+ def _prepare_scheme_query(self) -> str:
192
+ """Create table schema
193
+ :param dim: dimension of embeddings
194
+ :param index_params: parameters used for index
195
+
196
+ This function returns a `CREATE TABLE` statement based on the value of
197
+ `self.config.index_type`.
198
+ If an index type is specified that index will be created, otherwise
199
+ no index will be created.
200
+ In the case of there being no index, a linear scan will be performed
201
+ when the embedding field is queried.
202
+ """
203
+ return f"""
204
+ CREATE TABLE IF NOT EXISTS `{self.config.table}` (
205
+ {self.config.column_map["id"]} Utf8,
206
+ {self.config.column_map["document"]} Utf8,
207
+ {self.config.column_map["embedding"]} String,
208
+ {self.config.column_map["metadata"]} Json,
209
+ PRIMARY KEY ({self.config.column_map["id"]})
210
+ );"""
211
+
212
+ def _escape_str(self, text: str) -> str:
213
+ escape = "\\"
214
+ chars_to_escape = ["\\", '"', "'"]
215
+ return "".join(
216
+ [ch if ch not in chars_to_escape else escape + ch for ch in text]
217
+ )
218
+
219
+ def _prepare_insert_query(self) -> str:
220
+ return f"""
221
+ DECLARE $id AS Utf8;
222
+ DECLARE $document as Utf8;
223
+ DECLARE $embedding as List<Float>;
224
+ DECLARE $metadata as Json;
225
+
226
+ UPSERT INTO `{self.config.table}`
227
+ (
228
+ {self.config.column_map["id"]},
229
+ {self.config.column_map["document"]},
230
+ {self.config.column_map["embedding"]},
231
+ {self.config.column_map["metadata"]}
232
+ )
233
+ VALUES
234
+ (
235
+ $id,
236
+ $document,
237
+ Untag(Knn::ToBinaryStringFloat($embedding), "FloatVector"),
238
+ $metadata
239
+ );
240
+ """
241
+
242
+ def _prepare_search_query(
243
+ self,
244
+ k: int,
245
+ filter: Optional[dict],
246
+ ) -> str:
247
+ where_statement = ""
248
+ if filter:
249
+ where_statement = "WHERE "
250
+ metadata_col = self.config.column_map["metadata"]
251
+ stmts = []
252
+ for key, value in filter.items():
253
+ stmts.append(f'JSON_VALUE({metadata_col}, "$.{key}") = "{value}"')
254
+
255
+ where_statement = f"WHERE {' AND '.join(stmts)}"
256
+
257
+ strategy = self.config.strategy
258
+ embedding_col = self.config.column_map["embedding"]
259
+
260
+ return f"""
261
+ DECLARE $embedding as List<Float>;
262
+
263
+ $TargetEmbedding = Knn::ToBinaryStringFloat($embedding);
264
+
265
+ SELECT
266
+ {self.config.column_map["id"]} as id,
267
+ {self.config.column_map["document"]} as document,
268
+ {self.config.column_map["metadata"]} as metadata,
269
+ Knn::{strategy}({embedding_col}, $TargetEmbedding) as score
270
+ FROM {self.config.table} {where_statement}
271
+ ORDER BY score
272
+ {self.sort_order}
273
+ LIMIT {k};
274
+ """
275
+
276
+ def _prepare_delete_query(self, ids: Optional[list[str]]) -> str:
277
+ query = f"DELETE FROM {self.config.table}"
278
+ if ids:
279
+ query += f" WHERE {self.config.column_map['id']} IN {str(ids)}"
280
+ return query
281
+
282
+ def add_texts(
283
+ self,
284
+ texts: Iterable[str],
285
+ metadatas: Optional[list[dict]] = None,
286
+ *,
287
+ ids: Optional[list[str]] = None,
288
+ **kwargs: Any,
289
+ ) -> list[str]:
290
+ """Run more texts through the embeddings and add to the vectorstore.
291
+
292
+ Args:
293
+ texts: Iterable of strings to add to the vectorstore.
294
+ metadatas: Optional list of metadatas associated with the texts.
295
+ ids: Optional list of IDs associated with the texts.
296
+ **kwargs: vectorstore specific parameters.
297
+ One of the kwargs should be `ids` which is a list of ids
298
+ associated with the texts.
299
+
300
+ Returns:
301
+ List of ids from adding the texts into the vectorstore.
302
+ """
303
+ texts_ = texts if isinstance(texts, (list, tuple)) else list(texts)
304
+
305
+ if ids is None:
306
+ ids = [sha1(t.encode("utf-8")).hexdigest() for t in texts_]
307
+
308
+ if metadatas and len(metadatas) != len(texts_):
309
+ msg = (
310
+ "The number of metadatas must match the number of texts."
311
+ f"Got {len(metadatas)} metadatas and {len(texts_)} texts."
312
+ )
313
+ raise ValueError(msg)
314
+
315
+ metadatas = metadatas if metadatas else [{} for _ in range(len(texts_))]
316
+
317
+ ydb = self._ydb_lib
318
+
319
+ for id, text, metadata in self.pgbar(
320
+ zip(ids, texts, metadatas),
321
+ desc="Inserting data...",
322
+ total=len(ids),
323
+ ):
324
+ embedding = self.embedding_function.embed_query(text)
325
+ self._execute_query(
326
+ self._insert_query,
327
+ {
328
+ "$id": id,
329
+ "$document": text,
330
+ "$embedding": (embedding, ydb.ListType(ydb.PrimitiveType.Float)),
331
+ "$metadata": (json.dumps(metadata), ydb.PrimitiveType.Json),
332
+ },
333
+ )
334
+
335
+ return ids
336
+
337
+ @classmethod
338
+ def from_texts(
339
+ cls,
340
+ texts: list[str],
341
+ embedding: Embeddings,
342
+ metadatas: Optional[list[dict]] = None,
343
+ *,
344
+ config: Optional[YDBSettings] = None,
345
+ ids: Optional[list[str]] = None,
346
+ **kwargs: Any,
347
+ ) -> YDB:
348
+ """Return YDB VectorStore initialized from texts and embeddings.
349
+
350
+ Args:
351
+ texts: Texts to add to the vectorstore.
352
+ embedding: Embedding function to use.
353
+ metadatas: Optional list of metadatas associated with the texts.
354
+ Default is None.
355
+ ids: Optional list of IDs associated with the texts.
356
+ kwargs: Additional keyword arguments.
357
+
358
+ Returns:
359
+ VectorStore: VectorStore initialized from texts and embeddings.
360
+ """
361
+ vs = cls(embedding, config, **kwargs)
362
+ vs.add_texts(texts=texts, metadatas=metadatas, ids=ids)
363
+ return vs
364
+
365
+ def delete(self, ids: Optional[list[str]] = None, **kwargs: Any) -> Optional[bool]:
366
+ """Delete by vector ID or other criteria.
367
+
368
+ Args:
369
+ ids: List of ids to delete. If None, delete all. Default is None.
370
+ **kwargs: Other keyword arguments that subclasses might use.
371
+
372
+ Returns:
373
+ Optional[bool]: True if deletion is successful,
374
+ False otherwise, None if not implemented.
375
+ """
376
+ query = self._prepare_delete_query(ids)
377
+ self._execute_query(query)
378
+ return True
379
+
380
+ def similarity_search(
381
+ self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any
382
+ ) -> list[Document]:
383
+ """Return docs most similar to query.
384
+
385
+ Args:
386
+ query: Input text.
387
+ k: Number of Documents to return. Defaults to 4.
388
+ **kwargs: Arguments to pass to the search method.
389
+
390
+ Returns:
391
+ List of Documents most similar to the query.
392
+ """
393
+ embedding = self.embedding_function.embed_query(query)
394
+ return self.similarity_search_by_vector(embedding, k, filter=filter, **kwargs)
395
+
396
+ def similarity_search_by_vector(
397
+ self,
398
+ embedding: list[float],
399
+ k: int = 4,
400
+ filter: Optional[dict] = None,
401
+ **kwargs: Any,
402
+ ) -> list[Document]:
403
+ """Return docs most similar to embedding vector.
404
+
405
+ Args:
406
+ embedding: Embedding to look up documents similar to.
407
+ k: Number of Documents to return. Defaults to 4.
408
+ **kwargs: Arguments to pass to the search method.
409
+
410
+ Returns:
411
+ List of Documents most similar to the query vector.
412
+ """
413
+ ydb = self._ydb_lib
414
+ query = self._prepare_search_query(k, filter=filter)
415
+ res = self._execute_query(
416
+ query,
417
+ params={"$embedding": (embedding, ydb.ListType(ydb.PrimitiveType.Float))},
418
+ )
419
+ return [
420
+ Document(
421
+ page_content=row["document"],
422
+ metadata=json.loads(row["metadata"]),
423
+ )
424
+ for row in res
425
+ ]
426
+
427
+ def similarity_search_with_score(
428
+ self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any
429
+ ) -> list[tuple[Document, float]]:
430
+ """Run similarity search with distance.
431
+
432
+ Args:
433
+ *args: Arguments to pass to the search method.
434
+ **kwargs: Arguments to pass to the search method.
435
+
436
+ Returns:
437
+ List of Tuples of (doc, similarity_score).
438
+ """
439
+ ydb = self._ydb_lib
440
+ embedding = self.embedding_function.embed_query(query)
441
+ query = self._prepare_search_query(k, filter=filter)
442
+ res = self._execute_query(
443
+ query,
444
+ params={"$embedding": (embedding, ydb.ListType(ydb.PrimitiveType.Float))},
445
+ )
446
+ return [
447
+ (
448
+ Document(
449
+ page_content=row[self.config.column_map["document"]],
450
+ metadata=json.loads(row["metadata"]),
451
+ ),
452
+ row["score"],
453
+ )
454
+ for row in res
455
+ ]
456
+
457
+ def drop(self) -> None:
458
+ """
459
+ Helper function: Drop data
460
+ """
461
+ self._execute_query(
462
+ f"DROP TABLE IF EXISTS `{self.config.table}`",
463
+ ddl=True,
464
+ )
@@ -0,0 +1,35 @@
1
+ [project]
2
+ name = "langchain-ydb"
3
+ version = "0.0.1" # AUTOVERSION
4
+ description = "An integration package connecting YDB and LangChain"
5
+ authors = []
6
+ readme = "README.md"
7
+ requires-python = ">=3.9,<4.0"
8
+ dependencies = [
9
+ "langchain-core (>=0.2.13,<0.4.0)",
10
+ "ydb-dbapi (>=0.1.11,<0.2.0)"
11
+ ]
12
+
13
+
14
+ [build-system]
15
+ requires = ["poetry-core>=2.0.0,<3.0.0"]
16
+ build-backend = "poetry.core.masonry.api"
17
+
18
+
19
+ [tool.poetry.group.dev.dependencies]
20
+ pytest = "^8.3.5"
21
+ ruff = "^0.11.2"
22
+ mypy = "^1.15.0"
23
+ pytest-asyncio = "^0.26.0"
24
+
25
+
26
+ [tool.ruff.lint]
27
+ select = [
28
+ "E", # pycodestyle
29
+ "F", # pyflakes
30
+ "I", # isort
31
+ ]
32
+
33
+
34
+ [tool.mypy]
35
+ disable_error_code = ["import-untyped"]