divy131 commited on
Commit
ec9f6d8
1 Parent(s): 0c8bc8e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -0
app.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_community.vectorstores import FAISS
2
+ from langchain_community.embeddings import HuggingFaceEmbeddings
3
+ from langchain.prompts import PromptTemplate
4
+ from langchain_together import Together
5
+ import os
6
+ from langchain.memory import ConversationBufferWindowMemory
7
+ from langchain.chains import ConversationalRetrievalChain
8
+ import streamlit as st
9
+ import time
10
+ st.set_page_config(page_title="LawGPT")
11
+ col1, col2, col3 = st.columns([1,4,1])
12
+ with col2:
13
+ st.image("https://github.com/harshitv804/LawGPT/assets/100853494/ecff5d3c-f105-4ba2-a93a-500282f0bf00")
14
+
15
+ st.markdown(
16
+ """
17
+ <style>
18
+ div.stButton > button:first-child {
19
+ background-color: #ffd0d0;
20
+ }
21
+ div.stButton > button:active {
22
+ background-color: #ff6262;
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=2, memory_key="chat_history",return_messages=True)
51
+
52
+ embeddings = HuggingFaceEmbeddings(model_name="nomic-ai/nomic-embed-text-v1",model_kwargs={"trust_remote_code":True,"revision":"289f532e14dbbbd5a04753fa58739e9ba766f3c7"})
53
+ db = FAISS.load_local("ipc_vector_db", embeddings)
54
+ db_retriever = db.as_retriever(search_type="similarity",search_kwargs={"k": 4})
55
+
56
+ prompt_template = """<s>[INST]This is a chat template and As a legal chat bot specializing in Indian Penal Code queries, 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.
57
+ CONTEXT: {context}
58
+ CHAT HISTORY: {chat_history}
59
+ QUESTION: {question}
60
+ ANSWER:
61
+ </s>[INST]
62
+ """
63
+
64
+ prompt = PromptTemplate(template=prompt_template,
65
+ input_variables=['context', 'question', 'chat_history'])
66
+
67
+ # You can also use other LLMs options from https://python.langchain.com/docs/integrations/llms. Here I have used TogetherAI API
68
+ TOGETHER_AI_API= os.environ['TOGETHER_AI']
69
+ llm = Together(
70
+ model="mistralai/Mistral-7B-Instruct-v0.2",
71
+ temperature=0.5,
72
+ max_tokens=1024,
73
+ together_api_key=f"{TOGETHER_AI_API}"
74
+ )
75
+
76
+ qa = ConversationalRetrievalChain.from_llm(
77
+ llm=llm,
78
+ memory=st.session_state.memory,
79
+ retriever=db_retriever,
80
+ combine_docs_chain_kwargs={'prompt': prompt}
81
+ )
82
+
83
+ for message in st.session_state.messages:
84
+ with st.chat_message(message.get("role")):
85
+ st.write(message.get("content"))
86
+
87
+ input_prompt = st.chat_input("Say something")
88
+
89
+ if input_prompt:
90
+ with st.chat_message("user"):
91
+ st.write(input_prompt)
92
+
93
+ st.session_state.messages.append({"role":"user","content":input_prompt})
94
+
95
+ with st.chat_message("assistant"):
96
+ with st.status("Thinking 💡...",expanded=True):
97
+ result = qa.invoke(input=input_prompt)
98
+
99
+ message_placeholder = st.empty()
100
+
101
+ full_response = "⚠️ **_Note: Information provided may be inaccurate._** \n\n\n"
102
+ for chunk in result["answer"]:
103
+ full_response+=chunk
104
+ time.sleep(0.02)
105
+
106
+ message_placeholder.markdown(full_response+" ▌")
107
+ st.button('Reset All Chat 🗑️', on_click=reset_conversation)
108
+
109
+ st.session_state.messages.append({"role":"assistant","content":result["answer"]})