drkareemkamal commited on
Commit
a1649a4
·
verified ·
1 Parent(s): f69b692

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +119 -0
app.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #from langchain import PromptTemplate
2
+ from langchain_core.prompts import PromptTemplate
3
+ import os
4
+ from langchain_community.embeddings import HuggingFaceBgeEmbeddings
5
+ from langchain_community.vectorstores import FAISS
6
+ from langchain_community.llms.ctransformers import CTransformers
7
+ #from langchain.chains import RetrievalQA
8
+ from langchain.chains.retrieval_qa.base import RetrievalQA
9
+ import streamlit as st
10
+
11
+ DB_FAISS_PATH = 'vectorstores/'
12
+
13
+ custom_prompt_template = '''use the following pieces of information to answer the user's questions.
14
+ If you don't know the answer, please just say that don't know the answer, don't try to make uo an answer.
15
+ Context : {context}
16
+ Question : {question}
17
+ only return the helpful answer below and nothing else.
18
+ '''
19
+
20
+ def set_custom_prompt():
21
+ """
22
+ Prompt template for QA retrieval for vector stores
23
+ """
24
+ prompt = PromptTemplate(template = custom_prompt_template,
25
+ input_variables = ['context','question'])
26
+
27
+ return prompt
28
+
29
+
30
+ def load_llm():
31
+ llm = CTransformers(
32
+ model = 'TheBloke/Llama-2-7B-Chat-GGML',
33
+ #model = AutoModel.from_pretrained("TheBloke/Llama-2-7B-Chat-GGML"),
34
+ model_type = 'llama',
35
+ max_new_token = 512,
36
+ temperature = 0.5
37
+ )
38
+ return llm
39
+
40
+ def retrieval_qa_chain(llm,prompt,db):
41
+ qa_chain = RetrievalQA.from_chain_type(
42
+ llm = llm,
43
+ chain_type = 'stuff',
44
+ retriever = db.as_retriever(search_kwargs= {'k': 2}),
45
+ return_source_documents = True,
46
+ chain_type_kwargs = {'prompt': prompt}
47
+ )
48
+
49
+ return qa_chain
50
+
51
+ def qa_bot():
52
+ embeddings = HuggingFaceBgeEmbeddings(model_name = 'sentence-transformers/all-MiniLM-L6-v2',
53
+ model_kwargs = {'device':'cpu'})
54
+
55
+
56
+ db = FAISS.load_local(DB_FAISS_PATH, embeddings,allow_dangerous_deserialization=True)
57
+ llm = load_llm()
58
+ qa_prompt = set_custom_prompt()
59
+ qa = retrieval_qa_chain(llm,qa_prompt, db)
60
+
61
+ return qa
62
+
63
+ def final_result(query):
64
+ qa_result = qa_bot()
65
+ response = qa_result({'query' : query})
66
+
67
+ return response
68
+
69
+
70
+ import streamlit as st
71
+
72
+ # Initialize the bot
73
+ bot = qa_bot()
74
+
75
+ # def process_query(query):
76
+ # # Here you would include the logic to process the query and return a response
77
+ # response, sources = bot.answer_query(query) # Modify this according to your bot implementation
78
+ # if sources:
79
+ # response += f"\nSources: {', '.join(sources)}"
80
+ # else:
81
+ # response += "\nNo Sources Found"
82
+ # return response
83
+
84
+
85
+ # Streamlit webpage title
86
+ st.title('Medical Chatbot')
87
+
88
+ # User input
89
+ user_query = st.text_input("Please enter your question:")
90
+
91
+ # Button to get answer
92
+ if st.button('Get Answer'):
93
+ if user_query:
94
+ # Call the function from your chatbot script
95
+ response = final_result(user_query)
96
+ if response:
97
+ # Displaying the response
98
+ st.write("### Answer")
99
+ st.write(response['result'])
100
+
101
+ #Displaying source document details if available
102
+ if 'source_documents' in response:
103
+ st.write("### Source Document Information")
104
+ for doc in response['source_documents']:
105
+ # Retrieve and format page content by replacing '\n' with new line
106
+ formatted_content = doc.page_content.replace("\\n", "\n")
107
+ st.write("#### Document Content")
108
+ st.text_area(label="Page Content", value=formatted_content, height=300)
109
+
110
+ # Retrieve source and page from metadata
111
+ source = doc.metadata['source']
112
+ page = doc.metadata['page']
113
+ st.write(f"Source: {source}")
114
+ st.write(f"Page Number: {page}")
115
+
116
+ else:
117
+ st.write("Sorry, I couldn't find an answer to your question.")
118
+ else:
119
+ st.write("Please enter a question to get an answer.")