Abs6187 commited on
Commit
0e99a04
·
verified ·
1 Parent(s): ce02f1e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -25
app.py CHANGED
@@ -1,5 +1,5 @@
1
- import os
2
  import time
 
3
  import streamlit as st
4
  from langchain_community.vectorstores import FAISS
5
  from langchain_community.embeddings import HuggingFaceEmbeddings
@@ -7,14 +7,13 @@ from langchain.prompts import PromptTemplate
7
  from langchain.memory import ConversationBufferWindowMemory
8
  from langchain.chains import ConversationalRetrievalChain
9
  from langchain_together import Together
10
- from footer import footer # Ensure this module is present in the working directory
11
- from dotenv import load_dotenv
12
- import os
13
 
14
- # Set Streamlit configuration
15
- st.set_page_config(page_title="AI Legal App", layout="centered")
16
 
17
- # Display a logo or banner (replace with a local image or URL)
 
 
 
18
  col1, col2, col3 = st.columns([1, 30, 1])
19
  with col2:
20
  st.image("https://github.com/Nike-one/BharatLAW/blob/master/images/banner.png?raw=true", use_column_width=True)
@@ -29,7 +28,7 @@ def hide_hamburger_menu():
29
 
30
  hide_hamburger_menu()
31
 
32
- # Initialize session state
33
  if "messages" not in st.session_state:
34
  st.session_state.messages = []
35
 
@@ -47,29 +46,44 @@ db_retriever = db.as_retriever(search_type="similarity", search_kwargs={"k": 3})
47
 
48
  prompt_template = """
49
  <s>[INST]
50
- As a legal chatbot specializing in Indian law, your responses must be concise and accurate:
51
- - Provide bullet points summarizing key legal aspects.
52
- - Avoid assumptions or overly specific advice unless requested.
53
- - Clarify any common misconceptions.
54
- - Keep responses aligned with general legal principles.
 
 
 
55
  CONTEXT: {context}
56
  CHAT HISTORY: {chat_history}
57
  QUESTION: {question}
58
  ANSWER:
 
 
 
 
 
59
  </s>[INST]
60
  """
61
 
 
 
62
  prompt = PromptTemplate(template=prompt_template,
63
  input_variables=['context', 'question', 'chat_history'])
64
- load_dotenv()
65
  api_key = os.getenv('TOGETHER_API_KEY')
66
  llm = Together(model="mistralai/Mixtral-8x22B-Instruct-v0.1", temperature=0.5, max_tokens=1024, together_api_key=api_key)
67
 
68
  qa = ConversationalRetrievalChain.from_llm(llm=llm, memory=st.session_state.memory, retriever=db_retriever, combine_docs_chain_kwargs={'prompt': prompt})
69
 
70
  def extract_answer(full_response):
71
- """Extracts the assistant's answer from the response."""
72
- return full_response.strip()
 
 
 
 
 
73
 
74
  def reset_conversation():
75
  st.session_state.messages = []
@@ -79,28 +93,34 @@ for message in st.session_state.messages:
79
  with st.chat_message(message["role"]):
80
  st.write(message["content"])
81
 
82
- input_prompt = st.chat_input("Ask your legal query...")
 
83
  if input_prompt:
84
  with st.chat_message("user"):
85
  st.markdown(f"**You:** {input_prompt}")
86
 
87
  st.session_state.messages.append({"role": "user", "content": input_prompt})
88
  with st.chat_message("assistant"):
89
- with st.spinner("Analyzing..."):
90
  result = qa.invoke(input=input_prompt)
91
  message_placeholder = st.empty()
92
  answer = extract_answer(result["answer"])
93
 
94
- # Simulated typing effect
95
- response = ""
96
- for char in answer:
97
- response += char
98
- time.sleep(0.02)
99
- message_placeholder.markdown(response + " |", unsafe_allow_html=True)
 
100
 
101
  st.session_state.messages.append({"role": "assistant", "content": answer})
102
 
103
- if st.button('🗑️ Reset Chat', on_click=reset_conversation):
104
  st.experimental_rerun()
105
 
 
 
 
106
  footer()
 
 
 
1
  import time
2
+ import os
3
  import streamlit as st
4
  from langchain_community.vectorstores import FAISS
5
  from langchain_community.embeddings import HuggingFaceEmbeddings
 
7
  from langchain.memory import ConversationBufferWindowMemory
8
  from langchain.chains import ConversationalRetrievalChain
9
  from langchain_together import Together
 
 
 
10
 
11
+ from footer import footer
 
12
 
