harshitv804 commited on
Commit
68413f4
1 Parent(s): 640e52e

Rename app.py to app1.py

Browse files
Files changed (1) hide show
  1. app.py → app1.py +67 -39
app.py → app1.py RENAMED
@@ -1,82 +1,110 @@
1
  from langchain_community.vectorstores import FAISS
2
  from langchain_community.embeddings import HuggingFaceEmbeddings
3
- from langchain.callbacks.manager import CallbackManager
4
- from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
5
- from langchain.chains import LLMChain
6
  from langchain.prompts import PromptTemplate
7
  from langchain_community.llms import LlamaCpp
8
- from langchain.memory import ConversationBufferMemory
9
  from langchain.chains import ConversationalRetrievalChain
10
  import streamlit as st
11
- from langchain.callbacks import StreamlitCallbackHandler
12
  import time
13
- st.set_page_config(layout="wide")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  embeddings = HuggingFaceEmbeddings(model_name="BAAI/llm-embedder")
16
  db = FAISS.load_local("faiss_index", embeddings)
17
  db_retriever = db.as_retriever(search_type="similarity",search_kwargs={"k": 3})
18
- callback_manager = CallbackManager([StreamingStdOutCallbackHandler()])
19
 
20
  llm = LlamaCpp(
21
- model_path="mistral-7b-instruct-v0.1.Q4_K_M.gguf",
22
  temperature=0.75,
23
  max_tokens=2000,
24
  n_ctx = 4000,
25
- top_p=1,
26
- n_gpu_layers=10)
27
 
28
- custom_prompt_template = """You are a medical practitioner who provides right medical information. Use the given following pieces of information to answer the user's question correctly. Add additional information from your knowledge base if necessary. If you don't know the answer, just say that you don't know, don't try to make up an answer.
 
29
 
30
  Context: {context}
31
 
32
- Current conversation: {chat_history}
33
 
34
- Human: {question}
35
- Only return the helpful answer below and nothing else.
36
 
37
- AI Assistant:
38
  """
39
  prompt = PromptTemplate(template=custom_prompt_template,
40
- input_variables=['context', 'question','chat_history'])
41
 
42
  qa = ConversationalRetrievalChain.from_llm(
43
  llm=llm,
44
- memory=ConversationBufferMemory(
45
- memory_key="chat_history",
46
- ai_prefix="AI Assistant",
47
- return_messages=True
48
- ),
49
  retriever=db_retriever,
50
  combine_docs_chain_kwargs={'prompt': prompt}
51
  )
52
 
53
- if "messages" not in st.session_state:
54
- st.session_state.messages = []
55
-
56
- # st.write(st.session_state.messages)
57
-
58
  for message in st.session_state.messages:
59
  with st.chat_message(message.get("role")):
60
  st.write(message.get("content"))
61
 
62
- prompt = st.chat_input("Say something")
63
 
64
- if prompt:
65
  with st.chat_message("user"):
66
- st.write(prompt)
67
 
68
- st.session_state.messages.append({"role":"user","content":prompt})
69
 
70
  with st.chat_message("assistant"):
71
- with st.status("Thinking...",expanded=True):
72
- st_callback = StreamlitCallbackHandler(st.container())
73
- result = qa.invoke(input=prompt,callbacks=[st_callback])
74
- st.session_state.messages.append({"role":"assistant","content":result["answer"]})
75
  message_placeholder = st.empty()
76
- full_response = ""
77
 
78
- for chunk in result["answer"].split():
79
- full_response+=chunk+" "
80
- time.sleep(0.10)
 
 
 
 
81
 
82
- message_placeholder.markdown(full_response)
 
1
  from langchain_community.vectorstores import FAISS
2
  from langchain_community.embeddings import HuggingFaceEmbeddings
 
 
 
3
  from langchain.prompts import PromptTemplate
4
  from langchain_community.llms import LlamaCpp
5
+ from langchain.memory import ConversationBufferWindowMemory
6
  from langchain.chains import ConversationalRetrievalChain
7
  import streamlit as st
 
8
  import time
