Spaces:
Runtime error
Runtime error
ahmed-7124
commited on
Create app
Browse files
app
ADDED
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import os
|
3 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
4 |
+
from transformers import TextIteratorStreamer
|
5 |
+
from accelerate import init_empty_weights, load_checkpoint_and_dispatch
|
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 |
+
MODEL_NAME_OR_PATH = 'StevenChen16/llama3-8b-Lawyer'
|
15 |
+
|
16 |
+
DESCRIPTION = '''
|
17 |
+
<div style="display: flex; align-items: center; justify-content: center; text-align: center;">
|
18 |
+
<a href="https://wealthwizards.org/" target="_blank">
|
19 |
+
<img src="./images/logo.png" alt="Wealth Wizards Logo" style="width: 60px; height: auto; margin-right: 10px;">
|
20 |
+
</a>
|
21 |
+
<div style="display: inline-block; text-align: left;">
|
22 |
+
<h1 style="font-size: 36px; margin: 0;">AI Lawyer</h1>
|
23 |
+
<a href="https://wealthwizards.org/" target="_blank" style="text-decoration: none; color: inherit;">
|
24 |
+
<p style="font-size: 16px; margin: 0;">wealth wizards</p>
|
25 |
+
</a>
|
26 |
+
</div>
|
27 |
+
</div>
|
28 |
+
'''
|
29 |
+
|
30 |
+
LICENSE = """
|
31 |
+
<p/>
|
32 |
+
---
|
33 |
+
Built with model "StevenChen16/Llama3-8B-Lawyer", based on "meta-llama/Meta-Llama-3-8B"
|
34 |
+
"""
|
35 |
+
|
36 |
+
PLACEHOLDER = """
|
37 |
+
<div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
|
38 |
+
<h1 style="font-size: 28px; margin-bottom: 2px; opacity: 0.55;">AI Lawyer</h1>
|
39 |
+
<p style="font-size: 18px; margin-bottom: 2px; opacity: 0.65;">Ask me anything about US and Canada law...</p>
|
40 |
+
</div>
|
41 |
+
"""
|
42 |
+
|
43 |
+
css = """
|
44 |
+
h1 {
|
45 |
+
text-align: center;
|
46 |
+
display: block;
|
47 |
+
}
|
48 |
+
#duplicate-button {
|
49 |
+
margin: auto;
|
50 |
+
color: white;
|
51 |
+
background: #1565c0;
|
52 |
+
border-radius: 100vh;
|
53 |
+
}
|
54 |
+
"""
|
55 |
+
|
56 |
+
# Load the tokenizer
|
57 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME_OR_PATH)
|
58 |
+
|
59 |
+
# Load the model with disk offloading
|
60 |
+
print("Loading the model with disk offloading...")
|
61 |
+
model = AutoModelForCausalLM.from_pretrained(
|
62 |
+
MODEL_NAME_OR_PATH,
|
63 |
+
trust_remote_code=True,
|
64 |
+
low_cpu_mem_usage=True # Optimize memory usage during loading
|
65 |
+
)
|
66 |
+
|
67 |
+
# Specify an offload folder and map the model to disk and available GPUs
|
68 |
+
device_map = infer_auto_device_map(model, max_memory={"cpu": "50GB", "cuda:0": "16GB"})
|
69 |
+
dispatch_model(
|
70 |
+
model,
|
71 |
+
device_map=device_map,
|
72 |
+
offload_folder="./offload" # Folder for offloaded weights
|
73 |
+
)
|
74 |
+
|
75 |
+
terminators = [
|
76 |
+
tokenizer.eos_token_id,
|
77 |
+
tokenizer.convert_tokens_to_ids("<|eot_id|>")
|
78 |
+
]
|
79 |
+
|
80 |
+
# Embedding model and FAISS vector store
|
81 |
+
def create_embedding_model(model_name):
|
82 |
+
return HuggingFaceEmbeddings(
|
83 |
+
model_name=model_name,
|
84 |
+
model_kwargs={'trust_remote_code': True}
|
85 |
+
)
|
86 |
+
|
87 |
+
embedding_model = create_embedding_model('intfloat/multilingual-e5-large-instruct')
|
88 |
+
|
89 |
+
try:
|
90 |
+
print("Downloading vector store from HuggingFace Hub...")
|
91 |
+
repo_path = snapshot_download(
|
92 |
+
repo_id="StevenChen16/laws.faiss",
|
93 |
+
repo_type="model"
|
94 |
+
)
|
95 |
+
print("Loading vector store...")
|
96 |
+
vector_store = FAISS.load_local(
|
97 |
+
folder_path=repo_path,
|
98 |
+
embeddings=embedding_model,
|
99 |
+
allow_dangerous_deserialization=True
|
100 |
+
)
|
101 |
+
print("Vector store loaded successfully")
|
102 |
+
except Exception as e:
|
103 |
+
raise RuntimeError(f"Failed to load vector store from HuggingFace Hub: {str(e)}")
|
104 |
+
|
105 |
+
background_prompt = '''
|
106 |
+
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...
|
107 |
+
[Shortened for brevity]
|
108 |
+
'''
|
109 |
+
|
110 |
+
def query_vector_store(vector_store: FAISS, query, k=4, relevance_threshold=0.8):
|
111 |
+
"""
|
112 |
+
Query similar documents from vector store.
|
113 |
+
"""
|
114 |
+
retriever = vector_store.as_retriever(
|
115 |
+
search_type="similarity_score_threshold",
|
116 |
+
search_kwargs={"score_threshold": relevance_threshold, "k": k}
|
117 |
+
)
|
118 |
+
similar_docs = retriever.invoke(query)
|
119 |
+
context = [doc.page_content for doc in similar_docs]
|
120 |
+
return " ".join(context) if context else ""
|
121 |
+
|
122 |
+
def chat_llama3_8b(message: str, history: list, temperature=0.6, max_new_tokens=4096) -> str:
|
123 |
+
"""
|
124 |
+
Generate a streaming response using the LLaMA model.
|
125 |
+
"""
|
126 |
+
citation = query_vector_store(vector_store, message, k=4, relevance_threshold=0.7)
|
127 |
+
|
128 |
+
conversation = []
|
129 |
+
for user, assistant in history:
|
130 |
+
conversation.extend([
|
131 |
+
{"role": "user", "content": str(user)},
|
132 |
+
{"role": "assistant", "content": str(assistant)}
|
133 |
+
])
|
134 |
+
|
135 |
+
final_message = f"{background_prompt}\n{message}" if not citation else f"{background_prompt}\nBased on these references:\n{citation}\nPlease answer: {message}"
|
136 |
+
conversation.append({"role": "user", "content": final_message})
|
137 |
+
|
138 |
+
input_ids = tokenizer.apply_chat_template(
|
139 |
+
conversation,
|
140 |
+
return_tensors="pt"
|
141 |
+
).to(model.device)
|
142 |
+
|
143 |
+
streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
|
144 |
+
|
145 |
+
generation_config = {
|
146 |
+
"input_ids": input_ids,
|
147 |
+
"streamer": streamer,
|
148 |
+
"max_new_tokens": max_new_tokens,
|
149 |
+
"do_sample": temperature > 0,
|
150 |
+
"temperature": temperature,
|
151 |
+
"eos_token_id": terminators
|
152 |
+
}
|
153 |
+
|
154 |
+
thread = Thread(target=model.generate, kwargs=generation_config)
|
155 |
+
thread.start()
|
156 |
+
|
157 |
+
accumulated_text = []
|
158 |
+
for text_chunk in streamer:
|
159 |
+
accumulated_text.append(text_chunk)
|
160 |
+
yield "".join(accumulated_text)
|
161 |
+
|
162 |
+
# Gradio interface
|
163 |
+
chatbot = gr.Chatbot(height=600, placeholder=PLACEHOLDER, label='Gradio ChatInterface')
|
164 |
+
|
165 |
+
with gr.Blocks(fill_height=True, css=css) as demo:
|
166 |
+
gr.Markdown(DESCRIPTION)
|
167 |
+
gr.ChatInterface(
|
168 |
+
fn=chat_llama3_8b,
|
169 |
+
chatbot=chatbot,
|
170 |
+
fill_height=True,
|
171 |
+
examples=[
|
172 |
+
['What are the key differences between a sole proprietorship and a partnership?'],
|
173 |
+
['What legal steps should I take if I want to start a business in the US?'],
|
174 |
+
['Can you explain the concept of "duty of care" in negligence law?'],
|
175 |
+
['What are the legal requirements for obtaining a patent in Canada?'],
|
176 |
+
['How can I protect my intellectual property when sharing my idea with potential investors?']
|
177 |
+
],
|
178 |
+
cache_examples=False,
|
179 |
+
)
|
180 |
+
gr.Markdown(LICENSE)
|
181 |
+
|
182 |
+
if __name__ == "__main__":
|
183 |
+
demo.launch()
|