13
+ # Set the Streamlit page configuration and theme
14
+ st.set_page_config(page_title="BharatLAW", layout="centered")
15
+
16
+ # Display the logo image
17
  col1, col2, col3 = st.columns([1, 30, 1])
18
  with col2:
19
  st.image("https://github.com/Nike-one/BharatLAW/blob/master/images/banner.png?raw=true", use_column_width=True)
 
28
 
29
  hide_hamburger_menu()
30
 
31
+ # Initialize session state for messages and memory
32
  if "messages" not in st.session_state:
33
  st.session_state.messages = []
34
 
 
46
 
47
  prompt_template = """
48
  <s>[INST]
49
+ As a legal chatbot specializing in the Indian Penal Code, you are tasked with providing highly accurate and contextually appropriate responses. Ensure your answers meet these criteria:
50
+ - Respond in a bullet-point format to clearly delineate distinct aspects of the legal query.
51
+ - Each point should accurately reflect the breadth of the legal provision in question, avoiding over-specificity unless directly relevant to the user's query.
52
+ - Clarify the general applicability of the legal rules or sections mentioned, highlighting any common misconceptions or frequently misunderstood aspects.
53
+ - Limit responses to essential information that directly addresses the user's question, providing concise yet comprehensive explanations.
54
+ - Avoid assuming specific contexts or details not provided in the query, focusing on delivering universally applicable legal interpretations unless otherwise specified.
55
+ - Conclude with a brief summary that captures the essence of the legal discussion and corrects any common misinterpretations related to the topic.
56
+
57
  CONTEXT: {context}
58
  CHAT HISTORY: {chat_history}
59
  QUESTION: {question}
60
  ANSWER:
61
+ - [Detail the first key aspect of the law, ensuring it reflects general application]
62
+ - [Provide a concise explanation of how the law is typically interpreted or applied]
63
+ - [Correct a common misconception or clarify a frequently misunderstood aspect]
64
+ - [Detail any exceptions to the general rule, if applicable]
65
+ - [Include any additional relevant information that directly relates to the user's query]
66
  </s>[INST]
67
  """
68
 
69
+
70
+
71
  prompt = PromptTemplate(template=prompt_template,
72
  input_variables=['context', 'question', 'chat_history'])
73
+
74
  api_key = os.getenv('TOGETHER_API_KEY')
75
  llm = Together(model="mistralai/Mixtral-8x22B-Instruct-v0.1", temperature=0.5, max_tokens=1024, together_api_key=api_key)
76
 
77
  qa = ConversationalRetrievalChain.from_llm(llm=llm, memory=st.session_state.memory, retriever=db_retriever, combine_docs_chain_kwargs={'prompt': prompt})
78
 
79
  def extract_answer(full_response):
80
+ """Extracts the answer from the LLM's full response by removing the instructional text."""
81
+ answer_start = full_response.find("Response:")
82
+ if answer_start != -1:
83
+ answer_start += len("Response:")
84
+ answer_end = len(full_response)
85
+ return full_response[answer_start:answer_end].strip()
86
+ return full_response
87
 
88
  def reset_conversation():
89
  st.session_state.messages = []
 
93
  with st.chat_message(message["role"]):
94
  st.write(message["content"])
95
 
96
+
97
+ input_prompt = st.chat_input("Say something...")
98
  if input_prompt:
99
  with st.chat_message("user"):
100
  st.markdown(f"**You:** {input_prompt}")
101
 
102
  st.session_state.messages.append({"role": "user", "content": input_prompt})
103
  with st.chat_message("assistant"):
104
+ with st.spinner("Thinking 💡..."):
105
  result = qa.invoke(input=input_prompt)
106
  message_placeholder = st.empty()
107
  answer = extract_answer(result["answer"])
108
 
109
+ # Initialize the response message
110
+ full_response = "⚠️ **_Gentle reminder: We generally ensure precise information, but do double-check._** \n\n\n"
111
+ for chunk in answer:
112
+ # Simulate typing by appending chunks of the response over time
113
+ full_response += chunk
114
+ time.sleep(0.02) # Adjust the sleep time to control the "typing" speed
115
+ message_placeholder.markdown(full_response + " |", unsafe_allow_html=True)
116
 
117
  st.session_state.messages.append({"role": "assistant", "content": answer})
118
 
119
+ if st.button('🗑️ Reset All Chat', on_click=reset_conversation):
120
  st.experimental_rerun()
121
 
122
+
123
+
124
+ # Define the CSS to style the footer
125
  footer()
126
+