Carlosito16 commited on
Commit
89ca77a
β€’
1 Parent(s): 7cd5b79

Integrates memory and condense prompt

Browse files
Files changed (1) hide show
  1. app.py +286 -0
app.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #This version includes the memory and custom prompt, representing the final version
2
+
3
+ import streamlit as st
4
+ from streamlit_chat import message as st_message
5
+ import pandas as pd
6
+ import numpy as np
7
+ import datetime
8
+ import gspread
9
+ import pickle
10
+ import os
11
+ import csv
12
+ import json
13
+ import torch
14
+ from tqdm.auto import tqdm
15
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
16
+
17
+
18
+ # from langchain.vectorstores import Chroma
19
+ from langchain.vectorstores import FAISS
20
+ from langchain.embeddings import HuggingFaceInstructEmbeddings
21
+
22
+
23
+ from langchain import HuggingFacePipeline
24
+ from langchain.chains import RetrievalQA
25
+ from langchain.prompts import PromptTemplate
26
+ from langchain.memory import ConversationBufferWindowMemory
27
+
28
+
29
+ from langchain.chains import LLMChain
30
+ from langchain.chains import ConversationalRetrievalChain
31
+ from langchain.chains.question_answering import load_qa_chain
32
+ from langchain.chains.conversational_retrieval.prompts import CONDENSE_QUESTION_PROMPT
33
+
34
+
35
+
36
+ prompt_template = """
37
+ You are the chatbot and the face of Asian Institute of Technology (AIT). Your job is to give answers to prospective and current students about the school.
38
+ Your job is to answer questions only related to the AIT. Anything unrelated should be responded with the fact that your main job is solely to provide assistance regarding AIT.
39
+ Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.
40
+ Always make sure to be elaborate. And try to use vibrant, positive tone to represent good branding of the school.
41
+ Never answer with any unfinished response.
42
+ {context}
43
+ Question: {question}
44
+ Always make sure to elaborate your response and use vibrant, positive tone to represent good branding of the school.
45
+ Never answer with any unfinished response.
46
+ """
47
+ PROMPT = PromptTemplate(
48
+ template=prompt_template, input_variables=["context", "question"]
49
+ )
50
+ chain_type_kwargs = {"prompt": PROMPT}
51
+
52
+
53
+ st.set_page_config(
54
+ page_title = 'aitGPT',
55
+ page_icon = 'βœ…')
56
+
57
+
58
+
59
+
60
+ @st.cache_data
61
+ def load_scraped_web_info():
62
+ with open("ait-web-document", "rb") as fp:
63
+ ait_web_documents = pickle.load(fp)
64
+
65
+
66
+ text_splitter = RecursiveCharacterTextSplitter(
67
+ # Set a really small chunk size, just to show.
68
+ chunk_size = 500,
69
+ chunk_overlap = 100,
70
+ length_function = len,
71
+ )
72
+
73
+ chunked_text = text_splitter.create_documents([doc for doc in tqdm(ait_web_documents)])
74
+
75
+
76
+ @st.cache_resource
77
+ def load_embedding_model():
78
+ embedding_model = HuggingFaceInstructEmbeddings(model_name='hkunlp/instructor-base',
79
+ model_kwargs = {'device': torch.device('cuda' if torch.cuda.is_available() else 'cpu')})
80
+ return embedding_model
81
+
82
+ @st.cache_data
83
+ def load_faiss_index():
84
+ vector_database = FAISS.load_local("faiss_index_web_and_curri_new", embedding_model) #CHANGE THIS FAISS EMBEDDED KNOWLEDGE
85
+ return vector_database
86
+
87
+ @st.cache_resource
88
+ def load_llm_model():
89
+ # llm = HuggingFacePipeline.from_model_id(model_id= 'lmsys/fastchat-t5-3b-v1.0',
90
+ # task= 'text2text-generation',
91
+ # model_kwargs={ "device_map": "auto",
92
+ # "load_in_8bit": True,"max_length": 256, "temperature": 0,
93
+ # "repetition_penalty": 1.5})
94
+
95
+
96
+ llm = HuggingFacePipeline.from_model_id(model_id= 'lmsys/fastchat-t5-3b-v1.0',
97
+ task= 'text2text-generation',
98
+
99
+ model_kwargs={ "max_length": 256, "temperature": 0,
100
+ "torch_dtype":torch.float32,
101
+ "repetition_penalty": 1.3})
102
+ return llm
103
+
104
+
105
+ def load_retriever(llm, db):
106
+ qa_retriever = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff",
107
+ retriever=db.as_retriever(),
108
+ chain_type_kwargs= chain_type_kwargs)
109
+
110
+ return qa_retriever
111
+
112
+ def retrieve_document(query_input):
113
+ related_doc = vector_database.similarity_search(query_input)
114
+ return related_doc
115
+
116
+
117
+
118
+ def retrieve_answer():
119
+ prompt_answer= st.session_state.my_text_input + " " + "Try to elaborate as much as you can."
120
+ answer = qa_retriever.run(prompt_answer)
121
+ log = {"timestamp": datetime.datetime.now(),
122
+ "question":st.session_state.my_text_input,
123
+ "generated_answer": answer[6:],
124
+ "rating":0 }
125
+
126
+ st.session_state.history.append(log)
127
+ update_worksheet_qa()
128
+ st.session_state.chat_history.append({"message": st.session_state.my_text_input, "is_user": True})
129
+ st.session_state.chat_history.append({"message": answer[6:] , "is_user": False})
130
+
131
+ st.session_state.my_text_input = ""
132
+
133
+ return answer[6:] #this positional slicing helps remove "<pad> " at the beginning
134
+
135
+
136
+ def new_retrieve_answer():
137
+ prompt_answer= st.session_state.my_text_input + " " + "Try to elaborate as much as you can."
138
+ answer = conversational_qa_memory_retriever({"question": prompt_answer, })
139
+ log = {"timestamp": datetime.datetime.now(),
140
+ "question":st.session_state.my_text_input,
141
+ "generated_answer": answer[6:],
142
+ "rating":0 }
143
+
144
+ st.session_state.history.append(log)
145
+ update_worksheet_qa()
146
+ st.session_state.chat_history.append({"message": st.session_state.my_text_input, "is_user": True})
147
+ st.session_state.chat_history.append({"message": answer[6:] , "is_user": False})
148
+
149
+ st.session_state.my_text_input = ""
150
+
151
+ return answer[6:] #this positional slicing helps remove "<pad> " at the beginning
152
+
153
+ # def update_score():
154
+ # st.session_state.session_rating = st.session_state.rating
155
+
156
+
157
+ def update_worksheet_qa():
158
+ # st.session_state.session_rating = st.session_state.rating
159
+ #This if helps validate the initiated rating, if 0, then the google sheet would not be updated
160
+ #(edited) now even with the score of 0, we still want to store the log because some users do not give the score to complete the logging
161
+ # if st.session_state.session_rating == 0:
162
+ worksheet_qa.append_row([st.session_state.history[-1]['timestamp'].strftime(datetime_format),
163
+ st.session_state.history[-1]['question'],
164
+ st.session_state.history[-1]['generated_answer'],
165
+ 0])
166
+ # else:
167
+ # worksheet_qa.append_row([st.session_state.history[-1]['timestamp'].strftime(datetime_format),
168
+ # st.session_state.history[-1]['question'],
169
+ # st.session_state.history[-1]['generated_answer'],
170
+ # st.session_state.session_rating
171
+ # ])
172
+
173
+ def update_worksheet_comment():
174
+ worksheet_comment.append_row([datetime.datetime.now().strftime(datetime_format),
175
+ feedback_input])
176
+ success_message = st.success('Feedback successfully submitted, thank you', icon="βœ…",
177
+ )
178
+ time.sleep(3)
179
+ success_message.empty()
180
+
181
+
182
+ def clean_chat_history():
183
+ st.session_state.chat_history = []
184
+ conversational_qa_memory_retriever.memory.chat_memory.clear() #add this to remove
185
+
186
+ #--------------
187
+
188
+
189
+ if "history" not in st.session_state: #this one is for the google sheet logging
190
+ st.session_state.history = []
191
+
192
+
193
+ if "chat_history" not in st.session_state: #this one is to pass previous messages into chat flow
194
+ st.session_state.chat_history = []
195
+ # if "session_rating" not in st.session_state:
196
+ # st.session_state.session_rating = 0
197
+
198
+
199
+ credentials= json.loads(st.secrets['google_sheet_credential'])
200
+
201
+ service_account = gspread.service_account_from_dict(credentials)
202
+ workbook= service_account.open("aitGPT-qa-log")
203
+ worksheet_qa = workbook.worksheet("Sheet1")
204
+ worksheet_comment = workbook.worksheet("Sheet2")
205
+ datetime_format= "%Y-%m-%d %H:%M:%S"
206
+
207
+
208
+
209
+ load_scraped_web_info()
210
+ embedding_model = load_embedding_model()
211
+ vector_database = load_faiss_index()
212
+ llm_model = load_llm_model()
213
+ qa_retriever = load_retriever(llm= llm_model, db= vector_database)
214
+
215
+
216
+ print("all load done")
217
+
218
+ #Addional things for Conversation flows
219
+ question_generator = LLMChain(llm=llm_model, prompt=CONDENSE_QUESTION_PROMPT)
220
+ doc_chain = load_qa_chain(llm_model, chain_type="stuff", prompt = PROMPT)
221
+ memory = ConversationBufferWindowMemory(k = 3, memory_key="chat_history", return_messages=True, output_key='answer')
222
+
223
+
224
+
225
+ conversational_qa_memory_retriever = ConversationalRetrievalChain(
226
+ retriever=vector_database.as_retriever(),
227
+ question_generator=question_generator,
228
+ combine_docs_chain=doc_chain,
229
+ return_source_documents=True,
230
+ memory = memory,
231
+ get_chat_history=lambda h :h)
232
+
233
+
234
+
235
+ st.write("# aitGPT πŸ€– ")
236
+ st.markdown("""
237
+ #### The aitGPT project is a virtual assistant developed by the :green[Asian Institute of Technology] that contains a vast amount of information gathered from 205 AIT-related websites.
238
+ The goal of this chatbot is to provide an alternative way for applicants and current students to access information about the institute, including admission procedures, campus facilities, and more.
239
+ """)
240
+ st.write(' ⚠️ Please expect to wait **~ 10 - 20 seconds per question** as thi app is running on CPU against 3-billion-parameter LLM')
241
+
242
+ st.markdown("---")
243
+ st.write(" ")
244
+ st.write("""
245
+ ### ❔ Ask a question
246
+ """)
247
+
248
+
249
+ for chat in st.session_state.chat_history:
250
+ st_message(**chat)
251
+
252
+ query_input = st.text_input(label= 'What would you like to know about AIT?' , key = 'my_text_input', on_change= retrieve_answer )
253
+ # generate_button = st.button(label = 'Ask question!')
254
+
255
+ # if generate_button:
256
+ # answer = retrieve_answer(query_input)
257
+ # log = {"timestamp": datetime.datetime.now(),
258
+ # "question":query_input,
259
+ # "generated_answer": answer,
260
+ # "rating":0 }
261
+
262
+ # st.session_state.history.append(log)
263
+ # update_worksheet_qa()
264
+ # st.session_state.chat_history.append({"message": query_input, "is_user": True})
265
+ # st.session_state.chat_history.append({"message": answer, "is_user": False})
266
+
267
+ # print(st.session_state.chat_history)
268
+
269
+
270
+ clear_button = st.button("Start new convo",
271
+ on_click=clean_chat_history)
272
+
273
+
274
+ st.write(" ")
275
+ st.write(" ")
276
+
277
+ st.markdown("---")
278
+ st.write("""
279
+ ### πŸ’Œ Your voice matters
280
+ """)
281
+
282
+ feedback_input = st.text_area(label= 'please leave your feedback or any ideas to make this bot more knowledgeable and fun')
283
+ feedback_button = st.button(label = 'Submit feedback!')
284
+
285
+ if feedback_button:
286
+ update_worksheet_comment()