PyaeSoneK commited on
Commit
83c6bc2
β€’
1 Parent(s): b378d56

Upload 2 files

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