Spaces:
Runtime error
Runtime error
Upload 6 files
Browse files- README.md +14 -0
- app (1).py +288 -0
- avatar.png +0 -0
- gitattributes +35 -0
- requirements (1).txt +15 -0
- setup.sh +15 -0
README.md
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: Llama3 8b Lawyer
|
3 |
+
emoji: 🐨
|
4 |
+
colorFrom: yellow
|
5 |
+
colorTo: yellow
|
6 |
+
sdk: gradio
|
7 |
+
sdk_version: 4.31.5
|
8 |
+
app_file: app.py
|
9 |
+
pinned: false
|
10 |
+
license: mit
|
11 |
+
short_description: AI Lawyer
|
12 |
+
---
|
13 |
+
|
14 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app (1).py
ADDED
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from langchain_community.vectorstores.faiss import FAISS
|
8 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
9 |
+
from huggingface_hub import snapshot_download
|
10 |
+
|
11 |
+
# Set an environment variable
|
12 |
+
HF_TOKEN = os.environ.get("HF_TOKEN", None)
|
13 |
+
|
14 |
+
|
15 |
+
|
16 |
+
MODEL_NAME_OR_PATH = 'StevenChen16/llama3-8b-Lawyer'
|
17 |
+
# MODEL_NAME_OR_PATH = 'nvidia/Llama3-ChatQA-1.5-8B'
|
18 |
+
|
19 |
+
|
20 |
+
|
21 |
+
|
22 |
+
DESCRIPTION = '''
|
23 |
+
<div style="display: flex; align-items: center; justify-content: center; text-align: center;">
|
24 |
+
<a href="https://wealthwizards.org/" target="_blank">
|
25 |
+
<img src="./images/logo.png" alt="Wealth Wizards Logo" style="width: 60px; height: auto; margin-right: 10px;">
|
26 |
+
</a>
|
27 |
+
<div style="display: inline-block; text-align: left;">
|
28 |
+
<h1 style="font-size: 36px; margin: 0;">AI Lawyer</h1>
|
29 |
+
<a href="https://wealthwizards.org/" target="_blank" style="text-decoration: none; color: inherit;">
|
30 |
+
<p style="font-size: 16px; margin: 0;">wealth wizards</p>
|
31 |
+
</a>
|
32 |
+
</div>
|
33 |
+
</div>
|
34 |
+
'''
|
35 |
+
|
36 |
+
LICENSE = """
|
37 |
+
<p/>
|
38 |
+
---
|
39 |
+
Built with model "StevenChen16/Llama3-8B-Lawyer", based on "meta-llama/Meta-Llama-3-8B"
|
40 |
+
"""
|
41 |
+
|
42 |
+
PLACEHOLDER = """
|
43 |
+
<div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
|
44 |
+
<h1 style="font-size: 28px; margin-bottom: 2px; opacity: 0.55;">AI Lawyer</h1>
|
45 |
+
<p style="font-size: 18px; margin-bottom: 2px; opacity: 0.65;">Ask me anything about US and Canada law...</p>
|
46 |
+
</div>
|
47 |
+
"""
|
48 |
+
|
49 |
+
|
50 |
+
css = """
|
51 |
+
h1 {
|
52 |
+
text-align: center;
|
53 |
+
display: block;
|
54 |
+
}
|
55 |
+
#duplicate-button {
|
56 |
+
margin: auto;
|
57 |
+
color: white;
|
58 |
+
background: #1565c0;
|
59 |
+
border-radius: 100vh;
|
60 |
+
}
|
61 |
+
"""
|
62 |
+
|
63 |
+
# Load the tokenizer and model
|
64 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME_OR_PATH)
|
65 |
+
model = AutoModelForCausalLM.from_pretrained(MODEL_NAME_OR_PATH, device_map="auto") # to("cuda:0")
|
66 |
+
terminators = [
|
67 |
+
tokenizer.eos_token_id,
|
68 |
+
tokenizer.convert_tokens_to_ids("<|eot_id|>")
|
69 |
+
]
|
70 |
+
|
71 |
+
def create_embedding_model(model_name):
|
72 |
+
"""Create embedding model instance"""
|
73 |
+
return HuggingFaceEmbeddings(
|
74 |
+
model_name=model_name,
|
75 |
+
model_kwargs={'trust_remote_code': True}
|
76 |
+
)
|
77 |
+
embedding_model = create_embedding_model('intfloat/multilingual-e5-large-instruct')
|
78 |
+
try:
|
79 |
+
print("Downloading vector store from HuggingFace Hub...")
|
80 |
+
# Download FAISS files from HuggingFace Hub
|
81 |
+
repo_path = snapshot_download(
|
82 |
+
repo_id="StevenChen16/laws.faiss",
|
83 |
+
repo_type="model"
|
84 |
+
)
|
85 |
+
|
86 |
+
print("Loading vector store...")
|
87 |
+
# Load the vector store from downloaded files
|
88 |
+
vector_store = FAISS.load_local(
|
89 |
+
folder_path=repo_path,
|
90 |
+
embeddings=embedding_model,
|
91 |
+
allow_dangerous_deserialization=True
|
92 |
+
)
|
93 |
+
print("Vector store loaded successfully")
|
94 |
+
|
95 |
+
except Exception as e:
|
96 |
+
raise RuntimeError(f"Failed to load vector store from HuggingFace Hub: {str(e)}")
|
97 |
+
|
98 |
+
|
99 |
+
background_prompt = '''
|
100 |
+
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.
|
101 |
+
|
102 |
+
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.
|
103 |
+
|
104 |
+
Please adhere to the following guidelines:
|
105 |
+
|
106 |
+
1. Clarify the question:
|
107 |
+
|
108 |
+
- Ask questions to clarify the user's specific situation and needs to provide the most relevant and targeted advice.
|
109 |
+
- 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.
|
110 |
+
|
111 |
+
2. Gather information:
|
112 |
+
|
113 |
+
- Identify the key information needed to answer the question and proactively ask the user for these details.
|
114 |
+
- 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.
|
115 |
+
- If the user indicates that they have provided all relevant information, accept this and do not continue to demand more details.
|
116 |
+
|
117 |
+
3. Multi-perspective analysis:
|
118 |
+
|
119 |
+
- Evaluate legal issues from different viewpoints, considering various possible interpretations and applications.
|
120 |
+
- Present arguments supporting and opposing specific perspectives to comprehensively clarify complex issues.
|
121 |
+
- 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.
|
122 |
+
|
123 |
+
4. Explain reasoning:
|
124 |
+
|
125 |
+
- Explain the main legal principles, regulations, and case law you consider when analyzing the issue.
|
126 |
+
- Clarify how you apply legal knowledge to the user's specific situation and the logic behind your conclusions.
|
127 |
+
- When explaining your reasoning, use clear and concise language, avoiding excessive length or repetition.
|
128 |
+
|
129 |
+
5. Interactive dialogue:
|
130 |
+
|
131 |
+
- Encourage the user to participate in the discussion, ask follow-up questions, and share their thoughts and concerns.
|
132 |
+
- Dynamically adjust your analysis and recommendations based on new information obtained in the conversation.
|
133 |
+
- 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.
|
134 |
+
|
135 |
+
6. Professional advice:
|
136 |
+
|
137 |
+
- Provide clear, actionable legal advice, but also emphasize the necessity of consulting a professional lawyer before making a final decision.
|
138 |
+
- If clients wish to speak with a lawyer, you can introduce our team (WealthWizards), which consists of lawyers with different specializations and orientations.
|
139 |
+
- 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.
|
140 |
+
|
141 |
+
7. Assistance with standardized contracts and legal documents:
|
142 |
+
|
143 |
+
- When clients request assistance with drafting or reviewing standardized contracts and legal documents, provide guidance and support to the best of your abilities.
|
144 |
+
- Analyze the client's needs and requirements, and offer suggestions on appropriate contract templates or clauses to include.
|
145 |
+
- Review drafted documents for potential legal issues or areas that may need improvement, and provide constructive feedback.
|
146 |
+
- 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.
|
147 |
+
|
148 |
+
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.
|
149 |
+
|
150 |
+
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.
|
151 |
+
|
152 |
+
Now, please guide me step by step to describe the legal issues I am facing, according to the above requirements.
|
153 |
+
'''
|
154 |
+
|
155 |
+
def query_vector_store(vector_store: FAISS, query, k=4, relevance_threshold=0.8):
|
156 |
+
"""
|
157 |
+
Query similar documents from vector store.
|
158 |
+
"""
|
159 |
+
retriever = vector_store.as_retriever(search_type="similarity_score_threshold",
|
160 |
+
search_kwargs={"score_threshold": relevance_threshold, "k": k})
|
161 |
+
similar_docs = retriever.invoke(query)
|
162 |
+
context = [doc.page_content for doc in similar_docs]
|
163 |
+
# Join the context list into a single string
|
164 |
+
return " ".join(context) if context else ""
|
165 |
+
|
166 |
+
@spaces.GPU(duration=120)
|
167 |
+
def chat_llama3_8b(message: str,
|
168 |
+
history: list,
|
169 |
+
temperature=0.6,
|
170 |
+
max_new_tokens=4096
|
171 |
+
) -> str:
|
172 |
+
"""
|
173 |
+
Generate a streaming response using the LLaMA model.
|
174 |
+
|
175 |
+
Args:
|
176 |
+
message (str): The current user message
|
177 |
+
history (list): List of previous conversation turns
|
178 |
+
temperature (float): Sampling temperature (0.0 to 1.0)
|
179 |
+
max_new_tokens (int): Maximum number of tokens to generate
|
180 |
+
|
181 |
+
Returns:
|
182 |
+
str: Generated response with citations if available
|
183 |
+
"""
|
184 |
+
# try:
|
185 |
+
# 1. Get relevant citations from vector store
|
186 |
+
citation = query_vector_store(vector_store, message, k=4, relevance_threshold=0.7)
|
187 |
+
|
188 |
+
# 2. Format conversation history
|
189 |
+
conversation = []
|
190 |
+
for user, assistant in history:
|
191 |
+
conversation.extend([
|
192 |
+
{"role": "user", "content": str(user)},
|
193 |
+
{"role": "assistant", "content": str(assistant)}
|
194 |
+
])
|
195 |
+
|
196 |
+
# 3. Construct the final prompt
|
197 |
+
final_message = ""
|
198 |
+
if citation:
|
199 |
+
final_message = f"{background_prompt}\nBased on these references:\n{citation}\nPlease answer: {message}"
|
200 |
+
else:
|
201 |
+
final_message = f"{background_prompt}\n{message}"
|
202 |
+
|
203 |
+
conversation.append({"role": "user", "content": final_message})
|
204 |
+
|
205 |
+
# 4. Prepare model inputs
|
206 |
+
input_ids = tokenizer.apply_chat_template(
|
207 |
+
conversation,
|
208 |
+
return_tensors="pt"
|
209 |
+
).to(model.device)
|
210 |
+
|
211 |
+
# 5. Setup streamer
|
212 |
+
streamer = TextIteratorStreamer(
|
213 |
+
tokenizer,
|
214 |
+
timeout=10.0,
|
215 |
+
skip_prompt=True,
|
216 |
+
skip_special_tokens=True
|
217 |
+
)
|
218 |
+
|
219 |
+
# 6. Configure generation parameters
|
220 |
+
generation_config = {
|
221 |
+
"input_ids": input_ids,
|
222 |
+
"streamer": streamer,
|
223 |
+
"max_new_tokens": max_new_tokens,
|
224 |
+
"do_sample": temperature > 0,
|
225 |
+
"temperature": temperature,
|
226 |
+
"eos_token_id": terminators
|
227 |
+
}
|
228 |
+
|
229 |
+
# 7. Generate in a separate thread
|
230 |
+
thread = Thread(target=model.generate, kwargs=generation_config)
|
231 |
+
thread.start()
|
232 |
+
|
233 |
+
# 8. Stream the output
|
234 |
+
accumulated_text = []
|
235 |
+
final_chunk = False
|
236 |
+
|
237 |
+
for text_chunk in streamer:
|
238 |
+
accumulated_text.append(text_chunk)
|
239 |
+
current_response = "".join(accumulated_text)
|
240 |
+
|
241 |
+
# Check if this is the last chunk
|
242 |
+
try:
|
243 |
+
next_chunk = next(iter(streamer))
|
244 |
+
accumulated_text.append(next_chunk)
|
245 |
+
except (StopIteration, RuntimeError):
|
246 |
+
final_chunk = True
|
247 |
+
|
248 |
+
# Add citations on the final chunk if they exist
|
249 |
+
if final_chunk and citation:
|
250 |
+
formatted_citations = "\n\nReferences:\n" + "\n".join(
|
251 |
+
f"[{i+1}] {cite.strip()}"
|
252 |
+
for i, cite in enumerate(citation.split('\n'))
|
253 |
+
if cite.strip()
|
254 |
+
)
|
255 |
+
current_response += formatted_citations
|
256 |
+
|
257 |
+
yield current_response
|
258 |
+
|
259 |
+
# except Exception as e:
|
260 |
+
# error_message = f"An error occurred: {str(e)}"
|
261 |
+
# print(error_message) # For logging
|
262 |
+
# yield error_message
|
263 |
+
|
264 |
+
|
265 |
+
# Gradio block
|
266 |
+
chatbot=gr.Chatbot(height=600, placeholder=PLACEHOLDER, label='Gradio ChatInterface')
|
267 |
+
|
268 |
+
with gr.Blocks(fill_height=True, css=css) as demo:
|
269 |
+
|
270 |
+
gr.Markdown(DESCRIPTION)
|
271 |
+
gr.ChatInterface(
|
272 |
+
fn=chat_llama3_8b,
|
273 |
+
chatbot=chatbot,
|
274 |
+
fill_height=True,
|
275 |
+
examples=[
|
276 |
+
['What are the key differences between a sole proprietorship and a partnership?'],
|
277 |
+
['What legal steps should I take if I want to start a business in the US?'],
|
278 |
+
['Can you explain the concept of "duty of care" in negligence law?'],
|
279 |
+
['What are the legal requirements for obtaining a patent in Canada?'],
|
280 |
+
['How can I protect my intellectual property when sharing my idea with potential investors?']
|
281 |
+
],
|
282 |
+
cache_examples=False,
|
283 |
+
)
|
284 |
+
|
285 |
+
gr.Markdown(LICENSE)
|
286 |
+
|
287 |
+
if __name__ == "__main__":
|
288 |
+
demo.launch()
|
avatar.png
ADDED
gitattributes
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
requirements (1).txt
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#flask
|
2 |
+
#flask-cors
|
3 |
+
#git+https://github.com/hiyouga/LLaMA-Factory.git
|
4 |
+
#git+https://github.com/unslothai/unsloth.git
|
5 |
+
#bitsandbytes==0.43.1
|
6 |
+
#torch==2.0.1
|
7 |
+
#transformers==4.37.2
|
8 |
+
#openai
|
9 |
+
accelerate
|
10 |
+
transformers
|
11 |
+
SentencePiece
|
12 |
+
langchain-community
|
13 |
+
langchain-huggingface
|
14 |
+
einops
|
15 |
+
faiss-cpu
|
setup.sh
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
|
3 |
+
# # Clone and install LLaMA-Factory
|
4 |
+
# git clone https://github.com/hiyouga/LLaMA-Factory.git
|
5 |
+
# cd LLaMA-Factory
|
6 |
+
# pip install .[torch,bitsandbytes] --quiet
|
7 |
+
|
8 |
+
# # Install unsloth
|
9 |
+
# pip install git+https://github.com/unslothai/unsloth.git --quiet
|
10 |
+
|
11 |
+
# # Return to the root directory
|
12 |
+
# cd ..
|
13 |
+
|
14 |
+
# Run the application with gunicorn
|
15 |
+
gunicorn --bind 0.0.0.0:5000 app:app
|