sattari commited on
Commit
1f64567
·
verified ·
1 Parent(s): 8f9ea07

Update LegalBot2.py

Browse files
Files changed (1) hide show
  1. LegalBot2.py +89 -35
LegalBot2.py CHANGED
@@ -1,31 +1,35 @@
1
  import os
2
  import streamlit as st
3
- from langchain_openai import OpenAIEmbeddings
4
- from langchain_openai.chat_models import ChatOpenAI
5
- from langchain_community.vectorstores import Chroma
6
  from langchain.chains import RetrievalQA
7
- from langchain.prompts import PromptTemplate
8
  from langchain.memory import ConversationBufferMemory
9
- from langchain.agents import initialize_agent, Tool
10
  from langchain.text_splitter import CharacterTextSplitter
11
  import openai
12
 
13
- # Set OpenAI API Key securely
14
- openai_api_key = os.environ.get("OPENAI_API_KEY")
15
- if not openai_api_key:
16
- raise ValueError("OpenAI API key is not set in environment variables.")
17
- os.environ["OPENAI_API_KEY"] = openai_api_key
18
 
19
  # Document file paths
20
  file1 = "./data/DIVISION OF ASSETS AFTER DIVORCE.txt"
21
  file2 = "./data/INHERITANCE.txt"
22
 
 
 
23
  def openai_setting():
24
  embedding = OpenAIEmbeddings()
25
- model_name = "gpt-3.5-turbo"
 
26
  llm = ChatOpenAI(model_name=model_name, temperature=0)
27
  return embedding, llm
28
 
 
 
29
  def law_content_splitter(path, splitter="CIVIL CODE"):
30
  with open(path) as f:
31
  law_content = f.read()
@@ -33,28 +37,61 @@ def law_content_splitter(path, splitter="CIVIL CODE"):
33
  text_splitter = CharacterTextSplitter()
34
  return text_splitter.create_documents(law_content_by_article)
35
 
 
 
36
  def is_greeting(input_str):
37
  greetings = [
38
- "hello", "hi", "hey", "greetings", "good morning", "good afternoon",
39
- "good evening", "hi there", "hello there", "hey there",
40
- "whats up", "ciao", "salve", "buongiorno",
41
- "buona sera", "buonasera", "buon pomeriggio", "buonpomeriggio",
42
- "come stai", "comestai", "come va", "comeva", "come sta", "comesta"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  ]
44
  return any(greet in input_str.lower() for greet in greetings)
45
 
46
- def chatbot1(question, agent):
 
 
47
  try:
48
  return agent.run(question)
49
  except Exception as e:
50
- print(f"Error: {e}")
51
- return "I'm sorry, I'm having trouble understanding your question."
52
 
53
- def chatbot(input_str, agent):
 
54
  if is_greeting(input_str):
55
  return "Hello! Ask me your question about Italian Divorce or Inheritance Law?"
56
  else:
57
- return chatbot1(input_str, agent)
 
 
 
 
 
 
 
 
 
 
58
 
59
  # Splitting the content of law documents
60
  divorce_splitted = law_content_splitter(file1)
@@ -74,12 +111,15 @@ You should capably address queries regarding asset allocation, child custody, sp
74
  {context}
75
 
76
  Question: {question}"""
77
- DIVORCE_BOT_PROMPT = PromptTemplate(template=divorce_prompt, input_variables=["context", "question"])
 
 
78
 
 
79
  inheritance_prompt = """As a specialist in Italian inheritance law, you should deliver detailed and accurate insights about inheritance regulations in Italy.
80
  You should always cite the article numbers you reference.
81
  When responding to user queries, you should always base your answers on the provided context.
82
- Always MUST MUST cite the specific article numbers you mention and refrain from speculating.
83
  Maintain precision in all your responses.
84
  If a user's question doesn't align with the legal documents, you should point out that it's beyond your domain of expertise.
85
  You should elucidate Italian inheritance law comprehensively, touching on topics such as testamentary inheritance, intestate inheritance, and other pertinent subjects.
