Sivabalan Thirunavukkarasu commited on
Commit
163701b
·
unverified ·
1 Parent(s): 441f971

W4D1 Midterm - Building and Deploying a Custom RAG Application

Browse files
Files changed (6) hide show
  1. .gitignore +7 -0
  2. Dockerfile +10 -0
  3. app.py +150 -0
  4. chainlit.md +1 -0
  5. data/airbnb_financials.pdf +0 -0
  6. requirements.txt +10 -0
.gitignore ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ .env
2
+ __pycache__/
3
+ .chainlit
4
+ *.faiss
5
+ *.pkl
6
+ .files
7
+ airbnb-auditor/.git*
Dockerfile ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11
2
+ RUN useradd -m -u 1000 user
3
+ ENV HOME=/home/user \
4
+ PATH=/home/user/.local/bin:$PATH
5
+ WORKDIR $HOME/app
6
+ COPY . .
7
+ RUN chown -R user:user .
8
+ RUN pip install -r requirements.txt
9
+ USER user
10
+ CMD ["chainlit", "run", "app.py", "--port", "7860"]
app.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import chainlit as cl
3
+ from dotenv import load_dotenv
4
+ from operator import itemgetter
5
+ from langchain_huggingface import HuggingFaceEndpoint
6
+ from langchain_community.document_loaders import PyMuPDFLoader
7
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
8
+ from langchain_community.vectorstores import Qdrant
9
+ from langchain_openai.embeddings import OpenAIEmbeddings
10
+ from langchain_core.prompts import PromptTemplate
11
+ from langchain.schema.runnable.config import RunnableConfig
12
+
13
+ # GLOBAL SCOPE - ENTIRE APPLICATION HAS ACCESS TO VALUES SET IN THIS SCOPE #
14
+ # ---- ENV VARIABLES ---- #
15
+ """
16
+ This function will load our environment file (.env) if it is present.
17
+
18
+ NOTE: Make sure that .env is in your .gitignore file - it is by default, but please ensure it remains there.
19
+ """
20
+ load_dotenv()
21
+
22
+ """
23
+ We will load our environment variables here.
24
+ """
25
+ HF_LLM_ENDPOINT = os.environ["HF_LLM_ENDPOINT"]
26
+ HF_TOKEN = os.environ["HF_TOKEN"]
27
+
28
+ # ---- GLOBAL DECLARATIONS ---- #
29
+
30
+ # -- RETRIEVAL -- #
31
+ """
32
+ 1. Load Documents from PDF File
33
+ 2. Split Documents into Chunks
34
+ 3. Load HuggingFace Embeddings (remember to use the URL we set above)
35
+ 4. Index Files if they do not exist, otherwise load the vectorstore
36
+ """
37
+ document_loader = PyMuPDFLoader("./data/airbnb_financials.pdf")
38
+ documents = document_loader.load()
39
+
40
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=30)
41
+ split_documents = text_splitter.split_documents(documents)
42
+
43
+ openai_embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
44
+
45
+ if os.path.exists("./data/vectorstore"):
46
+ vectorstore = Qdrant.from_existing_collection(
47
+ embeddings=openai_embeddings,
48
+ collection_name="airbnb_financials",
49
+ path="./data/vectorstore",
50
+ batch_size=32,
51
+ )
52
+ print("Loaded Vectorstore")
53
+ else:
54
+ print("Indexing Files")
55
+ os.makedirs("./data/vectorstore", exist_ok=True)
56
+ vectorstore = Qdrant.from_documents(
57
+ documents=split_documents,
58
+ embedding=openai_embeddings,
59
+ path="./data/vectorstore",
60
+ collection_name="airbnb_financials",
61
+ batch_size=32,
62
+ )
63
+
64
+ retriever = vectorstore.as_retriever()
65
+
66
+ # -- AUGMENTED -- #
67
+ """
68
+ 1. Define a String Template
69
+ 2. Create a Prompt Template from the String Template
70
+ """
71
+ RAG_PROMPT_TEMPLATE = """\
72
+ <|start_header_id|>system<|end_header_id|>
73
+ You are a helpful assistant. You answer user questions based on provided context. If you can't answer the question with the provided context, say you don't know. Do not provide relevant context in response unless explicitly asked.<|eot_id|>
74
+
75
+ <|start_header_id|>user<|end_header_id|>
76
+ User Query:
77
+ {query}
78
+
79
+ Context:
80
+ {context}<|eot_id|>
81
+
82
+ <|start_header_id|>assistant<|end_header_id|>
83
+ """
84
+
85
+ rag_prompt = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE)
86
+
87
+ # -- GENERATION -- #
88
+ """
89
+ 1. Create a HuggingFaceEndpoint for the LLM
90
+ """
91
+ hf_llm = HuggingFaceEndpoint(
92
+ endpoint_url=HF_LLM_ENDPOINT,
93
+ max_new_tokens=512,
94
+ top_k=10,
95
+ top_p=0.95,
96
+ temperature=0.3,
97
+ repetition_penalty=1.15,
98
+ huggingfacehub_api_token=HF_TOKEN,
99
+ )
100
+
101
+ @cl.author_rename
102
+ def rename(original_author: str):
103
+ """
104
+ This function can be used to rename the 'author' of a message.
105
+
106
+ In this case, we're overriding the 'Assistant' author to be 'Paul Graham Essay Bot'.
107
+ """
108
+ rename_dict = {
109
+ "Assistant" : "AirBnB Auditor"
110
+ }
111
+ return rename_dict.get(original_author, original_author)
112
+
113
+ @cl.on_chat_start
114
+ async def start_chat():
115
+ """
116
+ This function will be called at the start of every user session.
117
+
118
+ We will build our LCEL RAG chain here, and store it in the user session.
119
+
120
+ The user session is a dictionary that is unique to each user session, and is stored in the memory of the server.
121
+ """
122
+
123
+ lcel_rag_chain = (
124
+ {"context": itemgetter("query") | retriever, "query": itemgetter("query")}
125
+ | rag_prompt | hf_llm
126
+ )
127
+
128
+ cl.user_session.set("lcel_rag_chain", lcel_rag_chain)
129
+
130
+ @cl.on_message
131
+ async def main(message: cl.Message):
132
+ """
133
+ This function will be called every time a message is recieved from a session.
134
+
135
+ We will use the LCEL RAG chain to generate a response to the user query.
136
+
137
+ The LCEL RAG chain is stored in the user session, and is unique to each user session - this is why we can access it here.
138
+ """
139
+ lcel_rag_chain = cl.user_session.get("lcel_rag_chain")
140
+
141
+ msg = cl.Message(content="")
142
+
143
+ for chunk in await cl.make_async(lcel_rag_chain.stream)(
144
+ {"query": message.content},
145
+ config=RunnableConfig(callbacks=[cl.LangchainCallbackHandler()]),
146
+ ):
147
+ if chunk != "<|eot_id|>":
148
+ await msg.stream_token(chunk)
149
+
150
+ await msg.send()
chainlit.md ADDED
@@ -0,0 +1 @@
 
 
1
+ # AirBnB Auditor
data/airbnb_financials.pdf ADDED
Binary file (596 kB). View file
 
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ chainlit==0.7.700
2
+ langchain==0.2.5
3
+ langchain_community==0.2.5
4
+ langchain_core==0.2.9
5
+ langchain_huggingface==0.0.3
6
+ langchain_text_splitters==0.2.1
7
+ langchain_openai==0.1.9
8
+ python-dotenv==1.0.1
9
+ pymupdf==1.24.5
10
+ qdrant-client==1.9.2