Pouya commited on
Commit
7fcc935
·
verified ·
1 Parent(s): 1e3e93e

Upload Legal ChatBot.py

Browse files
Files changed (1) hide show
  1. Legal ChatBot.py +191 -0
Legal ChatBot.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, AgentExecutor
10
+ from langchain.text_splitter import CharacterTextSplitter
11
+ import openai
12
+
13
+ # Set OpenAI API Key
14
+ openai_api_key = os.environ.get("OPENAI_API_KEY")
15
+ openai.api_key = openai_api_key
16
+
17
+ # Document file paths
18
+ file1 = "./data/DIVISION OF ASSETS AFTER DIVORCE.txt"
19
+ file2 = "./data/INHERITANCE.txt"
20
+
21
+ def openai_setting():
22
+ embedding = OpenAIEmbeddings()
23
+ model_name = "gpt-3.5-turbo"
24
+ llm = ChatOpenAI(model_name=model_name, temperature=0)
25
+ return embedding, llm
26
+
27
+ def law_content_splitter(path, splitter="CIVIL CODE"):
28
+ with open(path) as f:
29
+ law_content = f.read()
30
+ law_content_by_article = law_content.split(splitter)[1:]
31
+ text_splitter = CharacterTextSplitter()
32
+ return text_splitter.create_documents(law_content_by_article)
33
+
34
+ def is_greeting(input_str):
35
+ greetings = [
36
+ "hello", "hi", "hey", "greetings", "good morning", "good afternoon",
37
+ "good evening", "hi there", "hello there", "hey there",
38
+ "whats up", "ciao", "salve", "buongiorno",
39
+ "buona sera", "buonasera", "buon pomeriggio", "buonpomeriggio",
40
+ "come stai", "comestai", "come va", "comeva", "come sta", "comesta"
41
+ ]
42
+ return any(greet in input_str.lower() for greet in greetings)
43
+
44
+ def chatbot1(question):
45
+ try:
46
+ return agent.run(question)
47
+ except:
48
+ return "I'm sorry, I'm having trouble understanding your question."
49
+
50
+ def chatbot(input_str):
51
+ if is_greeting(input_str):
52
+ return "Hello! Ask me your question about Italian Divorce or Inheritance Law?"
53
+ else:
54
+ return chatbot1(input_str)
55
+
56
+
57
+ ### If you wanna disable Greeting in the chatbot, use this code:
58
+ # def chatbot(input_str):
59
+ # # Directly process every input as a question
60
+ # response = chatbot1(input_str)
61
+ # if response == "N/A":
62
+ # return "I'm sorry, I'm having trouble understanding your question. Could you please rephrase it or provide more context"
63
+ # else:
64
+ # return response
65
+
66
+
67
+
68
+ # Splitting the content of law documents
69
+ divorce_splitted = law_content_splitter(file1)
70
+ inheritance_splitted = law_content_splitter(file2)
71
+
72
+ # Initializing embedding and language model
73
+ embedding, llm = openai_setting()
74
+
75
+ # Define the prompts
76
+ divorce_prompt = """As a specialized bot in divorce law, you should offer accurate insights on Italian divorce regulations.
77
+ You should always cite the article numbers you reference.
78
+ Ensure you provide detailed and exact data.
79
+ If a query doesn't pertain to the legal documents, you should remind the user that it falls outside your expertise.
80
+ You should be adept at discussing the various Italian divorce categories, including fault-based divorce, mutual-consent divorce, and divorce due to infidelity.
81
+ You should guide users through the prerequisites and procedures of each divorce type, detailing the essential paperwork, expected duration, and potential legal repercussions.
82
+ You should capably address queries regarding asset allocation, child custody, spousal support, and other financial concerns related to divorce, all while staying true to Italian legislation.
83
+ {context}
84
+
85
+ Question: {question}"""
86
+ DIVORCE_BOT_PROMPT = PromptTemplate(template=divorce_prompt, input_variables=["context", "question"])
87
+
88
+ # define inheritance prompt
89
+ inheritance_prompt = """As a specialist in Italian inheritance law, you should deliver detailed and accurate insights about inheritance regulations in Italy.
90
+ You should always cite the article numbers you reference.
91
+ When responding to user queries, you should always base your answers on the provided context.
92
+ Always cite the specific article numbers you mention and refrain from speculating.
93
+ Maintain precision in all your responses.
94
+ If a user's question doesn't align with the legal documents, you should point out that it's beyond your domain of expertise.
95
+ You should elucidate Italian inheritance law comprehensively, touching on topics such as testamentary inheritance, intestate inheritance, and other pertinent subjects.
96
+ Make sure to elaborate on the obligations and rights of inheritors, the methodology of estate distribution, asset assessment, and settling debts, all while adhering to Italian law specifics.
97
+ You should adeptly tackle questions about various will forms like holographic or notarial wills, ensuring you clarify their legitimacy within Italian jurisdiction.
98
+ Offer advice on creating a will, naming heirs, and managing potential conflicts.
99
+ You should provide detailed information on tax nuances associated with inheritance in Italy, inclusive of exemptions, tax rates, and mandatory disclosures.
100
+
101
+ {context}
102
+
103
+ Question: {question}"""
104
+ INHERITANCE_BOT_PROMPT = PromptTemplate(template=inheritance_prompt, input_variables=["context", "question"])
105
+
106
+ # Setup for Chroma databases and RetrievalQA
107
+ chroma_directory = "./docs/chroma"
108
+
109
+ inheritance_db = Chroma.from_documents(
110
+ documents=inheritance_splitted,
111
+ embedding=embedding,
112
+ persist_directory=chroma_directory,
113
+ )
114
+ inheritance = RetrievalQA.from_chain_type(
115
+ llm=llm,
116
+ chain_type="stuff",
117
+ retriever=inheritance_db.as_retriever(),
118
+ chain_type_kwargs={"prompt": INHERITANCE_BOT_PROMPT},
119
+ )
120
+
121
+ divorce_db = Chroma.from_documents(
122
+ documents=divorce_splitted, embedding=embedding, persist_directory=chroma_directory
123
+ )
124
+ divorce = RetrievalQA.from_chain_type(
125
+ llm=llm,
126
+ chain_type="stuff",
127
+ retriever=divorce_db.as_retriever(),
128
+ chain_type_kwargs={"prompt": DIVORCE_BOT_PROMPT},
129
+ )
130
+
131
+ # Define the tools for the chatbot
132
+ tools = [
133
+ Tool(
134
+ name="Divorce Italian law QA System",
135
+ func=divorce.run,
136
+ description="useful for when you need to answer questions about divorce laws in Italy.Give also the number of article you use for it.",
137
+ ),
138
+ Tool(
139
+ name="Inheritance Italian law QA System",
140
+ func=inheritance.run,
141
+ description="useful for when you need to answer questions about inheritance laws in Italy.Give also the number of article you use for it.",
142
+ ),
143
+ ]
144
+
145
+ # Initialize conversation memory and ReAct agent
146
+ memory = ConversationBufferMemory(memory_key="chat_history", input_key="input", output_key="output")
147
+ react = initialize_agent(tools, llm, agent="zero-shot-react-description")
148
+ agent = AgentExecutor.from_agent_and_tools(tools=tools, agent=react.agent, memory=memory, verbose=False)
149
+
150
+ # Streamlit UI Setup
151
+ def setup_ui():
152
+ st.set_page_config(page_title="Italian Law Chatbot", page_icon="⚖️")
153
+ st.title("Italian Law Chatbot 🏛️")
154
+ st.info(
155
+ "Check out the full tutorial to build this app in our [📝 blog post](https://sattari.org/projects/) — "
156
+ "[GitHub Repository](https://sattari.org)",
157
+ icon="ℹ️",
158
+ )
159
+ st.success(
160
+ "Check out [Prompt Examples List](https://sattari.org/projects/) to learn how to interact with this ChatBot 🤗 ",
161
+ icon="✅",
162
+ )
163
+ if "messages" not in st.session_state:
164
+ st.session_state.messages = [
165
+ {
166
+ "role": "assistant",
167
+ "content": "Hello! I'm here to help you with Italian Divorce or Inheritance Law.",
168
+ }
169
+ ]
170
+
171
+ # Display previous messages and handle new user input
172
+ for message in st.session_state.messages:
173
+ with st.chat_message(message["role"]):
174
+ st.markdown(message["content"])
175
+
176
+ if user_input := st.chat_input("Ask a question about Italian Divorce or Inheritance Law:"):
177
+ st.session_state.messages.append({"role": "user", "content": user_input})
178
+ with st.chat_message("user"):
179
+ st.markdown(user_input)
180
+
181
+ # Generate and display chatbot response
182
+ with st.chat_message("assistant"):
183
+ response_placeholder = st.empty()
184
+ response = chatbot(user_input) # Your existing chatbot function
185
+ response_placeholder.markdown(response)
186
+
187
+ # Append the response to the conversation history
188
+ st.session_state.messages.append({"role": "assistant", "content": response})
189
+
190
+ if __name__ == "__main__":
191
+ setup_ui()