annas4421 commited on
Commit
b380376
β€’
1 Parent(s): 8209f90

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -0
app.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_community.document_loaders import PyPDFLoader,DirectoryLoader
2
+ from langchain.embeddings import HuggingFaceEmbeddings
3
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
4
+ from langchain_community.vectorstores import FAISS
5
+ import os
6
+ from langchain.prompts import PromptTemplate
7
+ from langchain_together import Together
8
+ import os
9
+ from langchain.memory import ConversationBufferWindowMemory
10
+ from langchain.chains import ConversationalRetrievalChain
11
+ import streamlit as st
12
+ import time
13
+
14
+
15
+ embeddings = HuggingFaceEmbeddings(model_name="nomic-ai/nomic-embed-text-v1",model_kwargs={"trust_remote_code":True,"revision":"289f532e14dbbbd5a04753fa58739e9ba766f3c7"})
16
+ #vectordb = Chroma.from_documents(texts, embedding=embeddings, persist_directory="./data")
17
+ #db_retriever =vectordb.as_retriever(search_type="similarity",search_kwargs={'k':4})
18
+
19
+ db = FAISS.load_local("vectordb", embeddings, allow_dangerous_deserialization=True)
20
+ db_retriever = db.as_retriever(search_type="similarity",search_kwargs={"k": 4})
21
+
22
+
23
+ st.set_page_config(page_title="Qanoon-Bot")
24
+ col1, col2, col3 = st.columns([1,4,1])
25
+ with col2:
26
+ st.image("https://s3.ap-south-1.amazonaws.com/makerobosfastcdn/cms-assets/Legal_AI_Chatbot.png")
27
+
28
+ st.markdown(
29
+ """
30
+ <style>
31
+ div.stButton > button:first-child {
32
+ background-color: #ffd0d0;
33
+ }
34
+ div.stButton > button:active {
35
+ background-color: #ff6262;
36
+ }
37
+ div[data-testid="stStatusWidget"] div button {
38
+ display: none;
39
+ }
40
+
41
+ .reportview-container {
42
+ margin-top: -2em;
43
+ }
44
+ #MainMenu {visibility: hidden;}
45
+ .stDeployButton {display:none;}
46
+ footer {visibility: hidden;}
47
+ #stDecoration {display:none;}
48
+ button[title="View fullscreen"]{
49
+ visibility: hidden;}
50
+ </style>
51
+ """,
52
+ unsafe_allow_html=True,
53
+ )
54
+
55
+ def reset_conversation():
56
+ st.session_state.messages = []
57
+ st.session_state.memory.clear()
58
+
59
+ if "messages" not in st.session_state:
60
+ st.session_state.messages = []
61
+
62
+ if "memory" not in st.session_state:
63
+ st.session_state.memory = ConversationBufferWindowMemory(k=2, memory_key="chat_history",return_messages=True)
64
+
65
+ embeddings = HuggingFaceEmbeddings(model_name="nomic-ai/nomic-embed-text-v1",model_kwargs={"trust_remote_code":True,"revision":"289f532e14dbbbd5a04753fa58739e9ba766f3c7"})
66
+ #db=FAISS.load_local("/content/ipc_vector_db", embeddings, allow_dangerous_deserialization=True)
67
+
68
+ prompt_template = """<s>[INST]This is a chat template and As a legal chat bot specializing in pakistan Penal Code queries and , your primary objective is to provide accurate and concise information based on the user's questions. Do not generate your own questions and answers. You will adhere strictly to the instructions provided, offering relevant context from the knowledge base while avoiding unnecessary details. Your responses will be brief, to the point, and in compliance with the established format. If a question falls outside the given context, you will refrain from utilizing the chat history and instead rely on your own knowledge base to generate an appropriate response. You will prioritize the user's query and refrain from posing additional questions. The aim is to deliver professional, precise, and contextually relevant information pertaining to the Indian Penal Code.
69
+ CONTEXT: {context}
70
+ CHAT HISTORY: {chat_history}
71
+ QUESTION: {question}
72
+ ANSWER:
73
+ </s>[INST]
74
+ """
75
+
76
+ prompt = PromptTemplate(template=prompt_template,
77
+ input_variables=['context', 'question', 'chat_history'])
78
+
79
+ # You can also use other LLMs options from https://python.langchain.com/docs/integrations/llms. Here I have used TogetherAI API
80
+
81
+ from config import together_api
82
+ llm = Together(
83
+ model="mistralai/Mistral-7B-Instruct-v0.2",
84
+ temperature=0.5,
85
+ max_tokens=1024,
86
+ together_api_key=together_api
87
+ )
88
+ qa = ConversationalRetrievalChain.from_llm(
89
+ llm=llm,
90
+ memory=st.session_state.memory,
91
+ retriever=db_retriever,
92
+ combine_docs_chain_kwargs={'prompt': prompt}
93
+ )
94
+
95
+ for message in st.session_state.messages:
96
+ with st.chat_message(message.get("role")):
97
+ st.write(message.get("content"))
98
+
99
+ input_prompt = st.chat_input("Say something")
100
+
101
+ if input_prompt:
102
+ with st.chat_message("user"):
103
+ st.write(input_prompt)
104
+
105
+ st.session_state.messages.append({"role":"user","content":input_prompt})
106
+
107
+ with st.chat_message("assistant"):
108
+ with st.status("Thinking πŸ’‘...",expanded=True):
109
+ result = qa.invoke(input=input_prompt)
110
+
111
+ message_placeholder = st.empty()
112
+
113
+ full_response = "**_Note: Information provided by Qanoon-Bot may be inaccurate. ** \n\n\n"
114
+ for chunk in result["answer"]:
115
+ full_response+=chunk
116
+ time.sleep(0.02)
117
+
118
+ message_placeholder.markdown(full_response+" β–Œ")
119
+ st.button('Reset All Chat πŸ—‘οΈ', on_click=reset_conversation)
120
+
121
+ st.session_state.messages.append({"role":"assistant","content":result["answer"]})