phuochungus commited on
Commit
42a588a
0 Parent(s):

save change

Browse files
packages/rag-redis/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2023 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.
packages/rag-redis/README.md ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # rag-redis
3
+
4
+ This template performs RAG using Redis (vector database) and OpenAI (LLM) on financial 10k filings docs for Nike.
5
+
6
+ It relies on the sentence transformer `all-MiniLM-L6-v2` for embedding chunks of the pdf and user questions.
7
+
8
+ ## Environment Setup
9
+
10
+ Set the `OPENAI_API_KEY` environment variable to access the [OpenAI](https://platform.openai.com) models:
11
+
12
+ ```bash
13
+ export OPENAI_API_KEY= <YOUR OPENAI API KEY>
14
+ ```
15
+
16
+ Set the following [Redis](https://redis.com/try-free) environment variables:
17
+
18
+ ```bash
19
+ export REDIS_HOST = <YOUR REDIS HOST>
20
+ export REDIS_PORT = <YOUR REDIS PORT>
21
+ export REDIS_USER = <YOUR REDIS USER NAME>
22
+ export REDIS_PASSWORD = <YOUR REDIS PASSWORD>
23
+ ```
24
+
25
+ ## Supported Settings
26
+ We use a variety of environment variables to configure this application
27
+
28
+ | Environment Variable | Description | Default Value |
29
+ |----------------------|-----------------------------------|---------------|
30
+ | `DEBUG` | Enable or disable Langchain debugging logs | True |
31
+ | `REDIS_HOST` | Hostname for the Redis server | "localhost" |
32
+ | `REDIS_PORT` | Port for the Redis server | 6379 |
33
+ | `REDIS_USER` | User for the Redis server | "" |
34
+ | `REDIS_PASSWORD` | Password for the Redis server | "" |
35
+ | `REDIS_URL` | Full URL for connecting to Redis | `None`, Constructed from user, password, host, and port if not provided |
36
+ | `INDEX_NAME` | Name of the vector index | "rag-redis" |
37
+
38
+ ## Usage
39
+
40
+ To use this package, you should first have the LangChain CLI and Pydantic installed in a Python virtual environment:
41
+
42
+ ```shell
43
+ pip install -U langchain-cli pydantic==1.10.13
44
+ ```
45
+
46
+ To create a new LangChain project and install this as the only package, you can do:
47
+
48
+ ```shell
49
+ langchain app new my-app --package rag-redis
50
+ ```
51
+
52
+ If you want to add this to an existing project, you can just run:
53
+ ```shell
54
+ langchain app add rag-redis
55
+ ```
56
+
57
+ And add the following code snippet to your `app/server.py` file:
58
+ ```python
59
+ from rag_redis.chain import chain as rag_redis_chain
60
+
61
+ add_routes(app, rag_redis_chain, path="/rag-redis")
62
+ ```
63
+
64
+ (Optional) Let's now configure LangSmith.
65
+ LangSmith will help us trace, monitor and debug LangChain applications.
66
+ LangSmith is currently in private beta, you can sign up [here](https://smith.langchain.com/).
67
+ If you don't have access, you can skip this section
68
+
69
+
70
+ ```shell
71
+ export LANGCHAIN_TRACING_V2=true
72
+ export LANGCHAIN_API_KEY=<your-api-key>
73
+ export LANGCHAIN_PROJECT=<your-project> # if not specified, defaults to "default"
74
+ ```
75
+
76
+ If you are inside this directory, then you can spin up a LangServe instance directly by:
77
+
78
+ ```shell
79
+ langchain serve
80
+ ```
81
+
82
+ This will start the FastAPI app with a server is running locally at
83
+ [http://localhost:8000](http://localhost:8000)
84
+
85
+ We can see all templates at [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)
86
+ We can access the playground at [http://127.0.0.1:8000/rag-redis/playground](http://127.0.0.1:8000/rag-redis/playground)
87
+
88
+ We can access the template from code with:
89
+
90
+ ```python
91
+ from langserve.client import RemoteRunnable
92
+
93
+ runnable = RemoteRunnable("http://localhost:8000/rag-redis")
94
+ ```
packages/rag-redis/ingest.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from langchain.document_loaders import UnstructuredFileLoader
4
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
5
+ from langchain.vectorstores import Redis
6
+ from rag_redis.config import INDEX_NAME, INDEX_SCHEMA, REDIS_URL
7
+ from langchain.embeddings import OpenAIEmbeddings
8
+
9
+
10
+ def ingest_documents():
11
+ """
12
+ Ingest PDF to Redis from the data/ directory that
13
+ """
14
+ # Load list of pdfs
15
+ data_path = "data/"
16
+ docs = [os.path.join(data_path, file) for file in os.listdir(data_path)]
17
+
18
+ print("Parsing docs", docs)
19
+
20
+ text_splitter = RecursiveCharacterTextSplitter(
21
+ chunk_size=1500, chunk_overlap=100, add_start_index=True
22
+ )
23
+ chunks = []
24
+ for doc in docs:
25
+ loader = UnstructuredFileLoader(doc, mode="single", strategy="fast")
26
+ chunks.extend(loader.load_and_split(text_splitter))
27
+
28
+ print("Chunk 0:", chunks[0])
29
+
30
+ print("Done preprocessing. Created", len(chunks), "chunks of the original pdf")
31
+
32
+ rds = Redis.from_texts(
33
+ texts=[chunk.page_content for chunk in chunks],
34
+ metadatas=[chunk.metadata for chunk in chunks],
35
+ embedding=OpenAIEmbeddings(),
36
+ index_name=INDEX_NAME,
37
+ redis_url=REDIS_URL,
38
+ )
39
+ rds.write_schema(INDEX_SCHEMA)
40
+
41
+
42
+ if __name__ == "__main__":
43
+ ingest_documents()
packages/rag-redis/poetry.lock ADDED
The diff for this file is too large to render. See raw diff
 
packages/rag-redis/pyproject.toml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.poetry]
2
+ name = "rag-redis"
3
+ version = "0.0.1"
4
+ description = "Run a RAG app backed by OpenAI, HuggingFace, and Redis as a vector database"
5
+ authors = [
6
+ "Tyler Hutcherson <tyler.hutcherson@redis.com>",
7
+ "Sam Partee <sam.partee@redis.com>",
8
+ ]
9
+ readme = "README.md"
10
+
11
+ [tool.poetry.dependencies]
12
+ python = ">=3.9,<3.13"
13
+ langchain = ">=0.0.325"
14
+ fastapi = "^0.104.0"
15
+ sse-starlette = "^1.6.5"
16
+ openai = "<2"
17
+ sentence-transformers = "2.2.2"
18
+ redis = "5.0.1"
19
+ tiktoken = "0.5.1"
20
+ pdf2image = "1.16.3"
21
+
22
+ [tool.poetry.dependencies.unstructured]
23
+ version = "^0.10.27"
24
+ extras = [
25
+ "pdf",
26
+ ]
27
+
28
+ [tool.poetry.group.dev.dependencies]
29
+ poethepoet = "^0.24.1"
30
+ langchain-cli = ">=0.0.15"
31
+
32
+ [tool.langserve]
33
+ export_module = "rag_redis.chain"
34
+ export_attr = "chain"
35
+
36
+ [tool.templates-hub]
37
+ use-case = "rag"
38
+ author = "Redis"
39
+ integrations = ["OpenAI", "Redis", "HuggingFace"]
40
+ tags = ["vectordbs"]
41
+
42
+ [tool.poe.tasks.start]
43
+ cmd = "uvicorn langchain_cli.dev_scripts:create_demo_server --reload --port $port --host $host"
44
+ args = [
45
+ { name = "port", help = "port to run on", default = "8000" },
46
+ { name = "host", help = "host to run on", default = "127.0.0.1" },
47
+ ]
48
+
49
+ [build-system]
50
+ requires = [
51
+ "poetry-core",
52
+ ]
53
+ build-backend = "poetry.core.masonry.api"
packages/rag-redis/rag_redis.ipynb ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "681a5d1e",
6
+ "metadata": {},
7
+ "source": [
8
+ "## Connect to RAG App\n",
9
+ "\n",
10
+ "Assuming you are already running this server:\n",
11
+ "```bash\n",
12
+ "langserve start\n",
13
+ "```"
14
+ ]
15
+ },
16
+ {
17
+ "cell_type": "code",
18
+ "execution_count": 37,
19
+ "id": "d774be2a",
20
+ "metadata": {},
21
+ "outputs": [
22
+ {
23
+ "name": "stdout",
24
+ "output_type": "stream",
25
+ "text": [
26
+ "Nike's revenue in 2023 was $51.2 billion. \n",
27
+ "\n",
28
+ "Source: 'data/nke-10k-2023.pdf', Start Index: '146100'\n"
29
+ ]
30
+ }
31
+ ],
32
+ "source": [
33
+ "from langserve.client import RemoteRunnable\n",
34
+ "\n",
35
+ "rag_redis = RemoteRunnable(\"http://localhost:8000/rag-redis\")\n",
36
+ "\n",
37
+ "print(rag_redis.invoke(\"What was Nike's revenue in 2023?\"))"
38
+ ]
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "execution_count": 43,
43
+ "id": "07ae0005",
44
+ "metadata": {},
45
+ "outputs": [
46
+ {
47
+ "name": "stdout",
48
+ "output_type": "stream",
49
+ "text": [
50
+ "As of May 31, 2023, Nike had approximately 83,700 employees worldwide. This information can be found in the first piece of context provided. (source: data/nke-10k-2023.pdf, start_index: 32532)\n"
51
+ ]
52
+ }
53
+ ],
54
+ "source": [
55
+ "print(rag_redis.invoke(\"How many employees work at Nike?\"))"
56
+ ]
57
+ },
58
+ {
59
+ "cell_type": "code",
60
+ "execution_count": null,
61
+ "id": "4a6b9f00",
62
+ "metadata": {},
63
+ "outputs": [],
64
+ "source": []
65
+ }
66
+ ],
67
+ "metadata": {
68
+ "kernelspec": {
69
+ "display_name": "Python 3 (ipykernel)",
70
+ "language": "python",
71
+ "name": "python3"
72
+ },
73
+ "language_info": {
74
+ "codemirror_mode": {
75
+ "name": "ipython",
76
+ "version": 3
77
+ },
78
+ "file_extension": ".py",
79
+ "mimetype": "text/x-python",
80
+ "name": "python",
81
+ "nbconvert_exporter": "python",
82
+ "pygments_lexer": "ipython3",
83
+ "version": "3.10.6"
84
+ }
85
+ },
86
+ "nbformat": 4,
87
+ "nbformat_minor": 5
88
+ }
packages/rag-redis/rag_redis/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from dotenv import load_dotenv
2
+
3
+ load_dotenv()
packages/rag-redis/rag_redis/chain.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain.chat_models import ChatOpenAI
2
+ from langchain.embeddings import OpenAIEmbeddings
3
+ from langchain.prompts import ChatPromptTemplate
4
+ from langchain.pydantic_v1 import BaseModel
5
+ from langchain.schema.output_parser import StrOutputParser
6
+ from langchain.schema.runnable import RunnableParallel, RunnablePassthrough
7
+ from langchain.vectorstores import Redis
8
+
9
+ from rag_redis.config import (
10
+ INDEX_NAME,
11
+ INDEX_SCHEMA,
12
+ REDIS_URL,
13
+ )
14
+
15
+
16
+ # Make this look better in the docs.
17
+ class Question(BaseModel):
18
+ __root__: str
19
+
20
+
21
+ # Init Embeddings
22
+ embedder = OpenAIEmbeddings()
23
+
24
+ # Connect to pre-loaded vectorstore
25
+ # run the ingest.py script to populate this
26
+ vectorstore = Redis.from_existing_index(
27
+ embedding=embedder, index_name=INDEX_NAME, schema=INDEX_SCHEMA, redis_url=REDIS_URL
28
+ )
29
+ retriever = vectorstore.as_retriever(search_type="mmr")
30
+
31
+
32
+ # Define our prompt
33
+ template = """
34
+ Use the following pieces of context from ApartmentManagementDocument and
35
+ ProjectManagementDocument to answer the question. Do not make up an answer
36
+ if there is no context provided to help answer it. Answer the question in
37
+ the same language as the question is asked.
38
+
39
+ Context:
40
+ ---------
41
+ {context}
42
+
43
+ ---------
44
+ Question: {question}
45
+ ---------
46
+
47
+ Answer:
48
+ """
49
+
50
+
51
+ prompt = ChatPromptTemplate.from_template(template)
52
+
53
+ # Cache
54
+ from langchain.cache import InMemoryCache
55
+ from langchain.globals import set_llm_cache
56
+ set_llm_cache(InMemoryCache())
57
+
58
+ # RAG Chain
59
+ model = ChatOpenAI(model_name="gpt-3.5-turbo")
60
+ chain = (
61
+ RunnableParallel({"context": retriever, "question": RunnablePassthrough()})
62
+ | prompt
63
+ | model
64
+ | StrOutputParser()
65
+ ).with_types(input_type=Question)
packages/rag-redis/rag_redis/config.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+
4
+ def get_boolean_env_var(var_name, default_value=False):
5
+ """Retrieve the boolean value of an environment variable.
6
+
7
+ Args:
8
+ var_name (str): The name of the environment variable to retrieve.
9
+ default_value (bool): The default value to return if the variable
10
+ is not found.
11
+
12
+ Returns:
13
+ bool: The value of the environment variable, interpreted as a boolean.
14
+ """
15
+ true_values = {"true", "1", "t", "y", "yes"}
16
+ false_values = {"false", "0", "f", "n", "no"}
17
+
18
+ # Retrieve the environment variable's value
19
+ value = os.getenv(var_name, "").lower()
20
+
21
+ # Decide the boolean value based on the content of the string
22
+ if value in true_values:
23
+ return True
24
+ elif value in false_values:
25
+ return False
26
+ else:
27
+ return default_value
28
+
29
+
30
+ # Check for openai API key
31
+ if "OPENAI_API_KEY" not in os.environ:
32
+ raise Exception("Must provide an OPENAI_API_KEY as an env var.")
33
+
34
+
35
+ # Whether or not to enable langchain debugging
36
+ DEBUG = get_boolean_env_var("DEBUG", False)
37
+ # Set DEBUG env var to "true" if you wish to enable LC debugging module
38
+ if DEBUG:
39
+ import langchain
40
+
41
+ langchain.debug = True
42
+
43
+
44
+ # Redis Connection Information
45
+ REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
46
+ REDIS_PORT = int(os.getenv("REDIS_PORT", 6379))
47
+
48
+
49
+ def format_redis_conn_from_env():
50
+ redis_url = os.getenv("REDIS_URL", None)
51
+ if redis_url:
52
+ return redis_url
53
+ else:
54
+ using_ssl = get_boolean_env_var("REDIS_SSL", False)
55
+ start = "rediss://" if using_ssl else "redis://"
56
+
57
+ # if using RBAC
58
+ password = os.getenv("REDIS_PASSWORD", None)
59
+ username = os.getenv("REDIS_USERNAME", "default")
60
+ if password is not None:
61
+ start += f"{username}:{password}@"
62
+
63
+ return start + f"{REDIS_HOST}:{REDIS_PORT}"
64
+
65
+
66
+ REDIS_URL = format_redis_conn_from_env()
67
+
68
+ # Vector Index Configuration
69
+ INDEX_NAME = os.getenv("INDEX_NAME", "rag-redis")
70
+
71
+ # Embedding model
72
+
73
+ current_file_path = os.path.abspath(__file__)
74
+ parent_dir = os.path.dirname(current_file_path)
75
+ schema_path = os.path.join(parent_dir, "schema.yml")
76
+ INDEX_SCHEMA = schema_path
packages/rag-redis/rag_redis/schema.yml ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ numeric:
2
+ - name: start_index
3
+ no_index: false
4
+ sortable: false
5
+ text:
6
+ - name: source
7
+ no_index: false
8
+ no_stem: false
9
+ sortable: false
10
+ weight: 1
11
+ withsuffixtrie: false
12
+ - name: content
13
+ no_index: false
14
+ no_stem: false
15
+ sortable: false
16
+ weight: 1
17
+ withsuffixtrie: false
18
+ vector:
19
+ - algorithm: FLAT
20
+ datatype: FLOAT32
21
+ dims: 1536
22
+ distance_metric: COSINE
23
+ name: content_vector