mickkhaw commited on
Commit
afc63a7
Β·
1 Parent(s): 0490a6d

added env file

Browse files
Files changed (4) hide show
  1. Dockerfile +11 -0
  2. README.md +1 -1
  3. app.py +142 -0
  4. requirements.txt +9 -0
Dockerfile CHANGED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9
2
+ RUN useradd -m -u 1000 user
3
+ USER user
4
+ ENV HOME=/home/user \
5
+ PATH=/home/user/.local/bin:$PATH
6
+ WORKDIR $HOME/app
7
+ COPY --chown=user . $HOME/app
8
+ COPY ./requirements.txt ~/app/requirements.txt
9
+ RUN pip install -r requirements.txt
10
+ COPY . .
11
+ CMD ["chainlit", "run", "app.py", "--port", "7860"]
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: Airbnb Qabot
3
  emoji: πŸš€
4
  colorFrom: green
5
  colorTo: pink
 
1
  ---
2
+ title: Airbnb QA Bot
3
  emoji: πŸš€
4
  colorFrom: green
5
  colorTo: pink
app.py CHANGED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 TextLoader
7
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
8
+ from langchain_community.vectorstores import FAISS
9
+ from langchain_huggingface import HuggingFaceEndpointEmbeddings
10
+ from langchain_core.prompts import PromptTemplate
11
+ from langchain.schema.output_parser import StrOutputParser
12
+ from langchain.schema.runnable import RunnablePassthrough
13
+ from langchain.schema.runnable.config import RunnableConfig
14
+ from langchain_community.document_loaders import PyPDFLoader
15
+ # GLOBAL SCOPE - ENTIRE APPLICATION HAS ACCESS TO VALUES SET IN THIS SCOPE #
16
+ # ---- ENV VARIABLES ---- #
17
+ """
18
+ This function will load our environment file (.env) if it is present.
19
+ NOTE: Make sure that .env is in your .gitignore file - it is by default, but please ensure it remains there.
20
+ """
21
+ load_dotenv()
22
+ """
23
+ We will load our environment variables here.
24
+ """
25
+ HF_LLM_ENDPOINT = os.environ["HF_LLM_ENDPOINT"]
26
+ HF_EMBED_ENDPOINT = os.environ["HF_EMBED_ENDPOINT"]
27
+ HF_TOKEN = os.environ.get("HF_TOKEN")
28
+ # ---- GLOBAL DECLARATIONS ---- #
29
+ # -- RETRIEVAL -- #
30
+ """
31
+ 1. Load Documents
32
+ 2. Split Documents into Chunks
33
+ 3. Load HuggingFace Embeddings (remember to use the URL we set above)
34
+ 4. Index Files if they do not exist, otherwise load the vectorstore
35
+ """
36
+
37
+ ### 1. CREATE TEXT LOADER AND LOAD DOCUMENTS
38
+ ### NOTE: PAY ATTENTION TO THE PATH THEY ARE IN.
39
+ file_path = ("./data/airbnb.pdf")
40
+ loader = PyPDFLoader(file_path)
41
+ documents = loader.load() # Load the documents
42
+
43
+ ### 2. CREATE TEXT SPLITTER AND SPLIT DOCUMENTS
44
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=30)
45
+ split_documents = text_splitter.split_documents(documents)
46
+
47
+ ### 3. LOAD HUGGINGFACE EMBEDDINGS
48
+ hf_embeddings = HuggingFaceEndpointEmbeddings(
49
+ model=HF_EMBED_ENDPOINT,
50
+ task="feature-extraction",
51
+ huggingfacehub_api_token=HF_TOKEN,
52
+ )
53
+ if os.path.exists("./data/vectorstore"):
54
+ vectorstore = FAISS.load_local(
55
+ "./data/vectorstore",
56
+ hf_embeddings,
57
+ allow_dangerous_deserialization=True # this is necessary to load the vectorstore from disk as it's stored as a `.pkl` file.
58
+ )
59
+ hf_retriever = vectorstore.as_retriever()
60
+ print("Loaded Vectorstore")
61
+ else:
62
+ print("Indexing Files")
63
+ os.makedirs("./data/vectorstore", exist_ok=True)
64
+ ### 4. INDEX FILES
65
+ ### NOTE: REMEMBER TO BATCH THE DOCUMENTS WITH MAXIMUM BATCH SIZE = 32
66
+ for i in range(0, len(split_documents), 32):
67
+ if i == 0:
68
+ vectorstore = FAISS.from_documents(split_documents[i:i+32], hf_embeddings)
69
+ continue
70
+ vectorstore.add_documents(split_documents[i:i+32])
71
+ vectorstore.save_local("./data/vectorstore")
72
+ hf_retriever = vectorstore.as_retriever()
73
+
74
+ # -- AUGMENTED -- #
75
+ """
76
+ 1. Define a String Template
77
+ 2. Create a Prompt Template from the String Template
78
+ """
79
+ ### 1. DEFINE STRING TEMPLATE
80
+ RAG_PROMPT_TEMPLATE = """\
81
+ <|start_header_id|>system<|end_header_id|>
82
+ You are a helpful assistant. You answer user questions related to Airbnb based on provided context. If you can't answer the question related to Airbnb with the provided context, say you don't know. Otherwise, be conversational and informal in tone.<|eot_id|>
83
+ <|start_header_id|>user<|end_header_id|>
84
+ User Query:
85
+ {query}
86
+ Context:
87
+ {context}<|eot_id|>
88
+ <|start_header_id|>assistant<|end_header_id|>
89
+ """
90
+ ### 2. CREATE PROMPT TEMPLATE
91
+ rag_prompt = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE)
92
+ # -- GENERATION -- #
93
+ """
94
+ 1. Create a HuggingFaceEndpoint for the LLM
95
+ """
96
+ ### 1. CREATE HUGGINGFACE ENDPOINT FOR LLM
97
+ hf_llm = HuggingFaceEndpoint(
98
+ endpoint_url=HF_LLM_ENDPOINT,
99
+ max_new_tokens=512,
100
+ top_k=10,
101
+ top_p=0.95,
102
+ typical_p=0.95,
103
+ temperature=0.01,
104
+ repetition_penalty=1.03,
105
+ huggingfacehub_api_token=HF_TOKEN
106
+ )
107
+ @cl.author_rename
108
+ def rename(original_author: str):
109
+ """
110
+ This function can be used to rename the 'author' of a message.
111
+ In this case, we're overriding the 'Assistant' author to be 'Airbnb Filing Bot'.
112
+ """
113
+ rename_dict = {
114
+ "Assistant" : "Airbnb Filing Bot"
115
+ }
116
+ return rename_dict.get(original_author, original_author)
117
+ @cl.on_chat_start
118
+ async def start_chat():
119
+ """
120
+ This function will be called at the start of every user session.
121
+ We will build our LCEL RAG chain here, and store it in the user session.
122
+ The user session is a dictionary that is unique to each user session, and is stored in the memory of the server.
123
+ """
124
+ ### BUILD LCEL RAG CHAIN THAT ONLY RETURNS TEXT
125
+ # Diagram https://docs.google.com/presentation/d/1P9ohPhMdDr9VdXT7qgROZNY93B4jw1xaAvNH6g0AIIQ/edit?usp=sharing
126
+ lcel_rag_chain = {"context": itemgetter("query") | hf_retriever, "query": itemgetter("query")}| rag_prompt | hf_llm
127
+ cl.user_session.set("lcel_rag_chain", lcel_rag_chain)
128
+ @cl.on_message
129
+ async def main(message: cl.Message):
130
+ """
131
+ This function will be called every time a message is recieved from a session.
132
+ We will use the LCEL RAG chain to generate a response to the user query.
133
+ 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.
134
+ """
135
+ lcel_rag_chain = cl.user_session.get("lcel_rag_chain")
136
+ msg = cl.Message(content="")
137
+ async for chunk in lcel_rag_chain.astream(
138
+ {"query": message.content},
139
+ config=RunnableConfig(callbacks=[cl.LangchainCallbackHandler()]),
140
+ ):
141
+ await msg.stream_token(chunk)
142
+ await msg.send()
requirements.txt CHANGED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ chainlit==1.0.0
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
+ python-dotenv==1.0.1
8
+ faiss-cpu
9
+ pypdf