theekshana commited on
Commit
59dd032
1 Parent(s): 2ee55a8

how to use changed

Browse files
Files changed (2) hide show
  1. app.py +5 -4
  2. qaPipeline_custom_agent.py +352 -0
app.py CHANGED
@@ -97,8 +97,8 @@ def side_bar():
97
 
98
  st.markdown("\n")
99
 
100
- with st.form('openai api key'):
101
- if st.session_state.model == 'openai/gpt-3.5':
102
  api_key = st.text_input(
103
  "Enter openai api key",
104
  type="password",
@@ -132,8 +132,9 @@ def side_bar():
132
  st.markdown(
133
  "### How to use\n"
134
  "1. Select the chat model\n" # noqa: E501
135
- "2. Select \"show source files\" to show the source files related to the answer.📄\n"
136
- "3. Ask a question about the documents💬\n"
 
137
  )
138
 
139
 
 
97
 
98
  st.markdown("\n")
99
 
100
+ if st.session_state.model == 'openai/gpt-3.5':
101
+ with st.form('openai api key'):
102
  api_key = st.text_input(
103
  "Enter openai api key",
104
  type="password",
 
132
  st.markdown(
133
  "### How to use\n"
134
  "1. Select the chat model\n" # noqa: E501
135
+ "1. If selected model asks for a api key enter a valid api key.\n" # noqa: E501
136
+ "3. Select \"show source files\" to show the source files related to the answer.📄\n"
137
+ "4. Ask a question about the documents💬\n"
138
  )
139
 
140
 
qaPipeline_custom_agent.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Python Backend API to chat with private data
3
+
4
+ 08/14/2023
5
+ D.M. Theekshana Samaradiwakara
6
+ """
7
+
8
+ import os
9
+ import time
10
+
11
+ from dotenv import load_dotenv
12
+
13
+ from langchain.chains import RetrievalQA
14
+ from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
15
+
16
+ from langchain.llms import GPT4All
17
+ from langchain.llms import HuggingFaceHub
18
+ from langchain.chat_models import ChatOpenAI
19
+ from langchain.chat_models import ChatAnyscale
20
+
21
+ # from langchain.retrievers.self_query.base import SelfQueryRetriever
22
+ # from langchain.chains.query_constructor.base import AttributeInfo
23
+
24
+ # from chromaDb import load_store
25
+ from faissDb import load_FAISS_store
26
+
27
+ from langchain.agents import ZeroShotAgent, Tool, AgentExecutor
28
+
29
+ from langchain.prompts import PromptTemplate
30
+ from langchain.chains import LLMChain, ConversationalRetrievalChain
31
+ from conversationBufferWindowMemory import ConversationBufferWindowMemory
32
+ from langchain.memory import ReadOnlySharedMemory
33
+
34
+ load_dotenv()
35
+
36
+ #gpt4 all model
37
+ gpt4all_model_path = os.environ.get('GPT4ALL_MODEL_PATH')
38
+ model_n_ctx = os.environ.get('MODEL_N_CTX')
39
+ model_n_batch = int(os.environ.get('MODEL_N_BATCH',8))
40
+ target_source_chunks = int(os.environ.get('TARGET_SOURCE_CHUNKS',4))
41
+
42
+ openai_api_key = os.environ.get('OPENAI_API_KEY')
43
+ anyscale_api_key = os.environ.get('ANYSCALE_ENDPOINT_TOKEN')
44
+
45
+ verbose = os.environ.get('VERBOSE')
46
+
47
+ # activate/deactivate the streaming StdOut callback for LLMs
48
+ callbacks = [StreamingStdOutCallbackHandler()]
49
+
50
+ memory = ConversationBufferWindowMemory(
51
+ memory_key="chat_history",
52
+ input_key="question",
53
+ return_messages=True,
54
+ k=3
55
+ )
56
+
57
+ readonlymemory = ReadOnlySharedMemory(memory=memory)
58
+
59
+ class Singleton:
60
+ __instance = None
61
+ @staticmethod
62
+ def getInstance():
63
+ """ Static access method. """
64
+ if Singleton.__instance == None:
65
+ Singleton()
66
+ return Singleton.__instance
67
+ def __init__(self):
68
+ """ Virtually private constructor. """
69
+ if Singleton.__instance != None:
70
+ raise Exception("This class is a singleton!")
71
+ else:
72
+ Singleton.__instance = QAPipeline()
73
+
74
+ def get_local_LLAMA2():
75
+ import torch
76
+ from transformers import AutoTokenizer, AutoModelForCausalLM
77
+
78
+ tokenizer = AutoTokenizer.from_pretrained("NousResearch/Llama-2-13b-chat-hf",
79
+ # use_auth_token=True,
80
+ )
81
+
82
+ model = AutoModelForCausalLM.from_pretrained("NousResearch/Llama-2-13b-chat-hf",
83
+ device_map='auto',
84
+ torch_dtype=torch.float16,
85
+ use_auth_token=True,
86
+ # load_in_8bit=True,
87
+ # load_in_4bit=True
88
+ )
89
+ from transformers import pipeline
90
+
91
+ pipe = pipeline("text-generation",
92
+ model=model,
93
+ tokenizer= tokenizer,
94
+ torch_dtype=torch.bfloat16,
95
+ device_map="auto",
96
+ max_new_tokens = 512,
97
+ do_sample=True,
98
+ top_k=30,
99
+ num_return_sequences=1,
100
+ eos_token_id=tokenizer.eos_token_id
101
+ )
102
+
103
+ from langchain import HuggingFacePipeline
104
+ LLAMA2 = HuggingFacePipeline(pipeline = pipe, model_kwargs = {'temperature':0})
105
+ print(f"\n\n> torch.cuda.is_available(): {torch.cuda.is_available()}")
106
+ print("\n\n> local LLAMA2 loaded")
107
+ return LLAMA2
108
+
109
+ class QAPipeline:
110
+
111
+ def __init__(self):
112
+
113
+ print("\n\n> Initializing QAPipeline:")
114
+ self.llm_name = None
115
+ self.llm = None
116
+
117
+ self.dataset_name = None
118
+ self.vectorstore = None
119
+
120
+ self.qa_chain = None
121
+ self.agent = None
122
+
123
+
124
+ def run(self,query, model, dataset):
125
+
126
+ if (self.llm_name != model) or (self.dataset_name != dataset) or (self.qa_chain == None):
127
+ self.set_model(model)
128
+ self.set_vectorstore(dataset)
129
+ self.set_qa_chain()
130
+
131
+ # Get the answer from the chain
132
+ start = time.time()
133
+ res = self.qa_chain(query)
134
+ # answer, docs = res['result'],res['source_documents']
135
+ end = time.time()
136
+
137
+ # Print the result
138
+ print("\n\n> Question:")
139
+ print(query)
140
+ print(f"\n> Answer (took {round(end - start, 2)} s.):")
141
+ print( res)
142
+
143
+ return res
144
+
145
+ def run_agent(self,query, model, dataset):
146
+
147
+ try:
148
+
149
+ if (self.llm_name != model) or (self.dataset_name != dataset) or (self.agent == None):
150
+ self.set_model(model)
151
+ self.set_vectorstore(dataset)
152
+ self.set_qa_chain_with_agent()
153
+
154
+ # Get the answer from the chain
155
+ start = time.time()
156
+ res = self.agent(query)
157
+ # answer, docs = res['result'],res['source_documents']
158
+ end = time.time()
159
+
160
+ # Print the result
161
+ print("\n\n> Question:")
162
+ print(query)
163
+ print(f"\n> Answer (took {round(end - start, 2)} s.):")
164
+ print( res)
165
+
166
+ return res["output"]
167
+
168
+ except Exception as e:
169
+ # logger.error(f"Answer retrieval failed with {e}")
170
+ print(f"> QAPipeline run_agent Error : {e}")#, icon=":books:")
171
+ return
172
+
173
+
174
+ def set_model(self,model_type):
175
+ if model_type != self.llm_name:
176
+ match model_type:
177
+ case "gpt4all":
178
+ # self.llm = GPT4All(model=gpt4all_model_path, n_ctx=model_n_ctx, backend='gptj', n_batch=model_n_batch, callbacks=callbacks, verbose=verbose)
179
+ self.llm = GPT4All(model=gpt4all_model_path, max_tokens=model_n_ctx, backend='gptj', n_batch=model_n_batch, callbacks=callbacks, verbose=verbose)
180
+ # self.llm = HuggingFaceHub(repo_id="nomic-ai/gpt4all-j", model_kwargs={"temperature":0.001, "max_length":1024})
181
+ case "google/flan-t5-xxl":
182
+ self.llm = HuggingFaceHub(repo_id="google/flan-t5-xxl", model_kwargs={"temperature":0.001, "max_length":1024})
183
+ case "tiiuae/falcon-7b-instruct":
184
+ self.llm = HuggingFaceHub(repo_id=model_type, model_kwargs={"temperature":0.001, "max_length":1024})
185
+ case "openai":
186
+ self.llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)
187
+ case "Deci/DeciLM-6b-instruct":
188
+ self.llm = ChatOpenAI(model_name="Deci/DeciLM-6b-instruct", temperature=0)
189
+ case "Deci/DeciLM-6b":
190
+ self.llm = ChatOpenAI(model_name="Deci/DeciLM-6b", temperature=0)
191
+ case "local/LLAMA2":
192
+ self.llm = get_local_LLAMA2()
193
+ case "anyscale/Llama-2-13b-chat-hf":
194
+ self.llm = ChatAnyscale(anyscale_api_key=anyscale_api_key,temperature=0, model_name='meta-llama/Llama-2-13b-chat-hf', streaming=False)
195
+ case "anyscale/Llama-2-70b-chat-hf":
196
+ self.llm = ChatAnyscale(anyscale_api_key=anyscale_api_key,temperature=0, model_name='meta-llama/Llama-2-70b-chat-hf', streaming=False)
197
+ case _default:
198
+ # raise exception if model_type is not supported
199
+ raise Exception(f"Model type {model_type} is not supported. Please choose a valid one")
200
+
201
+ self.llm_name = model_type
202
+
203
+
204
+
205
+ def set_vectorstore(self, dataset):
206
+ if dataset != self.dataset_name:
207
+ # self.vectorstore = load_store(dataset)
208
+ self.vectorstore = load_FAISS_store()
209
+ print("\n\n> vectorstore loaded:")
210
+ self.dataset_name = dataset
211
+
212
+ def set_qa_chain(self):
213
+
214
+ self.qa_chain = RetrievalQA.from_chain_type(
215
+ llm=self.llm,
216
+ chain_type="stuff",
217
+ retriever = self.vectorstore.as_retriever(),
218
+ # retriever = self.vectorstore.as_retriever(search_kwargs={"k": target_source_chunks}
219
+ return_source_documents= True
220
+ )
221
+
222
+
223
+ def set_qa_chain_with_agent(self):
224
+
225
+ try:
226
+
227
+ # Define a custom prompt
228
+ general_qa_template = (
229
+ """[INST]<<SYS>> You are the AI of company boardpac which provide services to company board members related to banking and financial sector. You should only continue the conversation and reply to users questions like welcomes, greetings and goodbyes.
230
+ If you dont know the answer say you dont know, dont try to makeup answers. Answer should be short and simple as possible. Start the answer with code word Boardpac AI (chat): <</SYS>>
231
+ Conversation: {chat_history}
232
+ Question: {question} [/INST]"""
233
+ )
234
+
235
+ general_qa_chain_prompt = PromptTemplate(input_variables=["question", "chat_history"], template=general_qa_template)
236
+
237
+ general_qa_chain = LLMChain(
238
+ llm=self.llm,
239
+ prompt=general_qa_chain_prompt,
240
+ verbose=True,
241
+ memory=readonlymemory, # use the read-only memory to prevent the tool from modifying the memory
242
+ )
243
+
244
+ general_qa_chain_tool = Tool(
245
+ name="general qa",
246
+ func= general_qa_chain.run,
247
+ description='''use this when only you need to answer questions like welcomes, greetings and goodbyes.
248
+ Input should be a fully formed question.''',
249
+ return_direct=True,
250
+
251
+ )
252
+
253
+ # Define a custom prompt
254
+ retrieval_qa_template = (
255
+ """[INST]<<SYS>> You are the AI of company boardpac which provide services to company board members. Only answer questions related to Banking and Financial Services Sector like Banking & Financial regulations, legal framework, governance framework, compliance requirements as per Central Bank regulations.
256
+ please answer the question based on the chat history and context information provided below related to central bank acts published in various years. The published year is mentioned as the metadata 'year' of each source document.
257
+ The content of a bank act of a past year can updated by a bank act from a latest year. Always try to answer with latest information and mention the year which information extracted.
258
+ If you dont know the answer say you dont know, dont try to makeup answers. Answer should be short and simple as possible. Start the answer with code word Boardpac AI (QA): <</SYS>>
259
+ Conversation: {chat_history}
260
+ Context: {context}
261
+ Question : {question} [/INST]"""
262
+ )
263
+
264
+ retrieval_qa_chain_prompt = PromptTemplate(
265
+ input_variables=["question", "context", "chat_history"],
266
+ template=retrieval_qa_template
267
+ )
268
+
269
+ document_combine_prompt = PromptTemplate(
270
+ input_variables=["source","year", "page","page_content"],
271
+ template=
272
+ """<doc> source: {source}, year: {year}, page: {page}, page content: {page_content} </doc>"""
273
+ )
274
+
275
+ bank_regulations_qa = ConversationalRetrievalChain.from_llm(
276
+ llm=self.llm,
277
+ chain_type="stuff",
278
+ retriever = self.vectorstore.as_retriever(),
279
+ # retriever = self.vectorstore.as_retriever(
280
+ # search_type="mmr",
281
+ # search_kwargs={
282
+ # 'k': 6,
283
+ # # 'lambda_mult': 0.1,
284
+ # 'fetch_k': 50},
285
+ # # search_type="similarity_score_threshold",
286
+ # # search_kwargs={"score_threshold": .5}
287
+ # ),
288
+ return_source_documents= True,
289
+ return_generated_question= True,
290
+ get_chat_history=lambda h : h,
291
+ combine_docs_chain_kwargs={
292
+ "prompt": retrieval_qa_chain_prompt,
293
+ "document_prompt": document_combine_prompt,
294
+ },
295
+ verbose=True,
296
+ memory=readonlymemory, # use the read-only memory to prevent the tool from modifying the memory
297
+ )
298
+
299
+ bank_regulations_qa_tool = Tool(
300
+ name="bank regulations",
301
+ func= lambda question: bank_regulations_qa({"question": question}),
302
+ description='''Use this more when you need to answer questions about Banking and Financial Services Sector like Banking & Financial regulations, legal framework, governance framework, compliance requirements as per Central Bank regulations.
303
+ Input should be a fully formed question.''',
304
+ return_direct=True,
305
+ )
306
+
307
+ tools = [
308
+ bank_regulations_qa_tool,
309
+ general_qa_chain_tool
310
+ ]
311
+
312
+ prefix = """<<SYS>> You are the AI of company boardpac which provide services to company board members related to banking and financial sector. Have a conversation with the user, answering the following questions as best you can. You have access to the following tools:"""
313
+ suffix = """Begin! "
314
+ {agent_scratchpad}
315
+ <chat history>: {chat_history}
316
+ <</SYS>>
317
+
318
+ [INST]
319
+ <Question>: {question}
320
+ [/INST]"""
321
+
322
+ agent_prompt = ZeroShotAgent.create_prompt(
323
+ tools,
324
+ prefix=prefix,
325
+ suffix=suffix,
326
+ input_variables=["question", "chat_history", "agent_scratchpad"],
327
+ )
328
+
329
+ llm_chain = LLMChain(llm=self.llm, prompt=agent_prompt)
330
+
331
+ agent = ZeroShotAgent(
332
+ llm_chain=llm_chain,
333
+ tools=tools,
334
+ verbose=True,
335
+ )
336
+
337
+ agent_chain = AgentExecutor.from_agent_and_tools(
338
+ agent=agent,
339
+ tools=tools,
340
+ verbose=True,
341
+ memory=memory,
342
+ handle_parsing_errors=True,
343
+ )
344
+
345
+ self.agent = agent_chain
346
+
347
+ print(f"\n> agent_chain created")
348
+
349
+ except Exception as e:
350
+ # logger.error(f"Answer retrieval failed with {e}")
351
+ print(f"> QAPipeline set_qa_chain_with_agent Error : {e}")#, icon=":books:")
352
+ return