StevenChen16 commited on
Commit
52e5df1
1 Parent(s): ba222bb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +170 -128
app.py CHANGED
@@ -1,21 +1,177 @@
1
  import gradio as gr
2
  import os
3
  import spaces
4
- from transformers import GemmaTokenizer, AutoModelForCausalLM
5
  from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
6
  from threading import Thread
 
 
7
 
8
- # Set an environment variable
9
- HF_TOKEN = os.environ.get("HF_TOKEN", None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
 
11
 
 
 
 
12
 
13
- MODEL_NAME_OR_PATH = 'StevenChen16/llama3-8b-Lawyer'
14
- # MODEL_NAME_OR_PATH = 'nvidia/Llama3-ChatQA-1.5-8B'
15
 
 
 
 
 
16
 
 
17
 
 
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  DESCRIPTION = '''
20
  <div style="display: flex; align-items: center; justify-content: center; text-align: center;">
21
  <a href="https://wealthwizards.org/" target="_blank">
@@ -43,7 +199,6 @@ PLACEHOLDER = """
43
  </div>
44
  """
45
 
46
-
47
  css = """
48
  h1 {
49
  text-align: center;
@@ -57,129 +212,16 @@ h1 {
57
  }
58
  """
59
 
60
- # Load the tokenizer and model
61
- tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME_OR_PATH)
62
- model = AutoModelForCausalLM.from_pretrained(MODEL_NAME_OR_PATH, device_map="auto") # to("cuda:0")
63
- terminators = [
64
- tokenizer.eos_token_id,
65
- tokenizer.convert_tokens_to_ids("<|eot_id|>")
66
- ]
67
-
68
-
69
- background_prompt = '''
70
- As an AI legal assistant, you are a highly trained expert in U.S. and Canadian law. Your purpose is to provide accurate, comprehensive, and professional legal information to assist users with a wide range of legal questions. When answering questions, you should actively ask questions to obtain more information, analyze from different perspectives, and explain your reasoning process to the user.
71
-
72
- In addition to providing general legal advice and analysis, you are also capable of assisting clients with drafting and reviewing standardized contracts and legal documents. However, your primary role is still to provide personalized legal guidance through interactive conversations with clients.
73
-
74
- Please adhere to the following guidelines:
75
-
76
- 1. Clarify the question:
77
-
78
- - Ask questions to clarify the user's specific situation and needs to provide the most relevant and targeted advice.
79
- - However, if the user has already provided sufficient background information, avoid excessively pressing for details. Focus on understanding the core of the issue, rather than unnecessary minutiae.
80
-
81
- 2. Gather information:
82
 
83
- - Identify the key information needed to answer the question and proactively ask the user for these details.
84
- - When gathering information, be sure to identify which details are directly relevant to the legal analysis of the case. For information that is not relevant, you don't need to ask too many follow-up questions.
85
- - If the user indicates that they have provided all relevant information, accept this and do not continue to demand more details.
86
-
87
- 3. Multi-perspective analysis:
88
-
89
- - Evaluate legal issues from different viewpoints, considering various possible interpretations and applications.
90
- - Present arguments supporting and opposing specific perspectives to comprehensively clarify complex issues.
91
- - In your analysis, strive to balance comprehensiveness and conciseness. Provide thorough analysis, but also ensure that the user can easily understand and absorb the information.
92
-
93
- 4. Explain reasoning:
94
-
95
- - Explain the main legal principles, regulations, and case law you consider when analyzing the issue.
96
- - Clarify how you apply legal knowledge to the user's specific situation and the logic behind your conclusions.
97
- - When explaining your reasoning, use clear and concise language, avoiding excessive length or repetition.
98
-
99
- 5. Interactive dialogue:
100
-
101
- - Encourage the user to participate in the discussion, ask follow-up questions, and share their thoughts and concerns.
102
- - Dynamically adjust your analysis and recommendations based on new information obtained in the conversation.
103
- - In your interactions, be attentive to the user's needs and concerns. If they express satisfaction or indicate that they don't require more information, respect their wishes.
104
-
105
- 6. Professional advice:
106
-
107
- - Provide clear, actionable legal advice, but also emphasize the necessity of consulting a professional lawyer before making a final decision.
108
- - If clients wish to speak with a lawyer, you can introduce our team (WealthWizards), which consists of lawyers with different specializations and orientations.
109
- - When providing advice, use language that is easy to understand and communicate with a tone of empathy and care. Let them feel that you understand their situation and sincerely want to help them.
110
-
111
- 7. Assistance with standardized contracts and legal documents:
112
-
113
- - When clients request assistance with drafting or reviewing standardized contracts and legal documents, provide guidance and support to the best of your abilities.
114
- - Analyze the client's needs and requirements, and offer suggestions on appropriate contract templates or clauses to include.
115
- - Review drafted documents for potential legal issues or areas that may need improvement, and provide constructive feedback.
116
- - However, always remind clients that while you can assist with drafting and review, final documents should still be reviewed and approved by a licensed attorney.
117
-
118
- Please remember that your role is to provide general legal information and analysis, but also to actively guide and interact with the user during the conversation in a personalized and professional manner. If you feel that necessary information is missing to provide targeted analysis and advice, take the initiative to ask until you believe you have sufficient details. However, also be mindful to avoid over-inquiring or disregarding the user's needs and concerns.
119
-
120
- When assisting with standardized contracts and documents, aim to provide value-added services while still maintaining the importance of attorney review. Your contract assistance should be a supplement to, not a replacement for, the interactive legal guidance that is your primary function.
121
-
122
- Now, please guide me step by step to describe the legal issues I am facing, according to the above requirements.
123
- '''
124
-
125
- @spaces.GPU(duration=120)
126
- def chat_llama3_8b(message: str,
127
- history: list,
128
- temperature=0.6,
129
- max_new_tokens=4096
130
- ) -> str:
131
- """
132
- Generate a streaming response using the llama3-8b model.
133
- Args:
134
- message (str): The input message.
135
- history (list): The conversation history used by ChatInterface.
136
- temperature (float): The temperature for generating the response.
137
- max_new_tokens (int): The maximum number of new tokens to generate.
138
- Returns:
139
- str: The generated response.
140
- """
141
- conversation = []
142
- for user, assistant in history:
143
- # content = background_prompt + user
144
- conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
145
- message = message + background_prompt
146
- conversation.append({"role": "user", "content": message})
147
-
148
- input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt").to(model.device)
149
-
150
- streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
151
-
152
- generate_kwargs = dict(
153
- input_ids= input_ids,
154
- streamer=streamer,
155
- max_new_tokens=max_new_tokens,
156
- do_sample=True,
157
- temperature=temperature,
158
- eos_token_id=terminators,
159
- )
160
- # This will enforce greedy generation (do_sample=False) when the temperature is passed 0, avoiding the crash.
161
- if temperature == 0:
162
- generate_kwargs['do_sample'] = False
163
-
164
- t = Thread(target=model.generate, kwargs=generate_kwargs)
165
- t.start()
166
-
167
- outputs = []
168
- for text in streamer:
169
- outputs.append(text)
170
- #print(outputs)
171
- yield "".join(outputs)
172
-
173
-
174
- # Gradio block
175
- chatbot=gr.Chatbot(height=600, placeholder=PLACEHOLDER, label='Gradio ChatInterface')
176
-
177
- with gr.Blocks(fill_height=True, css=css) as demo:
178
-
179
  gr.Markdown(DESCRIPTION)
 
180
  gr.ChatInterface(
181
- fn=chat_llama3_8b,
182
- chatbot=chatbot,
183
  fill_height=True,
184
  examples=[
185
  ['What are the key differences between a sole proprietorship and a partnership?'],
@@ -189,9 +231,9 @@ with gr.Blocks(fill_height=True, css=css) as demo:
189
  ['How can I protect my intellectual property when sharing my idea with potential investors?']
190
  ],
191
  cache_examples=False,
192
- )
193
 
194
  gr.Markdown(LICENSE)
195
-
196
  if __name__ == "__main__":
197
  demo.launch()
 
1
  import gradio as gr
2
  import os
3
  import spaces
 
4
  from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
5
  from threading import Thread
6
+ from langchain_community.vectorstores.faiss import FAISS
7
+ from langchain_huggingface import HuggingFaceEmbeddings
8
 
9
+ class RAGChatbot:
10
+ def __init__(self):
11
+ self.init_models()
12
+ self.init_vector_store()
13
+
14
+ self.background_prompt = '''
15
+ As an AI legal assistant, you are a highly trained expert in U.S. and Canadian law. Your purpose is to provide accurate, comprehensive, and professional legal information to assist users with a wide range of legal questions. When answering questions, you should actively ask questions to obtain more information, analyze from different perspectives, and explain your reasoning process to the user.
16
+
17
+ In addition to providing general legal advice and analysis, you are also capable of assisting clients with drafting and reviewing standardized contracts and legal documents. However, your primary role is still to provide personalized legal guidance through interactive conversations with clients.
18
+
19
+ Please adhere to the following guidelines:
20
+
21
+ 1. Clarify the question:
22
+
23
+ - Ask questions to clarify the user's specific situation and needs to provide the most relevant and targeted advice.
24
+ - However, if the user has already provided sufficient background information, avoid excessively pressing for details. Focus on understanding the core of the issue, rather than unnecessary minutiae.
25
+
26
+ 2. Gather information:
27
+
28
+ - Identify the key information needed to answer the question and proactively ask the user for these details.
29
+ - When gathering information, be sure to identify which details are directly relevant to the legal analysis of the case. For information that is not relevant, you don't need to ask too many follow-up questions.
30
+ - If the user indicates that they have provided all relevant information, accept this and do not continue to demand more details.
31
+
32
+ 3. Multi-perspective analysis:
33
+
34
+ - Evaluate legal issues from different viewpoints, considering various possible interpretations and applications.
35
+ - Present arguments supporting and opposing specific perspectives to comprehensively clarify complex issues.
36
+ - In your analysis, strive to balance comprehensiveness and conciseness. Provide thorough analysis, but also ensure that the user can easily understand and absorb the information.
37
+
38
+ 4. Explain reasoning:
39
+
40
+ - Explain the main legal principles, regulations, and case law you consider when analyzing the issue.
41
+ - Clarify how you apply legal knowledge to the user's specific situation and the logic behind your conclusions.
42
+ - When explaining your reasoning, use clear and concise language, avoiding excessive length or repetition.
43
+
44
+ 5. Interactive dialogue:
45
+
46
+ - Encourage the user to participate in the discussion, ask follow-up questions, and share their thoughts and concerns.
47
+ - Dynamically adjust your analysis and recommendations based on new information obtained in the conversation.
48
+ - In your interactions, be attentive to the user's needs and concerns. If they express satisfaction or indicate that they don't require more information, respect their wishes.
49
 
50
+ 6. Professional advice:
51
 
52
+ - Provide clear, actionable legal advice, but also emphasize the necessity of consulting a professional lawyer before making a final decision.
53
+ - If clients wish to speak with a lawyer, you can introduce our team (WealthWizards), which consists of lawyers with different specializations and orientations.
54
+ - When providing advice, use language that is easy to understand and communicate with a tone of empathy and care. Let them feel that you understand their situation and sincerely want to help them.
55
 
56
+ 7. Assistance with standardized contracts and legal documents:
 
57
 
58
+ - When clients request assistance with drafting or reviewing standardized contracts and legal documents, provide guidance and support to the best of your abilities.
59
+ - Analyze the client's needs and requirements, and offer suggestions on appropriate contract templates or clauses to include.
60
+ - Review drafted documents for potential legal issues or areas that may need improvement, and provide constructive feedback.
61
+ - However, always remind clients that while you can assist with drafting and review, final documents should still be reviewed and approved by a licensed attorney.
62
 
63
+ Please remember that your role is to provide general legal information and analysis, but also to actively guide and interact with the user during the conversation in a personalized and professional manner. If you feel that necessary information is missing to provide targeted analysis and advice, take the initiative to ask until you believe you have sufficient details. However, also be mindful to avoid over-inquiring or disregarding the user's needs and concerns.
64
 
65
+ When assisting with standardized contracts and documents, aim to provide value-added services while still maintaining the importance of attorney review. Your contract assistance should be a supplement to, not a replacement for, the interactive legal guidance that is your primary function.
66
 
67
+ Now, please guide me step by step to describe the legal issues I am facing, according to the above requirements.
68
+ '''
69
+
70
+ @spaces.GPU
71
+ def init_models(self):
72
+ """Initialize the LLM and embedding models"""
73
+ # LLM initialization
74
+ self.llm_model_name = 'StevenChen16/llama3-8b-Lawyer'
75
+ self.tokenizer = AutoTokenizer.from_pretrained(self.llm_model_name)
76
+ self.model = AutoModelForCausalLM.from_pretrained(
77
+ self.llm_model_name,
78
+ device_map="auto"
79
+ )
80
+ self.terminators = [
81
+ self.tokenizer.eos_token_id,
82
+ self.tokenizer.convert_tokens_to_ids("<|eot_id|>")
83
+ ]
84
+
85
+ # Embedding model initialization
86
+ self.embeddings = HuggingFaceEmbeddings(
87
+ model_name='intfloat/multilingual-e5-large-instruct',
88
+ model_kwargs={'trust_remote_code': True}
89
+ )
90
+
91
+ def init_vector_store(self):
92
+ """Load vector store from HuggingFace Hub"""
93
+ try:
94
+ self.vector_store = FAISS.from_huggingface_hub(
95
+ repo_id="StevenChen16/laws.faiss",
96
+ embeddings=self.embeddings,
97
+ allow_dangerous_deserialization=True
98
+ )
99
+ except Exception as e:
100
+ raise RuntimeError(f"Failed to load vector store from HuggingFace Hub: {str(e)}")
101
+
102
+ def get_relevant_context(self, query, k=4):
103
+ """Retrieve relevant context from vector store"""
104
+ retriever = self.vector_store.as_retriever(
105
+ search_type="similarity_score_threshold",
106
+ search_kwargs={
107
+ "score_threshold": 0.7,
108
+ "k": k
109
+ }
110
+ )
111
+ docs = retriever.invoke(query)
112
+ return "\n".join(doc.page_content for doc in docs)
113
+
114
+ @spaces.GPU(duration=120)
115
+ def generate_response(self, message, history, temperature=0.6, max_new_tokens=4096):
116
+ """Generate streaming response with RAG context"""
117
+ # Get relevant context
118
+ context = self.get_relevant_context(message)
119
+
120
+ # Build conversation history
121
+ conversation = []
122
+ for user, assistant in history:
123
+ conversation.extend([
124
+ {"role": "user", "content": user},
125
+ {"role": "assistant", "content": assistant}
126
+ ])
127
+
128
+ # Add context and background prompt to message
129
+ if context:
130
+ enhanced_message = f"""Based on the following legal context:
131
+ {context}
132
+
133
+ {self.background_prompt}
134
+
135
+ User question: {message}"""
136
+ else:
137
+ enhanced_message = message + self.background_prompt
138
+
139
+ conversation.append({"role": "user", "content": enhanced_message})
140
+
141
+ # Generate response
142
+ input_ids = self.tokenizer.apply_chat_template(
143
+ conversation,
144
+ return_tensors="pt"
145
+ ).to(self.model.device)
146
+
147
+ streamer = TextIteratorStreamer(
148
+ self.tokenizer,
149
+ timeout=10.0,
150
+ skip_prompt=True,
151
+ skip_special_tokens=True
152
+ )
153
+
154
+ generate_kwargs = dict(
155
+ input_ids=input_ids,
156
+ streamer=streamer,
157
+ max_new_tokens=max_new_tokens,
158
+ do_sample=True,
159
+ temperature=temperature,
160
+ eos_token_id=self.terminators,
161
+ )
162
+
163
+ if temperature == 0:
164
+ generate_kwargs['do_sample'] = False
165
+
166
+ t = Thread(target=self.model.generate, kwargs=generate_kwargs)
167
+ t.start()
168
+
169
+ outputs = []
170
+ for text in streamer:
171
+ outputs.append(text)
172
+ yield "".join(outputs)
173
+
174
+ # Gradio interface constants
175
  DESCRIPTION = '''
176
  <div style="display: flex; align-items: center; justify-content: center; text-align: center;">
177
  <a href="https://wealthwizards.org/" target="_blank">
 
199
  </div>
200
  """
201
 
 
202
  css = """
203
  h1 {
204
  text-align: center;
 
212
  }
213
  """
214
 
215
+ # Initialize chatbot
216
+ chatbot = RAGChatbot()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
 
218
+ # Gradio interface
219
+ with gr.Blocks(css=css) as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  gr.Markdown(DESCRIPTION)
221
+
222
  gr.ChatInterface(
223
+ fn=chatbot.generate_response,
224
+ chatbot=gr.Chatbot(height=600, placeholder=PLACEHOLDER, label='AI Legal Assistant'),
225
  fill_height=True,
226
  examples=[
227
  ['What are the key differences between a sole proprietorship and a partnership?'],
 
231
  ['How can I protect my intellectual property when sharing my idea with potential investors?']
232
  ],
233
  cache_examples=False,
234
+ )
235
 
236
  gr.Markdown(LICENSE)
237
+
238
  if __name__ == "__main__":
239
  demo.launch()