@@ -91,7 +131,9 @@ You should provide detailed information on tax nuances associated with inheritan
91
  {context}
92
 
93
  Question: {question}"""
94
- INHERITANCE_BOT_PROMPT = PromptTemplate(template=inheritance_prompt, input_variables=["context", "question"])
 
 
95
 
96
  # Setup for Chroma databases and RetrievalQA
97
  chroma_directory = "./docs/chroma"
@@ -123,30 +165,38 @@ tools = [
123
  Tool(
124
  name="Divorce Italian law QA System",
125
  func=divorce.run,
126
- description="useful for when you need to answer questions about divorce laws in Italy. Give also the number of article you use for it.",
127
  ),
128
  Tool(
129
  name="Inheritance Italian law QA System",
130
  func=inheritance.run,
131
- description="useful for when you need to answer questions about inheritance laws in Italy. Give also the number of article you use for it.",
132
  ),
133
  ]
134
 
135
  # Initialize conversation memory and ReAct agent
136
- memory = ConversationBufferMemory(memory_key="chat_history", input_key="input", output_key="output")
137
- agent = initialize_agent(tools, llm, agent="zero-shot-react-description", memory=memory, verbose=False)
 
 
 
 
 
 
138
 
139
  # Streamlit UI Setup
140
- def setup_ui(agent):
141
  st.set_page_config(page_title="Italian Law Chatbot", page_icon="⚖️")
142
  st.title("🏛️ Legal Chatbot: Divorce and Inheritance Italy Laws ")
143
 
144
- st.write("""
 
