Spaces:
Runtime error
Runtime error
Create main.py
Browse files
main.py
ADDED
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json # to work with JSON
|
2 |
+
import threading # to allow streaming response
|
3 |
+
import time # to pave the deliver of the message
|
4 |
+
|
5 |
+
import faiss # to create a search index
|
6 |
+
import gradio # for the interface
|
7 |
+
import numpy # to work with vectors
|
8 |
+
import pandas # to work with pandas
|
9 |
+
import sentence_transformers # to load an embedding model
|
10 |
+
import spaces # for GPU
|
11 |
+
import transformers # to load an LLM
|
12 |
+
|
13 |
+
# Constants
|
14 |
+
GREETING = (
|
15 |
+
"Howdy! I'm an AI agent that uses a [retrieval-augmented generation]("
|
16 |
+
"https://en.wikipedia.org/wiki/Retrieval-augmented_generation) pipeline to answer questions about published at [ASME IDETC](https://asmedigitalcollection.asme.org/IDETC-CIE). And the best part is that I always cite my sources! What"
|
17 |
+
" can I tell you about today?"
|
18 |
+
)
|
19 |
+
EXAMPLE_QUERIES = [
|
20 |
+
"What's the difference between a markov chain and a hidden markov model?",
|
21 |
+
]
|
22 |
+
EMBEDDING_MODEL_NAME = "allenai-specter"
|
23 |
+
LLM_MODEL_NAME = "Qwen/Qwen2-7B-Instruct"
|
24 |
+
|
25 |
+
# Load the dataset and convert to pandas
|
26 |
+
data = pd.read_parquet("hf://datasets/ccm/rag-idetc/data/train-00000-of-00001.parquet")
|
27 |
+
|
28 |
+
# Filter out any publications without an abstract
|
29 |
+
abstract_is_null = [
|
30 |
+
'"abstract": null' in json.dumps(bibdict) for bibdict in data["bib_dict"].values
|
31 |
+
]
|
32 |
+
data = data[~pandas.Series(abstract_is_null)]
|
33 |
+
data.reset_index(inplace=True)
|
34 |
+
|
35 |
+
# Load the model for later use in embeddings
|
36 |
+
model = sentence_transformers.SentenceTransformer(EMBEDDING_MODEL_NAME)
|
37 |
+
|
38 |
+
# Create an LLM pipeline that we can send queries to
|
39 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(LLM_MODEL_NAME)
|
40 |
+
streamer = transformers.TextIteratorStreamer(
|
41 |
+
tokenizer, skip_prompt=True, skip_special_tokens=True
|
42 |
+
)
|
43 |
+
chatmodel = transformers.AutoModelForCausalLM.from_pretrained(
|
44 |
+
LLM_MODEL_NAME, torch_dtype="auto", device_map="auto"
|
45 |
+
)
|
46 |
+
|
47 |
+
# Create a FAISS index for fast similarity search
|
48 |
+
metric = faiss.METRIC_INNER_PRODUCT
|
49 |
+
vectors = numpy.stack(data["embedding"].tolist(), axis=0)
|
50 |
+
index = faiss.IndexFlatL2(len(data["embedding"][0]))
|
51 |
+
index.metric_type = metric
|
52 |
+
faiss.normalize_L2(vectors)
|
53 |
+
index.train(vectors)
|
54 |
+
index.add(vectors)
|
55 |
+
|
56 |
+
|
57 |
+
def preprocess(query: str, k: int) -> tuple[str, str]:
|
58 |
+
"""
|
59 |
+
Searches the dataset for the top k most relevant papers to the query and returns a prompt and references
|
60 |
+
Args:
|
61 |
+
query (str): The user's query
|
62 |
+
k (int): The number of results to return
|
63 |
+
Returns:
|
64 |
+
tuple[str, str]: A tuple containing the prompt and references
|
65 |
+
"""
|
66 |
+
encoded_query = numpy.expand_dims(model.encode(query), axis=0)
|
67 |
+
print(query, encoded_query)
|
68 |
+
faiss.normalize_L2(encoded_query)
|
69 |
+
D, I = index.search(encoded_query, k)
|
70 |
+
top_five = data.loc[I[0]]
|
71 |
+
|
72 |
+
prompt = (
|
73 |
+
"You are an AI assistant who delights in helping people learn about research from the IDETC Conference. Your main task is to provide an ANSWER to the USER_QUERY based on the RESEARCH_ABSTRACTS.\n\n"
|
74 |
+
"RESEARCH_ABSTRACTS:\n{{ABSTRACTS_GO_HERE}}\n\n"
|
75 |
+
"USER_GUERY:\n{{QUERY_GOES_HERE}}\n\n"
|
76 |
+
"ANSWER:\n"
|
77 |
+
)
|
78 |
+
|
79 |
+
references = "\n\n## References\n\n"
|
80 |
+
research_abstracts = ""
|
81 |
+
|
82 |
+
for i in range(k):
|
83 |
+
title = str(int(top_five["title"].values[i])
|
84 |
+
id = str(int(top_five["id"].values[i])
|
85 |
+
url = "https://doi.org/10.1115/" + id
|
86 |
+
path = str(int(top_five["path"].values[i])
|
87 |
+
text = str(int(top_five["text"].values[i])
|
88 |
+
|
89 |
+
research_abstracts += str(i + i) + ". This excerpt from is from: '" + title + "':\n" + text + "\n"
|
90 |
+
references += (
|
91 |
+
str(i + 1)
|
92 |
+
+ ". ["
|
93 |
+
+ title
|
94 |
+
+ "]"
|
95 |
+
+ url
|
96 |
+
+ ").\n"
|
97 |
+
)
|
98 |
+
|
99 |
+
prompt = prompt.replace("{{ABSTRACTS_GO_HERE}}", research_abstracts)
|
100 |
+
prompt = prompt.replace("{{QUERY_GOES_HERE}}", query)
|
101 |
+
|
102 |
+
return prompt, references
|
103 |
+
|
104 |
+
def postprocess(response: str, bypass_from_preprocessing: str) -> str:
|
105 |
+
"""
|
106 |
+
Applies a postprocessing step to the LLM's response before the user receives it
|
107 |
+
Args:
|
108 |
+
response (str): The LLM's response
|
109 |
+
bypass_from_preprocessing (str): The bypass variable from the preprocessing step
|
110 |
+
Returns:
|
111 |
+
str: The postprocessed response
|
112 |
+
"""
|
113 |
+
return response + bypass_from_preprocessing
|
114 |
+
|
115 |
+
|
116 |
+
@spaces.GPU
|
117 |
+
def reply(message: str, history: list[str]) -> str:
|
118 |
+
"""
|
119 |
+
This function is responsible for crafting a response
|
120 |
+
Args:
|
121 |
+
message (str): The user's message
|
122 |
+
history (list[str]): The conversation history
|
123 |
+
Returns:
|
124 |
+
str: The AI's response
|
125 |
+
"""
|
126 |
+
|
127 |
+
# Apply preprocessing
|
128 |
+
message, bypass = preprocess(message, 5)
|
129 |
+
|
130 |
+
# This is some handling that is applied to the history variable to put it in a good format
|
131 |
+
history_transformer_format = [
|
132 |
+
{"role": role, "content": message_pair[idx]}
|
133 |
+
for message_pair in history
|
134 |
+
for idx, role in enumerate(["user", "assistant"])
|
135 |
+
if message_pair[idx] is not None
|
136 |
+
] + [{"role": "user", "content": message}]
|
137 |
+
|
138 |
+
# Stream a response from pipe
|
139 |
+
text = tokenizer.apply_chat_template(
|
140 |
+
history_transformer_format, tokenize=False, add_generation_prompt=True
|
141 |
+
)
|
142 |
+
model_inputs = tokenizer([text], return_tensors="pt").to("cuda:0")
|
143 |
+
|
144 |
+
generate_kwargs = dict(model_inputs, streamer=streamer, max_new_tokens=512)
|
145 |
+
t = threading.Thread(target=chatmodel.generate, kwargs=generate_kwargs)
|
146 |
+
t.start()
|
147 |
+
|
148 |
+
partial_message = ""
|
149 |
+
for new_token in streamer:
|
150 |
+
if new_token != "<":
|
151 |
+
partial_message += new_token
|
152 |
+
time.sleep(0.05)
|
153 |
+
yield partial_message
|
154 |
+
|
155 |
+
yield partial_message + bypass
|
156 |
+
|
157 |
+
|
158 |
+
# Create and run the gradio interface
|
159 |
+
gradio.ChatInterface(
|
160 |
+
reply,
|
161 |
+
examples=EXAMPLE_QUERIES,
|
162 |
+
chatbot=gradio.Chatbot(
|
163 |
+
show_label=False,
|
164 |
+
show_share_button=False,
|
165 |
+
show_copy_button=False,
|
166 |
+
value=[[None, GREETING]],
|
167 |
+
height="60vh",
|
168 |
+
bubble_full_width=False,
|
169 |
+
),
|
170 |
+
retry_btn=None,
|
171 |
+
undo_btn=None,
|
172 |
+
clear_btn=None,
|
173 |
+
).launch(debug=True)
|
174 |
+
|
175 |
+
|