sattari commited on
Commit
8e87361
·
verified ·
1 Parent(s): 371e063

Create LegalBot2.py

Browse files
Files changed (1) hide show
  1. LegalBot2.py +189 -0
LegalBot2.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()
32
+ law_content_by_article = law_content.split(splitter)[1:]
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)
61
+ inheritance_splitted = law_content_splitter(file2)
62
+
63
+ # Initializing embedding and language model
64
+ embedding, llm = openai_setting()
65
+
66
+ # Define the prompts
67
+ divorce_prompt = """As a specialized bot in divorce law, you should offer accurate insights on Italian divorce regulations.
68
+ You should always cite the article numbers you reference.
69
+ Ensure you provide detailed and exact data.
70
+ If a query doesn't pertain to the legal documents, you should remind the user that it falls outside your expertise.
71
+ You should be adept at discussing the various Italian divorce categories, including fault-based divorce, mutual-consent divorce, and divorce due to infidelity.
72
+ You should guide users through the prerequisites and procedures of each divorce type, detailing the essential paperwork, expected duration, and potential legal repercussions.
73
+ 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.
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.
86
+ 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.
87
+ You should adeptly tackle questions about various will forms like holographic or notarial wills, ensuring you clarify their legitimacy within Italian jurisdiction.
88
+ Offer advice on creating a will, naming heirs, and managing potential conflicts.
89
+ You should provide detailed information on tax nuances associated with inheritance in Italy, inclusive of exemptions, tax rates, and mandatory disclosures.
90
+
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"
98
+
99
+ inheritance_db = Chroma.from_documents(
100
+ documents=inheritance_splitted,
101
+ embedding=embedding,
102
+ persist_directory=chroma_directory,
103
+ )
104
+ inheritance = RetrievalQA.from_chain_type(
105
+ llm=llm,
106
+ chain_type="stuff",
107
+ retriever=inheritance_db.as_retriever(),
108
+ chain_type_kwargs={"prompt": INHERITANCE_BOT_PROMPT},
109
+ )
110
+
111
+ divorce_db = Chroma.from_documents(
112
+ documents=divorce_splitted, embedding=embedding, persist_directory=chroma_directory
113
+ )
114
+ divorce = RetrievalQA.from_chain_type(
115
+ llm=llm,
116
+ chain_type="stuff",
117
+ retriever=divorce_db.as_retriever(),
118
+ chain_type_kwargs={"prompt": DIVORCE_BOT_PROMPT},
119
+ )
120
+
121
+ # Define the tools for the chatbot
122
+ 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/)",
153
+ icon="ℹ️",
154
+ )
155
+
156
+ st.success(
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
+ {
164
+ "role": "assistant",
165
+ "content": "Hello! I'm here to help you with Italian Divorce or Inheritance Law.",
166
+ }
167
+ ]
168
+
169
+ # Display previous messages and handle new user input
170
+ for message in st.session_state.messages:
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)
178
+
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)