Spaces:
Sleeping
Sleeping
Create main.py
Browse files
main.py
ADDED
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import threading # to allow streaming response
|
2 |
+
import time # to pave the deliver of the message
|
3 |
+
|
4 |
+
import gradio # for the interface
|
5 |
+
import spaces # for GPU
|
6 |
+
import transformers # to load an LLM
|
7 |
+
import langchain_community.vectorstores # to load the publication vectorstore
|
8 |
+
import langchain_huggingface # for embeddings
|
9 |
+
|
10 |
+
# The greeting message
|
11 |
+
GREETING = (
|
12 |
+
"Howdy! "
|
13 |
+
"I'm an AI agent that uses [retrieval-augmented generation](https://en.wikipedia.org/wiki/Retrieval-augmented_generation) pipeline to answer questions about additive manufacturing research. "
|
14 |
+
"I still make some mistakes though. "
|
15 |
+
"What can I tell you about today?"
|
16 |
+
)
|
17 |
+
|
18 |
+
# Example queries
|
19 |
+
EXAMPLE_QUERIES = [
|
20 |
+
"Tell me about new research at the intersection of additive manufacturing and machine learning.",
|
21 |
+
]
|
22 |
+
|
23 |
+
# The embedding model name
|
24 |
+
EMBEDDING_MODEL_NAME = "all-MiniLM-L12-v2"
|
25 |
+
|
26 |
+
# The LLM model name
|
27 |
+
LLM_MODEL_NAME = "Qwen/Qwen2.5-1.5B-Instruct"
|
28 |
+
|
29 |
+
# The number of publications to retrieve
|
30 |
+
PUBLICATIONS_TO_RETRIEVE = 5
|
31 |
+
|
32 |
+
|
33 |
+
def embedding(
|
34 |
+
model_name: str = "all-MiniLM-L12-v2",
|
35 |
+
device: str = "mps",
|
36 |
+
normalize_embeddings: bool = False,
|
37 |
+
) -> langchain_huggingface.HuggingFaceEmbeddings:
|
38 |
+
"""
|
39 |
+
Get the embedding function
|
40 |
+
:param model_name: The model name
|
41 |
+
:type model_name: str
|
42 |
+
:param device: The device to use
|
43 |
+
:type device: str
|
44 |
+
:param normalize_embeddings: Whether to normalize embeddings
|
45 |
+
:type normalize_embeddings: bool
|
46 |
+
|
47 |
+
:return: The embedding function
|
48 |
+
:rtype: langchain_huggingface.HuggingFaceEmbeddings
|
49 |
+
"""
|
50 |
+
return langchain_huggingface.HuggingFaceEmbeddings(
|
51 |
+
model_name=model_name,
|
52 |
+
model_kwargs={"device": device},
|
53 |
+
encode_kwargs={"normalize_embeddings": normalize_embeddings},
|
54 |
+
)
|
55 |
+
|
56 |
+
|
57 |
+
def load_publication_vectorstore() -> langchain_community.vectorstores.FAISS:
|
58 |
+
"""
|
59 |
+
Load the publication vectorstore
|
60 |
+
:return: The publication vectorstore
|
61 |
+
:rtype: langchain_community.vectorstores.FAISS
|
62 |
+
"""
|
63 |
+
return langchain_community.vectorstores.FAISS.load_local(
|
64 |
+
folder_path="publication_vectorstore",
|
65 |
+
embeddings=embedding(),
|
66 |
+
allow_dangerous_deserialization=True,
|
67 |
+
)
|
68 |
+
|
69 |
+
|
70 |
+
publication_vectorstore = load_publication_vectorstore()
|
71 |
+
|
72 |
+
# Create an LLM pipeline that we can send queries to
|
73 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(
|
74 |
+
LLM_MODEL_NAME, trust_remote_code=True
|
75 |
+
)
|
76 |
+
streamer = transformers.TextIteratorStreamer(
|
77 |
+
tokenizer, skip_prompt=True, skip_special_tokens=True
|
78 |
+
)
|
79 |
+
chatmodel = transformers.AutoModelForCausalLM.from_pretrained(
|
80 |
+
LLM_MODEL_NAME, device_map="auto", torch_dtype="auto", trust_remote_code=True
|
81 |
+
)
|
82 |
+
|
83 |
+
|
84 |
+
def preprocess(query: str, k: int) -> tuple[str, str]:
|
85 |
+
"""
|
86 |
+
Searches the dataset for the top k most relevant papers to the query and returns a prompt and references
|
87 |
+
Args:
|
88 |
+
query (str): The user's query
|
89 |
+
k (int): The number of results to return
|
90 |
+
Returns:
|
91 |
+
tuple[str, str]: A tuple containing the prompt and references
|
92 |
+
"""
|
93 |
+
documents = publication_vectorstore.search(
|
94 |
+
query, k=PUBLICATIONS_TO_RETRIEVE, search_type="similarity"
|
95 |
+
)
|
96 |
+
|
97 |
+
prompt = (
|
98 |
+
"You are an AI assistant who delights in helping people learn about research from the Design Research Collective, which is a research lab at Carnegie Mellon University led by Professor Chris McComb. "
|
99 |
+
"Your main task is to provide a concise ANSWER to the USER_QUERY that includes as many of the RESEARCH_ABSTRACTS as possible. "
|
100 |
+
"The RESEARCH_ABSTRACTS are provided in the `.bibtex` format. Your ANSWER should contain citations to the RESEARCH_ABSTRACTS using (AUTHOR, YEAR) format. "
|
101 |
+
"DO NOT list references at the end of the answer.\n\n"
|
102 |
+
"===== RESEARCH_EXCERPTS =====:\n{{EXCERPTS_GO_HERE}}\n\n"
|
103 |
+
"===== USER_QUERY =====:\n{{QUERY_GOES_HERE}}\n\n"
|
104 |
+
"===== ANSWER =====:\n"
|
105 |
+
)
|
106 |
+
|
107 |
+
research_excerpts = [
|
108 |
+
'"... ' + document.page_content + '..."' for document in documents
|
109 |
+
]
|
110 |
+
|
111 |
+
prompt = prompt.replace("{{EXCERPTS_GO_HERE}}", "\n\n".join(research_excerpts))
|
112 |
+
prompt = prompt.replace("{{QUERY_GOES_HERE}}", query)
|
113 |
+
|
114 |
+
print(prompt)
|
115 |
+
|
116 |
+
return prompt, ""
|
117 |
+
|
118 |
+
|
119 |
+
@spaces.GPU
|
120 |
+
def reply(message: str, history: list[str]) -> str:
|
121 |
+
"""
|
122 |
+
This function is responsible for crafting a response
|
123 |
+
Args:
|
124 |
+
message (str): The user's message
|
125 |
+
history (list[str]): The conversation history
|
126 |
+
Returns:
|
127 |
+
str: The AI's response
|
128 |
+
"""
|
129 |
+
|
130 |
+
# Apply preprocessing
|
131 |
+
message, bypass = preprocess(message, PUBLICATIONS_TO_RETRIEVE)
|
132 |
+
|
133 |
+
# This is some handling that is applied to the history variable to put it in a good format
|
134 |
+
history_transformer_format = [
|
135 |
+
{"role": role, "content": message_pair[idx]}
|
136 |
+
for message_pair in history
|
137 |
+
for idx, role in enumerate(["user", "assistant"])
|
138 |
+
if message_pair[idx] is not None
|
139 |
+
] + [{"role": "user", "content": message}]
|
140 |
+
|
141 |
+
# Stream a response from pipe
|
142 |
+
text = tokenizer.apply_chat_template(
|
143 |
+
history_transformer_format, tokenize=False, add_generation_prompt=True
|
144 |
+
)
|
145 |
+
model_inputs = tokenizer([text], return_tensors="pt").to("cuda:0")
|
146 |
+
|
147 |
+
generate_kwargs = dict(model_inputs, streamer=streamer, max_new_tokens=512)
|
148 |
+
t = threading.Thread(target=chatmodel.generate, kwargs=generate_kwargs)
|
149 |
+
t.start()
|
150 |
+
|
151 |
+
partial_message = ""
|
152 |
+
for new_token in streamer:
|
153 |
+
if new_token != "<":
|
154 |
+
partial_message += new_token
|
155 |
+
time.sleep(0.01)
|
156 |
+
yield partial_message
|
157 |
+
|
158 |
+
yield partial_message + "\n\n" + bypass
|
159 |
+
|
160 |
+
|
161 |
+
# Create and run the gradio interface
|
162 |
+
gradio.ChatInterface(
|
163 |
+
reply,
|
164 |
+
examples=EXAMPLE_QUERIES,
|
165 |
+
chatbot=gradio.Chatbot(
|
166 |
+
show_label=False,
|
167 |
+
show_share_button=False,
|
168 |
+
show_copy_button=False,
|
169 |
+
value=[[None, GREETING]],
|
170 |
+
avatar_images=(
|
171 |
+
"https://cdn.dribbble.com/users/316121/screenshots/2333676/11-04_scotty-plaid_dribbble.png",
|
172 |
+
"https://media.thetab.com/blogs.dir/90/files/2021/06/screenshot-2021-06-10-at-110730-1024x537.png",
|
173 |
+
),
|
174 |
+
height="60vh",
|
175 |
+
bubble_full_width=False,
|
176 |
+
),
|
177 |
+
retry_btn=None,
|
178 |
+
undo_btn=None,
|
179 |
+
clear_btn=None,
|
180 |
+
theme=gradio.themes.Default(font=[gradio.themes.GoogleFont("Zilla Slab")]),
|
181 |
+
).launch(debug=True)
|