145
  [![HuggingFace Space](https://huggingface.co/datasets/huggingface/badges/resolve/main/open-in-hf-spaces-sm.svg)](https://huggingface.co/spaces/sattari/legal-chat-bot/tree/main)
146
  [![Github Repository](https://img.shields.io/badge/GitHub%20Repository-gray?logo=github)](https://github.com/pouyasattari/Legal-Chatbot-italy-divorce-inheritance)
147
  [![SATTARI.org](https://img.shields.io/badge/SATTARI.org-gray?logo=internetexplorer)](https://www.sattari.org)
148
  ![Visitors](https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2Fsattari-legal-chat-bot.hf.space&label=Visitors&labelColor=%235d5d5d&countColor=%231e7ebf&style=flat)
149
- """)
 
150
 
151
  st.info(
152
  "Check out full tutorial to build this app on Streamlit [📝 blog](https://sattari.org/legal-chatbot-divorce-and-inheritance-italy-laws/)",
@@ -157,7 +207,6 @@ def setup_ui(agent):
157
  "Check out [Prompt Examples List](https://github.com/pouyasattari/Legal-Chatbot-italy-divorce-inheritance/blob/main/promptExamples.txt) to know how to interact with this ChatBot 🤗 ",
158
  icon="✅",
159
  )
160
-
161
  if "messages" not in st.session_state:
162
  st.session_state.messages = [
163
  {
@@ -171,7 +220,9 @@ def setup_ui(agent):
171
  with st.chat_message(message["role"]):
172
  st.markdown(message["content"])
173
 
174
- if user_input := st.chat_input("Ask a question about Italian Divorce or Inheritance Law:"):
 
 
175
  st.session_state.messages.append({"role": "user", "content": user_input})
176
  with st.chat_message("user"):
177
  st.markdown(user_input)
@@ -179,11 +230,14 @@ def setup_ui(agent):
179
  # Generate and display chatbot response
180
  with st.chat_message("assistant"):
181
  response_placeholder = st.empty()
182
- response = chatbot(user_input, agent) # Pass the agent to the chatbot function
183
  response_placeholder.markdown(response)
184
 
185
  # Append the response to the conversation history
186
  st.session_state.messages.append({"role": "assistant", "content": response})
187
 
 
 
 
188
  if __name__ == "__main__":
189
- setup_ui(agent)
 
1
  import os
2
  import streamlit as st
3
+ from langchain.embeddings.openai import OpenAIEmbeddings
4
+ from langchain.vectorstores import Chroma
5
+ from langchain.chat_models import ChatOpenAI
6
  from langchain.chains import RetrievalQA
7
+ from langchain import PromptTemplate
8
  from langchain.memory import ConversationBufferMemory
9
+ from langchain.agents import initialize_agent, Tool, AgentExecutor
10
  from langchain.text_splitter import CharacterTextSplitter
11
  import openai
12
 
13
+ # Set OpenAI API Key
14
+ OPENAI_API_KEY = "sk-XC6vDUoMgm_qjeT-iAKtJOrPHLZZAupnjO39kh_x9nT3BlbkFJ-tfz3_p02QWfnC77SnWI32IPWLAqtLnX_VMlBpTH4A"
15
+ os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
16
+ openai.api_key = OPENAI_API_KEY
 
17
 
18
  # Document file paths
19
  file1 = "./data/DIVISION OF ASSETS AFTER DIVORCE.txt"
20
  file2 = "./data/INHERITANCE.txt"
21
 
22
+
23
+ # Function to initialize the OpenAI embeddings and model
24
  def openai_setting():
25
  embedding = OpenAIEmbeddings()
26
+ # model_name = "gpt-3.5-turbo"
27
+ model_name = "gpt-4o-mini"
28
  llm = ChatOpenAI(model_name=model_name, temperature=0)
29
  return embedding, llm
30
 
31
+
32
+ # Function to split the law content
33
  def law_content_splitter(path, splitter="CIVIL CODE"):
34
  with open(path) as f:
35
  law_content = f.read()
 
37
  text_splitter = CharacterTextSplitter()
38
  return text_splitter.create_documents(law_content_by_article)
39
 
40
+
41
+ # Function to determine if input is a greeting
42
  def is_greeting(input_str):
43
  greetings = [
44
+ "hello",
45
+ "hi",
46
+ "hey",
47
+ "greetings",
48
+ "good morning",
49
+ "good afternoon",
50
+ "good evening",
51
+ "hi there",
52
+ "hello there",
53
+ "hey there",
54
+ "whats up",
55
+ "ciao",
56
+ "salve",
57
+ "buongiorno",
58
+ "buona sera",
59
+ "buonasera",
60
+ "buon pomeriggio",
61
+ "buonpomeriggio",
62
+ "come stai",
63
+ "comestai",
64
+ "come va",
65
+ "comeva",
66
+ "come sta",
67
+ "comesta",
68
  ]
69
  return any(greet in input_str.lower() for greet in greetings)
70
 
71
+
72
+ # Function to handle chatbot logic
73
+ def chatbot1(question):
74
  try:
75
  return agent.run(question)
76
  except Exception as e:
77
+ return f"I'm sorry, I'm having trouble understanding your question. Error: {str(e)}"
 
78
 
79
+
80
+ def chatbot(input_str):
81
  if is_greeting(input_str):
82
  return "Hello! Ask me your question about Italian Divorce or Inheritance Law?"
83
  else:
84
+ return chatbot1(input_str)
85
+
86
+
87
+ # If you want to disable Greeting in the chatbot, use this code:
88
+ # def chatbot(input_str):
89
+ # # Directly process every input as a question
90
+ # response = chatbot1(input_str)
91
+ # if response == "N/A":
92
+ # return "I'm sorry, I'm having trouble understanding your question. Could you please rephrase it or provide more context"
93
+ # else:
94
+ # return response
95
 
96
  # Splitting the content of law documents
97
  divorce_splitted = law_content_splitter(file1)
 
111
  {context}
112
 
113
  Question: {question}"""
114
+ DIVORCE_BOT_PROMPT = PromptTemplate(
115
+ template=divorce_prompt, input_variables=["context", "question"]
116
+ )
117
 
118
+ # Define inheritance prompt
119
  inheritance_prompt = """As a specialist in Italian inheritance law, you should deliver detailed and accurate insights about inheritance regulations in Italy.
120
  You should always cite the article numbers you reference.
121
  When responding to user queries, you should always base your answers on the provided context.
122
+ Always MUST cite the specific article numbers you mention and refrain from speculating.
123
  Maintain precision in all your responses.
124
  If a user's question doesn't align with the legal documents, you should point out that it's beyond your domain of expertise.
125
  You should elucidate Italian inheritance law comprehensively, touching on topics such as testamentary inheritance, intestate inheritance, and other pertinent subjects.
 
131
  {context}
132
 
133
  Question: {question}"""
134
+ INHERITANCE_BOT_PROMPT = PromptTemplate(
135
+ template=inheritance_prompt, input_variables=["context", "question"]
136
+ )
137
 
138
  # Setup for Chroma databases and RetrievalQA
139
  chroma_directory = "./docs/chroma"
 
165
  Tool(
166
  name="Divorce Italian law QA System",
167
  func=divorce.run,
168
+ description="Useful for when you need to answer questions about divorce laws in Italy. Also provides the number of the article you use.",
169
  ),
170
  Tool(
171
  name="Inheritance Italian law QA System",
172
  func=inheritance.run,
173
+ description="Useful for when you need to answer questions about inheritance laws in Italy. Also provides the number of the article you use.",
174
  ),
175
  ]
176
 
177
  # Initialize conversation memory and ReAct agent
178
+ memory = ConversationBufferMemory(
179
+ memory_key="chat_history", input_key="input", output_key="output"
180
+ )
181
+ react = initialize_agent(tools, llm, agent="zero-shot-react-description")
182
+ agent = AgentExecutor.from_agent_and_tools(
183
+ tools=tools, agent=react.agent, memory=memory, verbose=False
184
+ )
185
+
186
 
187
  # Streamlit UI Setup
188
+ def setup_ui():
189
  st.set_page_config(page_title="Italian Law Chatbot", page_icon="⚖️")
190
  st.title("🏛️ Legal Chatbot: Divorce and Inheritance Italy Laws ")
191
 
192
+ st.write(
193
+ """
194
  [![HuggingFace Space](https://huggingface.co/datasets/huggingface/badges/resolve/main/open-in-hf-spaces-sm.svg)](https://huggingface.co/spaces/sattari/legal-chat-bot/tree/main)
195
  [![Github Repository](https://img.shields.io/badge/GitHub%20Repository-gray?logo=github)](https://github.com/pouyasattari/Legal-Chatbot-italy-divorce-inheritance)
196
  [![SATTARI.org](https://img.shields.io/badge/SATTARI.org-gray?logo=internetexplorer)](https://www.sattari.org)
197
  ![Visitors](https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2Fsattari-legal-chat-bot.hf.space&label=Visitors&labelColor=%235d5d5d&countColor=%231e7ebf&style=flat)
198
+ """
199
+ )
200
 
201
  st.info(
202
  "Check out full tutorial to build this app on Streamlit [📝 blog](https://sattari.org/legal-chatbot-divorce-and-inheritance-italy-laws/)",
 
207
  "Check out [Prompt Examples List](https://github.com/pouyasattari/Legal-Chatbot-italy-divorce-inheritance/blob/main/promptExamples.txt) to know how to interact with this ChatBot 🤗 ",
208
  icon="✅",
209
  )
 
210
  if "messages" not in st.session_state:
211
  st.session_state.messages = [
212
  {
 
220
  with st.chat_message(message["role"]):
221
  st.markdown(message["content"])
222
 
223
+ if user_input := st.chat_input(
224
+ "Ask a question about Italian Divorce or Inheritance Law:"
225
+ ):
226
  st.session_state.messages.append({"role": "user", "content": user_input})
227
  with st.chat_message("user"):
228
  st.markdown(user_input)
 
230
  # Generate and display chatbot response
231
  with st.chat_message("assistant"):
232
  response_placeholder = st.empty()
233
+ response = chatbot(user_input) # Your existing chatbot function
234
  response_placeholder.markdown(response)
235
 
236
  # Append the response to the conversation history
237
  st.session_state.messages.append({"role": "assistant", "content": response})
238
 
239
+
240
+ ## Made by Pouya / www.SATTARI.org
241
+
242
  if __name__ == "__main__":
243
+ setup_ui()