Shreyas commited on
Commit
8dd0947
1 Parent(s): 0a67e08

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +111 -0
app.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, allow_dangerous_deserialization=True)
54
+
55
+ db_retriever = db.as_retriever(search_type="similarity",search_kwargs={"k": 4})
56
+
57
+ 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.
58
+ CONTEXT: {context}
59
+ CHAT HISTORY: {chat_history}
60
+ QUESTION: {question}
61
+ ANSWER:
62
+ </s>[INST]
63
+ """
64
+
65
+ prompt = PromptTemplate(template=prompt_template,
66
+ input_variables=['context', 'question', 'chat_history'])
67
+
68
+ # You can also use other LLMs options from https://python.langchain.com/docs/integrations/llms. Here I have used TogetherAI API
69
+ os.environ["TOGETHER_API_KEY"] = "ce91a607b153fc2fa7a63f6081686beee67b30a6ff2a7e8e8d07d522b361bc55"
70
+ TOGETHER_AI_API = "ce91a607b153fc2fa7a63f6081686beee67b30a6ff2a7e8e8d07d522b361bc55"
71
+ llm = Together(
72
+ model="mistralai/Mistral-7B-Instruct-v0.2",
73
+ temperature=0.5,
74
+ max_tokens=1024,
75
+ together_api_key=TOGETHER_AI_API
76
+ )
77
+
78
+ qa = ConversationalRetrievalChain.from_llm(
79
+ llm=llm,
80
+ memory=st.session_state.memory,
81
+ retriever=db_retriever,
82
+ combine_docs_chain_kwargs={'prompt': prompt}
83
+ )
84
+
85
+ for message in st.session_state.messages:
86
+ with st.chat_message(message.get("role")):
87
+ st.write(message.get("content"))
88
+
89
+ input_prompt = st.chat_input("Say something")
90
+
91
+ if input_prompt:
92
+ with st.chat_message("user"):
93
+ st.write(input_prompt)
94
+
95
+ st.session_state.messages.append({"role":"user","content":input_prompt})
96
+
97
+ with st.chat_message("assistant"):
98
+ with st.status("Thinking 💡...",expanded=True):
99
+ result = qa.invoke(input=input_prompt)
100
+
101
+ message_placeholder = st.empty()
102
+
103
+ full_response = "⚠️ **_Note: Information provided may be inaccurate._** \n\n\n"
104
+ for chunk in result["answer"]:
105
+ full_response+=chunk
106
+ time.sleep(0.02)
107
+
108
+ message_placeholder.markdown(full_response+" ▌")
109
+ st.button('Reset All Chat 🗑️', on_click=reset_conversation)
110
+
111
+ st.session_state.messages.append({"role":"assistant","content":result["answer"]})