Spaces:
Runtime error
Runtime error
jharrison27
commited on
Commit
•
3dbe475
1
Parent(s):
3701fee
Upload 2 files
Browse files
app.py
CHANGED
@@ -2,165 +2,139 @@ import torch
|
|
2 |
import transformers
|
3 |
import gradio as gr
|
4 |
from ragatouille import RAGPretrainedModel
|
5 |
-
from huggingface_hub import InferenceClient
|
6 |
import re
|
7 |
from datetime import datetime
|
8 |
import json
|
9 |
-
|
10 |
import arxiv
|
11 |
-
from helper import *
|
12 |
-
|
13 |
-
retrieve_results = 20
|
14 |
-
show_examples = True
|
15 |
-
llm_models_to_choose = ['mistralai/Mixtral-8x7B-Instruct-v0.1','mistralai/Mistral-7B-Instruct-v0.2', 'google/gemma-7b-it', 'None']
|
16 |
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
|
24 |
-
|
25 |
RAG = RAGPretrainedModel.from_index("colbert/indexes/arxiv_colbert")
|
26 |
|
27 |
try:
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
gr.Warning("Retriever not working!")
|
34 |
|
35 |
-
|
36 |
mark_text = '# 🩺🔍 Search Results\n'
|
37 |
header_text = "## Arxiv Paper Summary With QA Retrieval Augmented Generation \n"
|
38 |
|
39 |
try:
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
except:
|
49 |
-
|
50 |
-
|
51 |
-
database_choices = [index_info,'Arxiv Search - Latest - (EXPERIMENTAL)']
|
52 |
-
|
53 |
-
|
54 |
arx_client = arxiv.Client()
|
55 |
is_arxiv_available = True
|
56 |
-
check_arxiv_result = get_arxiv_live_search("What is Self Rewarding AI and how can it be used in Multi-Agent Systems?", arx_client,
|
57 |
if len(check_arxiv_result) == 0:
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
|
63 |
-
|
64 |
-
|
65 |
-
sample_outputs = {
|
66 |
-
'output_placeholder': 'The LLM will provide an answer to your question here...',
|
67 |
-
'search_placeholder': '''
|
68 |
-
1. What is MoE?
|
69 |
-
2. What are Multi Agent Systems?
|
70 |
-
3. What is Self Rewarding AI?
|
71 |
-
4. What is Semantic and Episodic memory?
|
72 |
-
5. What is AutoGen?
|
73 |
-
6. What is ChatDev?
|
74 |
-
7. What is Omniverse?
|
75 |
-
8. What is Lumiere?
|
76 |
-
9. What is SORA?
|
77 |
-
'''
|
78 |
-
}
|
79 |
-
|
80 |
-
output_placeholder = sample_outputs['output_placeholder']
|
81 |
-
md_text_initial = sample_outputs['search_placeholder']
|
82 |
-
|
83 |
-
|
84 |
-
with gr.Blocks(theme = gr.themes.Soft()) as demo:
|
85 |
header = gr.Markdown(header_text)
|
86 |
|
87 |
with gr.Group():
|
88 |
-
|
89 |
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
output_text = gr.Textbox(show_label
|
98 |
-
input = gr.Textbox(show_label
|
99 |
-
gr_md = gr.Markdown(mark_text
|
100 |
-
|
101 |
-
def update_with_rag_md(
|
102 |
prompt_text_from_data = ""
|
103 |
database_to_use = database_choice
|
|
|
104 |
if database_choice == index_info:
|
105 |
-
|
106 |
else:
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
md_text_updated = mark_text
|
122 |
-
for i in
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
prompt = get_prompt_text(
|
131 |
return md_text_updated, prompt
|
132 |
-
|
133 |
-
def ask_llm(prompt, llm_model_picked
|
134 |
-
|
135 |
-
|
136 |
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
msg.submit(update_with_rag_md, [msg, llm_results, database_src, llm_model], [gr_md, input]).success(ask_llm, [input, llm_model, stream_results], output_text)
|
165 |
|
166 |
demo.queue().launch()
|
|
|
2 |
import transformers
|
3 |
import gradio as gr
|
4 |
from ragatouille import RAGPretrainedModel
|
|
|
5 |
import re
|
6 |
from datetime import datetime
|
7 |
import json
|
|
|
8 |
import arxiv
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
+
from helper import rag_cleaner, get_prompt_text, get_references, get_rag, SaveResponseAndRead, get_md_text_abstract, search_cleaner, get_arxiv_live_search
|
11 |
+
|
12 |
+
# Constants
|
13 |
+
RETRIEVE_RESULTS = 20
|
14 |
+
LLM_MODELS = ['mistralai/Mixtral-8x7B-Instruct-v0.1', 'mistralai/Mistral-7B-Instruct-v0.2', 'google/gemma-7b-it', 'None']
|
15 |
+
DEFAULT_LLM_MODEL = 'mistralai/Mistral-7B-Instruct-v0.2'
|
16 |
+
GENERATE_KWARGS = {
|
17 |
+
"temperature": None,
|
18 |
+
"max_new_tokens": 512,
|
19 |
+
"top_p": None,
|
20 |
+
"do_sample": False,
|
21 |
+
}
|
22 |
|
23 |
+
# RAG Model setup
|
24 |
RAG = RAGPretrainedModel.from_index("colbert/indexes/arxiv_colbert")
|
25 |
|
26 |
try:
|
27 |
+
gr.Info("Setting up retriever, please wait...")
|
28 |
+
rag_initial_output = RAG.search("What is Generative AI in Healthcare?", k=1)
|
29 |
+
gr.Info("Retriever working successfully!")
|
30 |
+
except Exception as e:
|
31 |
+
gr.Warning(f"Retriever not working: {str(e)}")
|
|
|
32 |
|
33 |
+
# Header setup
|
34 |
mark_text = '# 🩺🔍 Search Results\n'
|
35 |
header_text = "## Arxiv Paper Summary With QA Retrieval Augmented Generation \n"
|
36 |
|
37 |
try:
|
38 |
+
with open("README.md", "r") as f:
|
39 |
+
mdfile = f.read()
|
40 |
+
date_pattern = r'Index Last Updated : \d{4}-\d{2}-\d{2}'
|
41 |
+
match = re.search(date_pattern, mdfile)
|
42 |
+
date = match.group().split(': ')[1]
|
43 |
+
formatted_date = datetime.strptime(date, '%Y-%m-%d').strftime('%d %b %Y')
|
44 |
+
header_text += f'Index Last Updated: {formatted_date}\n'
|
45 |
+
index_info = f"Semantic Search - up to {formatted_date}"
|
46 |
+
except FileNotFoundError:
|
47 |
+
index_info = "Semantic Search"
|
48 |
+
|
49 |
+
database_choices = [index_info, 'Arxiv Search - Latest - (EXPERIMENTAL)']
|
50 |
+
|
51 |
+
# Arxiv API setup
|
52 |
arx_client = arxiv.Client()
|
53 |
is_arxiv_available = True
|
54 |
+
check_arxiv_result = get_arxiv_live_search("What is Self Rewarding AI and how can it be used in Multi-Agent Systems?", arx_client, RETRIEVE_RESULTS)
|
55 |
if len(check_arxiv_result) == 0:
|
56 |
+
is_arxiv_available = False
|
57 |
+
print("Arxiv search not working, switching to default search ...")
|
58 |
+
database_choices = [index_info]
|
|
|
59 |
|
60 |
+
# Gradio UI setup
|
61 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
header = gr.Markdown(header_text)
|
63 |
|
64 |
with gr.Group():
|
65 |
+
search_query = gr.Textbox(label='Search', placeholder='What is Generative AI in Healthcare?')
|
66 |
|
67 |
+
with gr.Accordion("Advanced Settings", open=False):
|
68 |
+
with gr.Row(equal_height=True):
|
69 |
+
llm_model = gr.Dropdown(choices=LLM_MODELS, value=DEFAULT_LLM_MODEL, label='LLM Model')
|
70 |
+
llm_results = gr.Slider(minimum=4, maximum=10, value=5, step=1, interactive=True, label="Top n results as context")
|
71 |
+
database_src = gr.Dropdown(choices=database_choices, value=index_info, label='Search Source')
|
72 |
+
stream_results = gr.Checkbox(value=True, label="Stream output", visible=False)
|
73 |
+
|
74 |
+
output_text = gr.Textbox(show_label=True, container=True, label='LLM Answer', visible=True)
|
75 |
+
input = gr.Textbox(show_label=False, visible=False)
|
76 |
+
gr_md = gr.Markdown(mark_text)
|
77 |
+
|
78 |
+
def update_with_rag_md(search_query, llm_results_use=5, database_choice=index_info, llm_model_picked=DEFAULT_LLM_MODEL):
|
79 |
prompt_text_from_data = ""
|
80 |
database_to_use = database_choice
|
81 |
+
|
82 |
if database_choice == index_info:
|
83 |
+
rag_out = get_rag(search_query, RAG, RETRIEVE_RESULTS)
|
84 |
else:
|
85 |
+
arxiv_search_success = True
|
86 |
+
try:
|
87 |
+
rag_out = get_arxiv_live_search(search_query, arx_client, RETRIEVE_RESULTS)
|
88 |
+
if len(rag_out) == 0:
|
89 |
+
arxiv_search_success = False
|
90 |
+
except Exception as e:
|
91 |
+
arxiv_search_success = False
|
92 |
+
gr.Warning(f"Arxiv Search not working: {str(e)}, switching to semantic search ...")
|
93 |
+
|
94 |
+
if not arxiv_search_success:
|
95 |
+
rag_out = get_rag(search_query, RAG, RETRIEVE_RESULTS)
|
96 |
+
database_to_use = index_info
|
97 |
+
|
|
|
98 |
md_text_updated = mark_text
|
99 |
+
for i, rag_answer in enumerate(rag_out):
|
100 |
+
if i < llm_results_use:
|
101 |
+
md_text_paper, prompt_text = get_md_text_abstract(rag_answer, source=database_to_use, return_prompt_formatting=True)
|
102 |
+
prompt_text_from_data += f"{i+1}. {prompt_text}"
|
103 |
+
else:
|
104 |
+
md_text_paper = get_md_text_abstract(rag_answer, source=database_to_use)
|
105 |
+
md_text_updated += md_text_paper
|
106 |
+
|
107 |
+
prompt = get_prompt_text(search_query, prompt_text_from_data, llm_model_picked=llm_model_picked)
|
108 |
return md_text_updated, prompt
|
109 |
+
|
110 |
+
def ask_llm(prompt, llm_model_picked=DEFAULT_LLM_MODEL, stream_outputs=False):
|
111 |
+
model_disabled_text = "LLM Model is disabled"
|
112 |
+
output = ""
|
113 |
|
114 |
+
if llm_model_picked == 'None':
|
115 |
+
if stream_outputs:
|
116 |
+
for out in model_disabled_text:
|
117 |
+
output += out
|
118 |
+
yield output
|
119 |
+
else:
|
120 |
+
return model_disabled_text
|
121 |
+
|
122 |
+
client = InferenceClient(llm_model_picked)
|
123 |
+
try:
|
124 |
+
response = client.text_generation(prompt, stream=stream_outputs, details=False, return_full_text=False, **GENERATE_KWARGS)
|
125 |
+
|
126 |
+
if stream_outputs:
|
127 |
+
for token in response:
|
128 |
+
output += token
|
129 |
+
yield SaveResponseAndRead(output)
|
130 |
+
else:
|
131 |
+
output = response
|
132 |
+
except Exception as e:
|
133 |
+
gr.Warning(f"LLM Inference failed: {str(e)}")
|
134 |
+
output = ""
|
135 |
+
|
136 |
+
return output
|
137 |
+
|
138 |
+
search_query.submit(update_with_rag_md, [search_query, llm_results, database_src, llm_model], [gr_md, input]).success(ask_llm, [input, llm_model, stream_results], output_text)
|
|
|
|
|
|
|
139 |
|
140 |
demo.queue().launch()
|
helper.py
CHANGED
@@ -1,3 +1,6 @@
|
|
|
|
|
|
|
|
1 |
import datetime
|
2 |
import string
|
3 |
import nltk
|
@@ -5,11 +8,6 @@ nltk.download('stopwords')
|
|
5 |
from nltk.corpus import stopwords
|
6 |
stop_words = stopwords.words('english')
|
7 |
import arxiv
|
8 |
-
import gradio as gr
|
9 |
-
import re
|
10 |
-
from datetime import datetime
|
11 |
-
import json
|
12 |
-
|
13 |
|
14 |
def rag_cleaner(inp):
|
15 |
rank = inp['rank']
|
@@ -18,28 +16,27 @@ def rag_cleaner(inp):
|
|
18 |
date = inp['document_metadata']['_time']
|
19 |
return f"{rank}. <b> {title} </b> \n Date : {date} \n Abstract: {content}"
|
20 |
|
21 |
-
def get_prompt_text(question, context, formatted
|
|
|
|
|
|
|
22 |
if formatted:
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
elif 'gemma' in llm_model_picked:
|
30 |
-
return f"<bos><start_of_turn>user\n{sys_instruction}" + f" {message}<end_of_turn>\n"
|
31 |
-
|
32 |
return f"Context:\n {context} \n Given the following info, take a deep breath and lets think step by step to answer the question: {question}. Cite the titles of your sources when answering.\n\n"
|
33 |
|
34 |
-
def get_references(question, retriever, k
|
35 |
rag_out = retriever.search(query=question, k=k)
|
36 |
return rag_out
|
37 |
|
38 |
-
def get_rag(message):
|
39 |
-
return get_references(message, RAG)
|
40 |
|
41 |
def SaveResponseAndRead(result):
|
42 |
-
documentHTML5='''
|
43 |
<!DOCTYPE html>
|
44 |
<html>
|
45 |
<head>
|
@@ -56,17 +53,15 @@ def SaveResponseAndRead(result):
|
|
56 |
<h1>🔊 Read It Aloud</h1>
|
57 |
<textarea id="textArea" rows="10" cols="80">
|
58 |
'''
|
59 |
-
documentHTML5
|
60 |
-
documentHTML5
|
61 |
</textarea>
|
62 |
<br>
|
63 |
<button onclick="readAloud()">🔊 Read Aloud</button>
|
64 |
</body>
|
65 |
</html>
|
66 |
'''
|
67 |
-
gr.HTML(documentHTML5)
|
68 |
-
|
69 |
-
|
70 |
|
71 |
|
72 |
def get_md_text_abstract(rag_answer, source = ['Arxiv Search', 'Semantic Search'][1], return_prompt_formatting = False):
|
|
|
1 |
+
import sys
|
2 |
+
import gradio as gr
|
3 |
+
from huggingface_hub import InferenceClient
|
4 |
import datetime
|
5 |
import string
|
6 |
import nltk
|
|
|
8 |
from nltk.corpus import stopwords
|
9 |
stop_words = stopwords.words('english')
|
10 |
import arxiv
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
def rag_cleaner(inp):
|
13 |
rank = inp['rank']
|
|
|
16 |
date = inp['document_metadata']['_time']
|
17 |
return f"{rank}. <b> {title} </b> \n Date : {date} \n Abstract: {content}"
|
18 |
|
19 |
+
def get_prompt_text(question, context, formatted=True, llm_model_picked='mistralai/Mistral-7B-Instruct-v0.2'):
|
20 |
+
sys_instruction = f"Context:\n {context} \n Given the following scientific paper abstracts, take a deep breath and lets think step by step to answer the question. Cite the titles of your sources when answering, do not cite links or dates."
|
21 |
+
message = f"Question: {question}"
|
22 |
+
|
23 |
if formatted:
|
24 |
+
if 'mistralai' in llm_model_picked:
|
25 |
+
return f"<s>[INST] {sys_instruction} {message}[/INST]"
|
26 |
+
elif 'gemma' in llm_model_picked:
|
27 |
+
return f"<bos><start_of_turn>user\n{sys_instruction} {message}<end_of_turn>\n"
|
28 |
+
|
|
|
|
|
|
|
|
|
29 |
return f"Context:\n {context} \n Given the following info, take a deep breath and lets think step by step to answer the question: {question}. Cite the titles of your sources when answering.\n\n"
|
30 |
|
31 |
+
def get_references(question, retriever, k):
|
32 |
rag_out = retriever.search(query=question, k=k)
|
33 |
return rag_out
|
34 |
|
35 |
+
def get_rag(message, RAG, RETRIEVE_RESULTS):
|
36 |
+
return get_references(message, RAG, k=RETRIEVE_RESULTS)
|
37 |
|
38 |
def SaveResponseAndRead(result):
|
39 |
+
documentHTML5 = '''
|
40 |
<!DOCTYPE html>
|
41 |
<html>
|
42 |
<head>
|
|
|
53 |
<h1>🔊 Read It Aloud</h1>
|
54 |
<textarea id="textArea" rows="10" cols="80">
|
55 |
'''
|
56 |
+
documentHTML5 += result
|
57 |
+
documentHTML5 += '''
|
58 |
</textarea>
|
59 |
<br>
|
60 |
<button onclick="readAloud()">🔊 Read Aloud</button>
|
61 |
</body>
|
62 |
</html>
|
63 |
'''
|
64 |
+
return gr.HTML(documentHTML5)
|
|
|
|
|
65 |
|
66 |
|
67 |
def get_md_text_abstract(rag_answer, source = ['Arxiv Search', 'Semantic Search'][1], return_prompt_formatting = False):
|