9
+
10
+ col1, col2, col3 = st.columns([1,4,1])
11
+ with col2:
12
+ st.image("https://github.com/harshitv804/MedChat/assets/100853494/0aa18d7e-5305-4d8e-89d8-09fffce1589e")
13
+
14
+ st.markdown(
15
+ """
16
+ <style>
17
+ div.stButton > button:first-child {
18
+ background-color: #ffd0d0;
19
+ }
20
+ div.stButton > button:active {
21
+ background-color: #ff6262;
22
+ }
23
+
24
+ div[data-testid="stStatusWidget"] div button {
25
+ display: none;
26
+ }
27
+
28
+ .reportview-container {
29
+ margin-top: -2em;
30
+ }
31
+ #MainMenu {visibility: hidden;}
32
+ .stDeployButton {display:none;}
33
+ footer {visibility: hidden;}
34
+ #stDecoration {display:none;}
35
+ button[title="View fullscreen"]{
36
+ visibility: hidden;}
37
+ </style>
38
+ """,
39
+ unsafe_allow_html=True,
40
+ )
41
+
42
+ def reset_conversation():
43
+ st.session_state.messages = []
44
+ st.session_state.memory.clear()
45
+
46
+ if "messages" not in st.session_state:
47
+ st.session_state.messages = []
48
+
49
+ if "memory" not in st.session_state:
50
+ st.session_state.memory = ConversationBufferWindowMemory(k=3, memory_key="chat_history",return_messages=True)
51
 
52
  embeddings = HuggingFaceEmbeddings(model_name="BAAI/llm-embedder")
53
  db = FAISS.load_local("faiss_index", embeddings)
54
  db_retriever = db.as_retriever(search_type="similarity",search_kwargs={"k": 3})
 
55
 
56
  llm = LlamaCpp(
57
+ model_path=r"C:\Users\TESS\Downloads\stablelm-zephyr-3b.Q4_K_M.gguf",
58
  temperature=0.75,
59
  max_tokens=2000,
60
  n_ctx = 4000,
61
+ top_p=1)
 
62
 
63
+
64
+ custom_prompt_template = """You are a medical practitioner who provides right medical information. Use the given following pieces of information to answer the user's question correctly. If you don't know the answer, just say that you don't know, don't try to make up an answer. Utilize the provided knowledge base and search for relevant information. Follow and answer the question format closely. Give only the important information. The information should be abstract, high quality content and comprehensive.
65
 
66
  Context: {context}
67
 
68
+ History: {chat_history}
69
 
70
+ Question: {question}
 
71
 
72
+ Answer:
73
  """
74
  prompt = PromptTemplate(template=custom_prompt_template,
75
+ input_variables=['context', 'question', 'chat_history'])
76
 
77
  qa = ConversationalRetrievalChain.from_llm(
78
  llm=llm,
79
+ memory=st.session_state.memory,
 
 
 
 
80
  retriever=db_retriever,
81
  combine_docs_chain_kwargs={'prompt': prompt}
82
  )
83
 
 
 
 
 
 
84
  for message in st.session_state.messages:
85
  with st.chat_message(message.get("role")):
86
  st.write(message.get("content"))
87
 
88
+ input_prompt = st.chat_input("Say something")
89
 
90
+ if input_prompt:
91
  with st.chat_message("user"):
92
+ st.write(input_prompt)
93
 
94
+ st.session_state.messages.append({"role":"user","content":input_prompt})
95
 
96
  with st.chat_message("assistant"):
97
+ with st.status("Thinking 💡...",expanded=True):
98
+ result = qa.invoke(input=input_prompt)
99
+
 
100
  message_placeholder = st.empty()
 
101
 
102
+ full_response = "⚠️ **_Note: Information provided may be inaccurate. Consult a qualified doctor for accurate advice._** \n\n\n"
103
+ for chunk in result["answer"]:
104
+ full_response+=chunk
105
+ time.sleep(0.02)
106
+
107
+ message_placeholder.markdown(full_response+" ▌")
108
+ st.button('Reset All Chat 🗑️', on_click=reset_conversation)
109
 
110
+ st.session_state.messages.append({"role":"assistant","content":result["answer"]})