Spaces:
Paused
Paused
gkbalu
commited on
Commit
·
8b7bc13
1
Parent(s):
282df4d
Midterm proj
Browse files
app.py
CHANGED
@@ -3,7 +3,7 @@ import chainlit as cl
|
|
3 |
from dotenv import load_dotenv
|
4 |
from operator import itemgetter
|
5 |
from langchain_huggingface import HuggingFaceEndpoint
|
6 |
-
from
|
7 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
8 |
from langchain_community.vectorstores import Qdrant
|
9 |
from langchain_openai.embeddings import OpenAIEmbeddings
|
@@ -35,21 +35,36 @@ VECTOR_STORE_PATH = "./data/vectorstore"
|
|
35 |
3. Load HuggingFace Embeddings (remember to use the URL we set above)
|
36 |
4. Index Files if they do not exist, otherwise load the vectorstore
|
37 |
"""
|
38 |
-
document_loader =
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
|
44 |
# Note: Uses OPENAI_API_KEY env variable to make api calls
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
|
51 |
retriever = vectorstore.as_retriever()
|
52 |
-
|
53 |
# -- AUGMENTED -- #
|
54 |
"""
|
55 |
1. Define a String Template
|
|
|
3 |
from dotenv import load_dotenv
|
4 |
from operator import itemgetter
|
5 |
from langchain_huggingface import HuggingFaceEndpoint
|
6 |
+
from PyPDF2 import PdfReader
|
7 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
8 |
from langchain_community.vectorstores import Qdrant
|
9 |
from langchain_openai.embeddings import OpenAIEmbeddings
|
|
|
35 |
3. Load HuggingFace Embeddings (remember to use the URL we set above)
|
36 |
4. Index Files if they do not exist, otherwise load the vectorstore
|
37 |
"""
|
38 |
+
document_loader = PdfReader("./data/Airbnb_Q1_Filings.pdf")
|
39 |
+
|
40 |
+
raw_text = ''
|
41 |
+
for i, page in enumerate(document_loader.pages):
|
42 |
+
content = page.extract_text()
|
43 |
+
if content:
|
44 |
+
raw_text += content
|
45 |
+
|
46 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
47 |
+
chunk_size = 850,
|
48 |
+
chunk_overlap = 50,
|
49 |
+
length_function = len,
|
50 |
+
)
|
51 |
+
texts = text_splitter.split_text(raw_text)
|
52 |
|
53 |
# Note: Uses OPENAI_API_KEY env variable to make api calls
|
54 |
+
hf_embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
|
55 |
+
|
56 |
+
for i in range(0, len(texts), 32):
|
57 |
+
if i == 0:
|
58 |
+
vectorstore = Qdrant.from_texts(
|
59 |
+
texts[i:i+32],
|
60 |
+
hf_embeddings,
|
61 |
+
force_recreate=True,
|
62 |
+
path=VECTOR_STORE_PATH,
|
63 |
+
collection_name="Airbnb Filings")
|
64 |
+
continue
|
65 |
+
vectorstore.add_texts(texts[i:i+32])
|
66 |
|
67 |
retriever = vectorstore.as_retriever()
|
|
|
68 |
# -- AUGMENTED -- #
|
69 |
"""
|
70 |
1. Define a String Template
|
backup.py
ADDED
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
VECTOR_STORE_PATH = "./data/vectorstore"
|
28 |
+
|
29 |
+
# ---- GLOBAL DECLARATIONS ---- #
|
30 |
+
|
31 |
+
# -- RETRIEVAL -- #
|
32 |
+
"""
|
33 |
+
1. Load Documents from PDF File
|
34 |
+
2. Split Documents into Chunks
|
35 |
+
3. Load HuggingFace Embeddings (remember to use the URL we set above)
|
36 |
+
4. Index Files if they do not exist, otherwise load the vectorstore
|
37 |
+
"""
|
38 |
+
document_loader = PyMuPDFLoader("./data/Airbnb_Q1_Filings.pdf")
|
39 |
+
documents = document_loader.load()
|
40 |
+
|
41 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=30)
|
42 |
+
split_documents = text_splitter.split_documents(documents)
|
43 |
+
|
44 |
+
# Note: Uses OPENAI_API_KEY env variable to make api calls
|
45 |
+
openai_embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
|
46 |
+
|
47 |
+
os.makedirs(VECTOR_STORE_PATH, exist_ok=True)
|
48 |
+
vectorstore = Qdrant.from_documents(documents=split_documents,embedding=openai_embeddings,path=VECTOR_STORE_PATH,collection_name="airbnb_financials",batch_size=32,
|
49 |
+
)
|
50 |
+
|
51 |
+
retriever = vectorstore.as_retriever()
|
52 |
+
|
53 |
+
# -- AUGMENTED -- #
|
54 |
+
"""
|
55 |
+
1. Define a String Template
|
56 |
+
2. Create a Prompt Template from the String Template
|
57 |
+
"""
|
58 |
+
RAG_PROMPT_TEMPLATE = """\
|
59 |
+
<|start_header_id|>system<|end_header_id|>
|
60 |
+
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.<|eot_id|>
|
61 |
+
|
62 |
+
<|start_header_id|>user<|end_header_id|>
|
63 |
+
User Query:
|
64 |
+
{query}
|
65 |
+
|
66 |
+
Context:
|
67 |
+
{context}<|eot_id|>
|
68 |
+
|
69 |
+
<|start_header_id|>assistant<|end_header_id|>
|
70 |
+
"""
|
71 |
+
|
72 |
+
rag_prompt = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE)
|
73 |
+
|
74 |
+
# -- GENERATION -- #
|
75 |
+
"""
|
76 |
+
1. Create a HuggingFaceEndpoint for the LLM
|
77 |
+
"""
|
78 |
+
hf_llm = HuggingFaceEndpoint(
|
79 |
+
endpoint_url=HF_LLM_ENDPOINT,
|
80 |
+
max_new_tokens=512,
|
81 |
+
top_k=10,
|
82 |
+
top_p=0.95,
|
83 |
+
temperature=0.3,
|
84 |
+
repetition_penalty=1.15,
|
85 |
+
huggingfacehub_api_token=HF_TOKEN,
|
86 |
+
)
|
87 |
+
|
88 |
+
@cl.author_rename
|
89 |
+
def rename(original_author: str):
|
90 |
+
"""
|
91 |
+
This function can be used to rename the 'author' of a message.
|
92 |
+
|
93 |
+
In this case, we're overriding the 'Assistant' author to be 'Paul Graham Essay Bot'.
|
94 |
+
"""
|
95 |
+
rename_dict = {
|
96 |
+
"Assistant" : "AirBnB Auditor"
|
97 |
+
}
|
98 |
+
return rename_dict.get(original_author, original_author)
|
99 |
+
|
100 |
+
@cl.on_chat_start
|
101 |
+
async def start_chat():
|
102 |
+
"""
|
103 |
+
This function will be called at the start of every user session.
|
104 |
+
|
105 |
+
We will build our LCEL RAG chain here, and store it in the user session.
|
106 |
+
|
107 |
+
The user session is a dictionary that is unique to each user session, and is stored in the memory of the server.
|
108 |
+
"""
|
109 |
+
|
110 |
+
lcel_rag_chain = (
|
111 |
+
{"context": itemgetter("query") | retriever, "query": itemgetter("query")}
|
112 |
+
| rag_prompt | hf_llm
|
113 |
+
)
|
114 |
+
|
115 |
+
cl.user_session.set("lcel_rag_chain", lcel_rag_chain)
|
116 |
+
|
117 |
+
@cl.on_message
|
118 |
+
async def main(message: cl.Message):
|
119 |
+
"""
|
120 |
+
This function will be called every time a message is recieved from a session.
|
121 |
+
|
122 |
+
We will use the LCEL RAG chain to generate a response to the user query.
|
123 |
+
|
124 |
+
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.
|
125 |
+
"""
|
126 |
+
lcel_rag_chain = cl.user_session.get("lcel_rag_chain")
|
127 |
+
|
128 |
+
msg = cl.Message(content="")
|
129 |
+
|
130 |
+
for chunk in await cl.make_async(lcel_rag_chain.stream)(
|
131 |
+
{"query": message.content},
|
132 |
+
config=RunnableConfig(callbacks=[cl.LangchainCallbackHandler()]),
|
133 |
+
):
|
134 |
+
# Note: Skip printing eot_id token at the end of response. A more elegant solution would be to fix the model's generator config.
|
135 |
+
if chunk != "<|eot_id|>":
|
136 |
+
await msg.stream_token(chunk)
|
137 |
+
|
138 |
+
await msg.send()
|