Sbnos commited on
Commit
4b7893b
1 Parent(s): 9a04c1e

Creating app.py with mistral llm

Browse files
Files changed (1) hide show
  1. app.py +267 -0
app.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ from langchain.vectorstores import Chroma
4
+ from langchain.embeddings import HuggingFaceBgeEmbeddings
5
+ from langchain.llms import Together
6
+ from langchain import hub
7
+ from operator import itemgetter
8
+ from langchain.schema.runnable import RunnableParallel
9
+ from langchain.schema import format_document
10
+ from typing import List, Tuple
11
+ from langchain.chains import LLMChain
12
+ from langchain.chains import RetrievalQA
13
+ from langchain.schema.output_parser import StrOutputParser
14
+ from langchain.memory import StreamlitChatMessageHistory
15
+ from langchain.memory import ConversationBufferMemory
16
+ from langchain.chains import ConversationalRetrievalChain
17
+ from langchain.memory import ConversationSummaryMemory
18
+ from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder, PromptTemplate
19
+ from langchain.schema.runnable import RunnableLambda, RunnablePassthrough
20
+
21
+
22
+ # Load the embedding function
23
+ model_name = "BAAI/bge-base-en"
24
+ encode_kwargs = {'normalize_embeddings': True} # set True to compute cosine similarity
25
+
26
+ embedding_function = HuggingFaceBgeEmbeddings(
27
+ model_name=model_name,
28
+ encode_kwargs=encode_kwargs
29
+ )
30
+
31
+ # Load the ChromaDB vector store
32
+ # persist_directory="./mrcpchromadb/"
33
+ # vectordb = Chroma(persist_directory=persist_directory, embedding_function=embedding_function,collection_name="mrcppassmednotes")
34
+
35
+
36
+
37
+
38
+ # Load the LLM
39
+ llm = Together(
40
+ model="mistralai/Mixtral-8x7B-Instruct-v0.1",
41
+ temperature=0.2,
42
+ max_tokens=4096,
43
+ top_k=4,
44
+ together_api_key=os.environ['pilotikval']
45
+ )
46
+
47
+ # Load the summarizeLLM
48
+ llmc = Together(
49
+ model="mistralai/Mixtral-8x7B-Instruct-v0.1",
50
+ temperature=0.2,
51
+ max_tokens=1024,
52
+ top_k=1,
53
+ together_api_key=os.environ['pilotikval']
54
+ )
55
+
56
+ msgs = StreamlitChatMessageHistory(key="langchain_messages")
57
+ memory = ConversationBufferMemory(chat_memory=msgs)
58
+
59
+
60
+
61
+ DEFAULT_DOCUMENT_PROMPT = PromptTemplate.from_template(template="{page_content}")
62
+
63
+ def _combine_documents(
64
+ docs, document_prompt=DEFAULT_DOCUMENT_PROMPT, document_separator="\n\n"
65
+ ):
66
+ doc_strings = [format_document(doc, document_prompt) for doc in docs]
67
+ return document_separator.join(doc_strings)
68
+
69
+
70
+
71
+ chistory = []
72
+
73
+ def store_chat_history(role: str, content: str):
74
+ # Append the new message to the chat history
75
+ chistory.append({"role": role, "content": content})
76
+
77
+
78
+ # Define the Streamlit app
79
+ def app():
80
+
81
+
82
+
83
+ with st.sidebar:
84
+
85
+ st.title("dochatter")
86
+ # Create a dropdown selection box
87
+ option = st.selectbox(
88
+ 'Which retriever would you like to use?',
89
+ ('RespiratoryFishman', 'RespiratoryMurray', 'MedMRCP2', 'OldMedicine')
90
+ )
91
+ # Depending on the selected option, choose the appropriate retriever
92
+ if option == 'RespiratoryFishman':
93
+ persist_directory="./respfishmandbcud/"
94
+ vectordb = Chroma(persist_directory=persist_directory, embedding_function=embedding_function,collection_name="fishmannotescud")
95
+ retriever = vectordb.as_retriever(search_kwargs={"k": 5})
96
+ retriever = retriever # replace with your actual retriever
97
+
98
+ if option == 'RespiratoryMurray':
99
+ persist_directory="./respmurray/"
100
+ vectordb = Chroma(persist_directory=persist_directory, embedding_function=embedding_function,collection_name="respmurraynotes")
101
+ retriever = vectordb.as_retriever(search_kwargs={"k": 5})
102
+ retriever = retriever
103
+
104
+ if option == 'MedMRCP2':
105
+ persist_directory="./medmrcp2store/"
106
+ vectordb = Chroma(persist_directory=persist_directory, embedding_function=embedding_function,collection_name="medmrcp2notes")
107
+ retriever = vectordb.as_retriever(search_kwargs={"k": 5})
108
+ retriever = retriever
109
+ else:
110
+ persist_directory="./mrcpchromadb/"
111
+ vectordb = Chroma(persist_directory=persist_directory, embedding_function=embedding_function,collection_name="mrcppassmednotes")
112
+ retriever = vectordb.as_retriever(search_kwargs={"k": 5})
113
+ retriever = retriever # replace with your actual retriever
114
+ retriever = retriever # replace with your actual retriever
115
+
116
+ #template = """You are an AI chatbot having a conversation with a human. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.
117
+ #{context}
118
+ #{history}
119
+ #Human: {human_input}
120
+ #AI: """
121
+ #prompt = PromptTemplate(input_variables=["history", "question"], template=template)
122
+ #template = st.text_area("Template", value=template, height=180)
123
+ #prompt2 = ChatPromptTemplate.from_template(template)
124
+
125
+
126
+
127
+
128
+ # Session State
129
+ # Store LLM generated responses
130
+ if "messages" not in st.session_state.keys():
131
+ st.session_state.messages = [{"role": "assistant", "content": "How may I help you?"}]
132
+
133
+
134
+
135
+
136
+
137
+
138
+
139
+
140
+
141
+
142
+ ## Retry lets go
143
+
144
+ _template = """Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question which contains the themes of the conversation. Do not write the question. Do not write the answer.
145
+
146
+ Chat History:
147
+ {chat_history}
148
+ Follow Up Input: {question}
149
+ Standalone question:"""
150
+ CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(_template)
151
+
152
+ template = """You are helping a doctor. Answer with what you know from the context provided. Please be as detailed and thorough. Answer the question based on the following context:
153
+ {context}
154
+
155
+ Question: {question}
156
+ """
157
+ ANSWER_PROMPT = ChatPromptTemplate.from_template(template)
158
+
159
+
160
+ _inputs = RunnableParallel(
161
+ standalone_question=RunnablePassthrough.assign(
162
+ chat_history=lambda x: chistory
163
+ )
164
+ | CONDENSE_QUESTION_PROMPT
165
+ | llmc
166
+ | StrOutputParser(),
167
+ )
168
+ _context = {
169
+ "context": itemgetter("standalone_question") | retriever | _combine_documents,
170
+ "question": lambda x: x["standalone_question"],
171
+ }
172
+ conversational_qa_chain = _inputs | _context | ANSWER_PROMPT | llm
173
+
174
+
175
+
176
+
177
+
178
+
179
+
180
+
181
+
182
+
183
+
184
+ st.header("Ask Away!")
185
+ # Display the messages
186
+ for message in st.session_state.messages:
187
+ with st.chat_message(message["role"]):
188
+ st.write(message["content"])
189
+ store_chat_history(message["role"], message["content"])
190
+
191
+ # prompt = hub.pull("rlm/rag-prompt")
192
+
193
+
194
+
195
+
196
+ prompts2 = st.chat_input("Say something")
197
+
198
+ # Implement using different book sources, if statements
199
+
200
+
201
+
202
+
203
+
204
+
205
+
206
+
207
+
208
+
209
+
210
+
211
+
212
+
213
+ if prompts2:
214
+ st.session_state.messages.append({"role": "user", "content": prompts2})
215
+ with st.chat_message("user"):
216
+ st.write(prompts2)
217
+
218
+
219
+
220
+ if st.session_state.messages[-1]["role"] != "assistant":
221
+ with st.chat_message("assistant"):
222
+ with st.spinner("Thinking..."):
223
+ response = conversational_qa_chain.invoke(
224
+ {
225
+ "question": prompts2,
226
+ "chat_history": chistory,
227
+ }
228
+ )
229
+ st.write(response)
230
+ message = {"role": "assistant", "content": response}
231
+ st.session_state.messages.append(message)
232
+
233
+
234
+
235
+
236
+
237
+
238
+
239
+
240
+
241
+
242
+
243
+
244
+ # Create a button to submit the question
245
+
246
+
247
+
248
+
249
+
250
+
251
+
252
+
253
+
254
+
255
+
256
+
257
+
258
+
259
+
260
+
261
+
262
+
263
+ # Initialize history
264
+ history = []
265
+
266
+ if __name__ == '__main__':
267
+ app()