langchain-redis 0.0.1rc1__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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 LangChain, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,279 @@
1
+ Metadata-Version: 2.1
2
+ Name: langchain-redis
3
+ Version: 0.0.1rc1
4
+ Summary: An integration package connecting Redis and LangChain
5
+ Home-page: https://github.com/langchain-ai/langchain-redis
6
+ License: MIT
7
+ Author: Brian Sam-Bodden
8
+ Author-email: bsb@redis.com
9
+ Requires-Python: >=3.9,<4.0
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Requires-Dist: langchain-core (>=0.1.52,<0.3)
17
+ Requires-Dist: numpy (>=1,<2)
18
+ Requires-Dist: python-ulid (>=2.7.0,<3.0.0)
19
+ Requires-Dist: redisvl (>=0.2.3,<0.3.0)
20
+ Requires-Dist: sentence-transformers (>=3.0.1,<4.0.0)
21
+ Project-URL: Repository, https://github.com/langchain-ai/langchain-redis
22
+ Project-URL: Source Code, https://github.com/langchain-ai/langchain-redis/tree/main/libs/redis
23
+ Description-Content-Type: text/markdown
24
+
25
+ # langchain-redis
26
+
27
+ This package contains the LangChain integration with Redis, providing powerful tools for vector storage, semantic caching, and chat history management.
28
+
29
+ ## Installation
30
+
31
+ ```bash
32
+ pip install -U langchain-redis
33
+ ```
34
+
35
+ This will install the package along with its dependencies, including `redis`, `redisvl`, and `ulid`.
36
+
37
+ ## Configuration
38
+
39
+ To use this package, you need to have a Redis instance running. You can configure the connection by setting the following environment variable:
40
+
41
+ ```bash
42
+ export REDIS_URL="redis://username:password@localhost:6379"
43
+ ```
44
+
45
+ Alternatively, you can pass the Redis URL directly when initializing the components or use the `RedisConfig` class for more detailed configuration.
46
+
47
+ ## Features
48
+
49
+ ### 1. Vector Store
50
+
51
+ The `RedisVectorStore` class provides a vector database implementation using Redis.
52
+
53
+ #### Usage
54
+
55
+ ```python
56
+ from langchain_redis import RedisVectorStore, RedisConfig
57
+ from langchain_core.embeddings import Embeddings
58
+
59
+ embeddings = Embeddings() # Your preferred embedding model
60
+
61
+ config = RedisConfig(
62
+ index_name="my_vectors",
63
+ redis_url="redis://localhost:6379",
64
+ distance_metric="COSINE" # Options: COSINE, L2, IP
65
+ )
66
+
67
+ vector_store = RedisVectorStore(embeddings, config=config)
68
+
69
+ # Adding documents
70
+ texts = ["Document 1 content", "Document 2 content"]
71
+ metadatas = [{"source": "file1"}, {"source": "file2"}]
72
+ vector_store.add_texts(texts, metadatas=metadatas)
73
+
74
+ # Adding documents with custom keys
75
+ custom_keys = ["doc1", "doc2"]
76
+ vector_store.add_texts(texts, metadatas=metadatas, keys=custom_keys)
77
+
78
+ # Similarity search
79
+ query = "Sample query"
80
+ docs = vector_store.similarity_search(query, k=2)
81
+
82
+ # Similarity search with score
83
+ docs_and_scores = vector_store.similarity_search_with_score(query, k=2)
84
+
85
+ # Similarity search with filtering
86
+ filter_expr = Tag("category") == "science"
87
+ filtered_docs = vector_store.similarity_search(query, k=2, filter=filter_expr)
88
+
89
+ # Maximum marginal relevance search
90
+ docs = vector_store.max_marginal_relevance_search(query, k=2, fetch_k=10)
91
+ ```
92
+
93
+ #### Features
94
+ - Efficient vector storage and retrieval
95
+ - Support for metadata filtering
96
+ - Multiple distance metrics: Cosine similarity, L2, and Inner Product
97
+ - Maximum marginal relevance search
98
+ - Custom key support for document indexing
99
+
100
+ ### 2. Cache
101
+
102
+ The `RedisCache` and `RedisSemanticCache` classes provide caching mechanisms for LLM calls.
103
+
104
+ #### Usage
105
+
106
+ ```python
107
+ from langchain_redis import RedisCache, RedisSemanticCache
108
+ from langchain_core.language_models import LLM
109
+ from langchain_core.embeddings import Embeddings
110
+
111
+ # Standard cache
112
+ cache = RedisCache(redis_url="redis://localhost:6379", ttl=3600)
113
+
114
+ # Semantic cache
115
+ embeddings = Embeddings() # Your preferred embedding model
116
+ semantic_cache = RedisSemanticCache(
117
+ redis_url="redis://localhost:6379",
118
+ embedding=embeddings,
119
+ distance_threshold=0.1
120
+ )
121
+
122
+ # Using cache with an LLM
123
+ llm = LLM(cache=cache) # or LLM(cache=semantic_cache)
124
+
125
+ # Async cache operations
126
+ await cache.aupdate("prompt", "llm_string", [Generation(text="cached_response")])
127
+ cached_result = await cache.alookup("prompt", "llm_string")
128
+ ```
129
+
130
+ #### Features
131
+ - Efficient caching of LLM responses
132
+ - TTL support for automatic cache expiration
133
+ - Semantic caching for similarity-based retrieval
134
+ - Asynchronous cache operations
135
+
136
+ ### 3. Chat History
137
+
138
+ The `RedisChatMessageHistory` class provides a Redis-based storage for chat message history.
139
+
140
+ #### Usage
141
+
142
+ ```python
143
+ from langchain_redis import RedisChatMessageHistory
144
+ from langchain_core.messages import HumanMessage, AIMessage, SystemMessage
145
+
146
+ history = RedisChatMessageHistory(
147
+ session_id="user_123",
148
+ redis_url="redis://localhost:6379",
149
+ ttl=3600 # Optional: set TTL for message expiration
150
+ )
151
+
152
+ # Adding messages
153
+ history.add_user_message("Hello, AI!")
154
+ history.add_ai_message("Hello, human! How can I assist you today?")
155
+ history.add_message(SystemMessage(content="This is a system message"))
156
+
157
+ # Retrieving messages
158
+ messages = history.messages
159
+
160
+ # Searching messages
161
+ results = history.search_messages("assist")
162
+
163
+ # Get the number of messages
164
+ message_count = len(history)
165
+
166
+ # Clear history
167
+ history.clear()
168
+ ```
169
+
170
+ #### Features
171
+ - Persistent storage of chat messages
172
+ - Support for different message types (Human, AI, System)
173
+ - Message searching capabilities
174
+ - Automatic expiration with TTL support
175
+ - Message count functionality
176
+
177
+ ## Advanced Configuration
178
+
179
+ The `RedisConfig` class allows for detailed configuration of the Redis integration:
180
+
181
+ ```python
182
+ from langchain_redis import RedisConfig
183
+
184
+ config = RedisConfig(
185
+ index_name="my_index",
186
+ redis_url="redis://localhost:6379",
187
+ distance_metric="COSINE",
188
+ key_prefix="my_prefix",
189
+ vector_datatype="FLOAT32",
190
+ storage_type="hash",
191
+ metadata_schema=[
192
+ {"name": "category", "type": "tag"},
193
+ {"name": "price", "type": "numeric"}
194
+ ]
195
+ )
196
+ ```
197
+
198
+ Refer to the inline documentation for detailed information on these configuration options.
199
+
200
+ ## Error Handling and Logging
201
+
202
+ The package uses Python's standard logging module. You can configure logging to get more information about the package's operations:
203
+
204
+ ```python
205
+ import logging
206
+ logging.basicConfig(level=logging.INFO)
207
+ ```
208
+
209
+ Error handling is done through custom exceptions. Make sure to handle these exceptions in your application code.
210
+
211
+ ## Performance Considerations
212
+
213
+ - For large datasets, consider using batched operations when adding documents to the vector store.
214
+ - Adjust the `k` and `fetch_k` parameters in similarity searches to balance between accuracy and performance.
215
+ - Use appropriate indexing algorithms (FLAT, HNSW) based on your dataset size and query requirements.
216
+
217
+ ## Examples
218
+
219
+ For more detailed examples and use cases, please refer to the `docs/` directory in this repository.
220
+
221
+ ## Contributing / Development
222
+
223
+ ### Unit Tests
224
+
225
+ To install dependencies for unit tests:
226
+
227
+ ```bash
228
+ poetry install --with test
229
+ ```
230
+
231
+ To run unit tests:
232
+
233
+ ```bash
234
+ make test
235
+ ```
236
+
237
+ To run a specific test:
238
+
239
+ ```bash
240
+ TEST_FILE=tests/unit_tests/test_imports.py make test
241
+ ```
242
+
243
+ ## Integration Tests
244
+
245
+ You would need an OpenAI API Key to run the integration tests:
246
+
247
+ ```bash
248
+ export OPENAI_API_KEY=sk-J3nnYJ3nnYWh0Can1Turnt0Ug1VeMe50mth1n1cAnH0ld0n2
249
+ ```
250
+
251
+ To install dependencies for integration tests:
252
+
253
+ ```bash
254
+ poetry install --with test,test_integration
255
+ ```
256
+
257
+ To run integration tests:
258
+
259
+ ```bash
260
+ make integration_tests
261
+ ```
262
+
263
+ ## Local Development
264
+
265
+ Install langchain-redis development requirements (for running langchain, running examples, linting, formatting, tests, and coverage):
266
+
267
+ ```bash
268
+ poetry install --with lint,typing,test,test_integration
269
+ ```
270
+
271
+ Then verify dependency installation:
272
+
273
+ ```bash
274
+ make lint
275
+ ```
276
+
277
+ ## License
278
+
279
+ This project is licensed under the MIT License (LICENSE).
@@ -0,0 +1,255 @@
1
+ # langchain-redis
2
+
3
+ This package contains the LangChain integration with Redis, providing powerful tools for vector storage, semantic caching, and chat history management.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install -U langchain-redis
9
+ ```
10
+
11
+ This will install the package along with its dependencies, including `redis`, `redisvl`, and `ulid`.
12
+
13
+ ## Configuration
14
+
15
+ To use this package, you need to have a Redis instance running. You can configure the connection by setting the following environment variable:
16
+
17
+ ```bash
18
+ export REDIS_URL="redis://username:password@localhost:6379"
19
+ ```
20
+
21
+ Alternatively, you can pass the Redis URL directly when initializing the components or use the `RedisConfig` class for more detailed configuration.
22
+
23
+ ## Features
24
+
25
+ ### 1. Vector Store
26
+
27
+ The `RedisVectorStore` class provides a vector database implementation using Redis.
28
+
29
+ #### Usage
30
+
31
+ ```python
32
+ from langchain_redis import RedisVectorStore, RedisConfig
33
+ from langchain_core.embeddings import Embeddings
34
+
35
+ embeddings = Embeddings() # Your preferred embedding model
36
+
37
+ config = RedisConfig(
38
+ index_name="my_vectors",
39
+ redis_url="redis://localhost:6379",
40
+ distance_metric="COSINE" # Options: COSINE, L2, IP
41
+ )
42
+
43
+ vector_store = RedisVectorStore(embeddings, config=config)
44
+
45
+ # Adding documents
46
+ texts = ["Document 1 content", "Document 2 content"]
47
+ metadatas = [{"source": "file1"}, {"source": "file2"}]
48
+ vector_store.add_texts(texts, metadatas=metadatas)
49
+
50
+ # Adding documents with custom keys
51
+ custom_keys = ["doc1", "doc2"]
52
+ vector_store.add_texts(texts, metadatas=metadatas, keys=custom_keys)
53
+
54
+ # Similarity search
55
+ query = "Sample query"
56
+ docs = vector_store.similarity_search(query, k=2)
57
+
58
+ # Similarity search with score
59
+ docs_and_scores = vector_store.similarity_search_with_score(query, k=2)
60
+
61
+ # Similarity search with filtering
62
+ filter_expr = Tag("category") == "science"
63
+ filtered_docs = vector_store.similarity_search(query, k=2, filter=filter_expr)
64
+
65
+ # Maximum marginal relevance search
66
+ docs = vector_store.max_marginal_relevance_search(query, k=2, fetch_k=10)
67
+ ```
68
+
69
+ #### Features
70
+ - Efficient vector storage and retrieval
71
+ - Support for metadata filtering
72
+ - Multiple distance metrics: Cosine similarity, L2, and Inner Product
73
+ - Maximum marginal relevance search
74
+ - Custom key support for document indexing
75
+
76
+ ### 2. Cache
77
+
78
+ The `RedisCache` and `RedisSemanticCache` classes provide caching mechanisms for LLM calls.
79
+
80
+ #### Usage
81
+
82
+ ```python
83
+ from langchain_redis import RedisCache, RedisSemanticCache
84
+ from langchain_core.language_models import LLM
85
+ from langchain_core.embeddings import Embeddings
86
+
87
+ # Standard cache
88
+ cache = RedisCache(redis_url="redis://localhost:6379", ttl=3600)
89
+
90
+ # Semantic cache
91
+ embeddings = Embeddings() # Your preferred embedding model
92
+ semantic_cache = RedisSemanticCache(
93
+ redis_url="redis://localhost:6379",
94
+ embedding=embeddings,
95
+ distance_threshold=0.1
96
+ )
97
+
98
+ # Using cache with an LLM
99
+ llm = LLM(cache=cache) # or LLM(cache=semantic_cache)
100
+
101
+ # Async cache operations
102
+ await cache.aupdate("prompt", "llm_string", [Generation(text="cached_response")])
103
+ cached_result = await cache.alookup("prompt", "llm_string")
104
+ ```
105
+
106
+ #### Features
107
+ - Efficient caching of LLM responses
108
+ - TTL support for automatic cache expiration
109
+ - Semantic caching for similarity-based retrieval
110
+ - Asynchronous cache operations
111
+
112
+ ### 3. Chat History
113
+
114
+ The `RedisChatMessageHistory` class provides a Redis-based storage for chat message history.
115
+
116
+ #### Usage
117
+
118
+ ```python
119
+ from langchain_redis import RedisChatMessageHistory
120
+ from langchain_core.messages import HumanMessage, AIMessage, SystemMessage
121
+
122
+ history = RedisChatMessageHistory(
123
+ session_id="user_123",
124
+ redis_url="redis://localhost:6379",
125
+ ttl=3600 # Optional: set TTL for message expiration
126
+ )
127
+
128
+ # Adding messages
129
+ history.add_user_message("Hello, AI!")
130
+ history.add_ai_message("Hello, human! How can I assist you today?")
131
+ history.add_message(SystemMessage(content="This is a system message"))
132
+
133
+ # Retrieving messages
134
+ messages = history.messages
135
+
136
+ # Searching messages
137
+ results = history.search_messages("assist")
138
+
139
+ # Get the number of messages
140
+ message_count = len(history)
141
+
142
+ # Clear history
143
+ history.clear()
144
+ ```
145
+
146
+ #### Features
147
+ - Persistent storage of chat messages
148
+ - Support for different message types (Human, AI, System)
149
+ - Message searching capabilities
150
+ - Automatic expiration with TTL support
151
+ - Message count functionality
152
+
153
+ ## Advanced Configuration
154
+
155
+ The `RedisConfig` class allows for detailed configuration of the Redis integration:
156
+
157
+ ```python
158
+ from langchain_redis import RedisConfig
159
+
160
+ config = RedisConfig(
161
+ index_name="my_index",
162
+ redis_url="redis://localhost:6379",
163
+ distance_metric="COSINE",
164
+ key_prefix="my_prefix",
165
+ vector_datatype="FLOAT32",
166
+ storage_type="hash",
167
+ metadata_schema=[
168
+ {"name": "category", "type": "tag"},
169
+ {"name": "price", "type": "numeric"}
170
+ ]
171
+ )
172
+ ```
173
+
174
+ Refer to the inline documentation for detailed information on these configuration options.
175
+
176
+ ## Error Handling and Logging
177
+
178
+ The package uses Python's standard logging module. You can configure logging to get more information about the package's operations:
179
+
180
+ ```python
181
+ import logging
182
+ logging.basicConfig(level=logging.INFO)
183
+ ```
184
+
185
+ Error handling is done through custom exceptions. Make sure to handle these exceptions in your application code.
186
+
187
+ ## Performance Considerations
188
+
189
+ - For large datasets, consider using batched operations when adding documents to the vector store.
190
+ - Adjust the `k` and `fetch_k` parameters in similarity searches to balance between accuracy and performance.
191
+ - Use appropriate indexing algorithms (FLAT, HNSW) based on your dataset size and query requirements.
192
+
193
+ ## Examples
194
+
195
+ For more detailed examples and use cases, please refer to the `docs/` directory in this repository.
196
+
197
+ ## Contributing / Development
198
+
199
+ ### Unit Tests
200
+
201
+ To install dependencies for unit tests:
202
+
203
+ ```bash
204
+ poetry install --with test
205
+ ```
206
+
207
+ To run unit tests:
208
+
209
+ ```bash
210
+ make test
211
+ ```
212
+
213
+ To run a specific test:
214
+
215
+ ```bash
216
+ TEST_FILE=tests/unit_tests/test_imports.py make test
217
+ ```
218
+
219
+ ## Integration Tests
220
+
221
+ You would need an OpenAI API Key to run the integration tests:
222
+
223
+ ```bash
224
+ export OPENAI_API_KEY=sk-J3nnYJ3nnYWh0Can1Turnt0Ug1VeMe50mth1n1cAnH0ld0n2
225
+ ```
226
+
227
+ To install dependencies for integration tests:
228
+
229
+ ```bash
230
+ poetry install --with test,test_integration
231
+ ```
232
+
233
+ To run integration tests:
234
+
235
+ ```bash
236
+ make integration_tests
237
+ ```
238
+
239
+ ## Local Development
240
+
241
+ Install langchain-redis development requirements (for running langchain, running examples, linting, formatting, tests, and coverage):
242
+
243
+ ```bash
244
+ poetry install --with lint,typing,test,test_integration
245
+ ```
246
+
247
+ Then verify dependency installation:
248
+
249
+ ```bash
250
+ make lint
251
+ ```
252
+
253
+ ## License
254
+
255
+ This project is licensed under the MIT License (LICENSE).
@@ -0,0 +1,12 @@
1
+ from langchain_redis.cache import RedisCache, RedisSemanticCache
2
+ from langchain_redis.chat_message_history import RedisChatMessageHistory
3
+ from langchain_redis.config import RedisConfig
4
+ from langchain_redis.vectorstores import RedisVectorStore
5
+
6
+ __all__ = [
7
+ "RedisVectorStore",
8
+ "RedisConfig",
9
+ "RedisCache",
10
+ "RedisSemanticCache",
11
+ "RedisChatMessageHistory",
12
+ ]