-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbase.py
381 lines (335 loc) · 14.3 KB
/
base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import arxiv
import ast
import concurrent
from csv import writer
import json
import openai
import os
import pandas as pd
from PyPDF2 import PdfReader
import requests
from scipy import spatial
from tenacity import retry, wait_random_exponential, stop_after_attempt
import tiktoken
from tqdm import tqdm
from termcolor import colored
import markdown
import webbrowser
GPT_MODEL = "gpt-3.5-turbo-16k"
EMBEDDING_MODEL = "text-embedding-ada-002"
openai.api_key = '$key'
directory = './data/papers'
# Check if the directory already exists
if not os.path.exists(directory):
# If the directory doesn't exist, create it and any necessary intermediate directories
os.makedirs(directory)
print(f"Directory '{directory}' created successfully.")
else:
# If the directory already exists, print a message indicating it
print(f"Directory '{directory}' already exists.")
# Set a directory to store downloaded papers
data_dir = os.path.join(os.curdir, "data", "papers")
paper_dir_filepath = "./data/arxiv_library.csv"
# Generate a blank dataframe where we can store downloaded files
df = pd.DataFrame(list())
df.to_csv(paper_dir_filepath)
@retry(wait=wait_random_exponential(min=1, max=40), stop=stop_after_attempt(3))
def embedding_request(text):
response = openai.Embedding.create(input=text, model=EMBEDDING_MODEL)
return response
def get_articles(query, library=paper_dir_filepath, top_k=5):
"""This function gets the top_k articles based on a user's query, sorted by relevance.
It also downloads the files and stores them in arxiv_library.csv to be retrieved by the read_article_and_summarize.
"""
search = arxiv.Search(
query=query, max_results=top_k, sort_by=arxiv.SortCriterion.Relevance
)
result_list = []
for result in search.results():
result_dict = {}
result_dict.update({"title": result.title})
result_dict.update({"summary": result.summary})
# Taking the first url provided
result_dict.update({"article_url": [x.href for x in result.links][0]})
result_dict.update({"pdf_url": [x.href for x in result.links][1]})
result_list.append(result_dict)
# Store references in library file
response = embedding_request(text=result.title)
file_reference = [
result.title,
result.download_pdf(data_dir),
response["data"][0]["embedding"],
]
# Write to file
with open(library, "a") as f_object:
writer_object = writer(f_object)
writer_object.writerow(file_reference)
f_object.close()
return result_list
def strings_ranked_by_relatedness(
query: str,
df: pd.DataFrame,
relatedness_fn=lambda x, y: 1 - spatial.distance.cosine(x, y),
top_n: int = 100,
) -> list[str]:
"""Returns a list of strings and relatednesses, sorted from most related to least."""
query_embedding_response = embedding_request(query)
query_embedding = query_embedding_response["data"][0]["embedding"]
strings_and_relatednesses = [
(row["filepath"], relatedness_fn(query_embedding, row["embedding"]))
for i, row in df.iterrows()
]
strings_and_relatednesses.sort(key=lambda x: x[1], reverse=True)
strings, relatednesses = zip(*strings_and_relatednesses)
return strings[:top_n]
def read_pdf(filepath):
"""Takes a filepath to a PDF and returns a string of the PDF's contents"""
# creating a pdf reader object
reader = PdfReader(filepath)
pdf_text = ""
page_number = 0
for page in reader.pages:
page_number += 1
pdf_text += page.extract_text() + f"\nPage Number: {page_number}"
return pdf_text
# Split a text into smaller chunks of size n, preferably ending at the end of a sentence
def create_chunks(text, n, tokenizer):
"""Returns successive n-sized chunks from provided text."""
tokens = tokenizer.encode(text)
i = 0
while i < len(tokens):
# Find the nearest end of sentence within a range of 0.5 * n and 1.5 * n tokens
j = min(i + int(1.5 * n), len(tokens))
while j > i + int(0.5 * n):
# Decode the tokens and check for full stop or newline
chunk = tokenizer.decode(tokens[i:j])
if chunk.endswith(".") or chunk.endswith("\n"):
break
j -= 1
# If no end of sentence found, use n tokens as the chunk size
if j == i + int(0.5 * n):
j = min(i + n, len(tokens))
yield tokens[i:j]
i = j
def extract_chunk(content, template_prompt):
"""This function applies a prompt to some input content. In this case it returns a summarized chunk of text"""
prompt = template_prompt + content
response = openai.ChatCompletion.create(
model=GPT_MODEL, messages=[{"role": "user", "content": prompt}], temperature=0
)
return response["choices"][0]["message"]["content"]
def summarize_text(query):
"""This function does the following:
- Reads in the arxiv_library.csv file in including the embeddings
- Finds the closest file to the user's query
- Scrapes the text out of the file and chunks it
- Summarizes each chunk in parallel
- Does one final summary and returns this to the user"""
# A prompt to dictate how the recursive summarizations should approach the input paper
summary_prompt = """Summarize this text from an academic paper. Extract any key points with reasoning.
You must include the authors and the paper's name at the top.\n\nPaper Name:\nAuthors:\nContent:"""
# If the library is empty (no searches have been performed yet), we perform one and download the results
library_df = pd.read_csv(paper_dir_filepath).reset_index()
if len(library_df) == 0:
print("No papers searched yet, downloading first.")
get_articles(query)
print("Papers downloaded, continuing")
library_df = pd.read_csv(paper_dir_filepath).reset_index()
library_df.columns = ["title", "filepath", "embedding"]
library_df["embedding"] = library_df["embedding"].apply(ast.literal_eval)
strings = strings_ranked_by_relatedness(query, library_df, top_n=1)
print("Chunking text from paper")
pdf_text = read_pdf(strings[0])
# Initialise tokenizer
tokenizer = tiktoken.get_encoding("cl100k_base")
results = ""
# Chunk up the document into 1500 token chunks
chunks = create_chunks(pdf_text, 1500, tokenizer)
text_chunks = [tokenizer.decode(chunk) for chunk in chunks]
print("Summarizing each chunk of text")
# Parallel process the summaries
with concurrent.futures.ThreadPoolExecutor(
max_workers=len(text_chunks)
) as executor:
futures = [
executor.submit(extract_chunk, chunk, summary_prompt)
for chunk in text_chunks
]
with tqdm(total=len(text_chunks)) as pbar:
for _ in concurrent.futures.as_completed(futures):
pbar.update(1)
for future in futures:
data = future.result()
results += data
# Final summary
print("Summarizing into overall summary")
response = openai.ChatCompletion.create(
model=GPT_MODEL,
messages=[
{
"role": "user",
"content": f"""Write a summary collated from this collection of key points extracted from an academic paper.
The summary should highlight the core argument, conclusions and evidence, and answer the user's query.
You must include the authors and the paper's name at the top.
User query: {query}
The summary should be structured in bulleted lists following the headings Core Argument, Evidence, and Conclusions.
Key points:\n{results}\n\nPaper Name:\nAuthors:\nSummary:\n""",
}
],
temperature=0,
)
return response
@retry(wait=wait_random_exponential(min=1, max=40), stop=stop_after_attempt(3))
def chat_completion_request(messages, functions=None, model=GPT_MODEL):
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer " + openai.api_key,
}
json_data = {"model": model, "messages": messages}
if functions is not None:
json_data.update({"functions": functions})
try:
response = requests.post(
"https://api.openai.com/v1/chat/completions",
headers=headers,
json=json_data,
)
return response
except Exception as e:
print("Unable to generate ChatCompletion response")
print(f"Exception: {e}")
return e
class Conversation:
def __init__(self):
self.conversation_history = []
def add_message(self, role, content):
message = {"role": role, "content": content}
self.conversation_history.append(message)
def display_conversation(self, detailed=False):
role_to_color = {
"system": "red",
"user": "green",
"assistant": "blue",
"function": "magenta",
}
for message in self.conversation_history:
print(
colored(
f"{message['role']}: {message['content']}\n\n",
role_to_color[message["role"]],
)
)
# Initiate our get_articles and read_article_and_summarize functions
arxiv_functions = [
{
"name": "get_articles",
"description": """Use this function to get academic papers from arXiv to answer user questions.""",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": f"""
User query in JSON. Responses should be summarized and should include the article URL reference
""",
}
},
"required": ["query"],
},
"name": "read_article_and_summarize",
"description": """Use this function to read whole papers and provide a summary for users.
You should NEVER call this function before get_articles has been called in the conversation.""",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": f"""
Description of the article in plain text based on the user's query
""",
}
},
"required": ["query"],
},
}
]
def call_arxiv_function(messages, full_message):
"""Function calling function which executes function calls when the model believes it is necessary.
Currently extended by adding clauses to this if statement."""
print("Using function: ", full_message["message"]["function_call"]["name"])
if full_message["message"]["function_call"]["name"] == "get_articles" or full_message["message"]["function_call"]["name"] == "arxiv.get_articles":
try:
parsed_output = json.loads(
full_message["message"]["function_call"]["arguments"]
)
print("Getting search results")
results = get_articles(parsed_output["query"])
except Exception as e:
print(parsed_output)
print(f"Function execution failed")
print(f"Error message: {e}")
messages.append(
{
"role": "function",
"name": full_message["message"]["function_call"]["name"],
"content": str(results),
}
)
try:
print("Got search results, summarizing content")
response = chat_completion_request(messages)
return response.json()
except Exception as e:
print(type(e))
raise Exception("Function chat request failed")
elif (
full_message["message"]["function_call"]["name"] == "read_article_and_summarize"
):
parsed_output = json.loads(
full_message["message"]["function_call"]["arguments"]
)
print("Finding and reading paper")
summary = summarize_text(parsed_output["query"])
return summary
else:
raise Exception("Function does not exist and cannot be called")
def chat_completion_with_function_execution(messages, functions=[None]):
"""This function makes a ChatCompletion API call with the option of adding functions"""
response = chat_completion_request(messages, functions)
full_message = response.json()["choices"][0]
if full_message["finish_reason"] == "function_call":
print(f"Function generation requested, calling function")
return call_arxiv_function(messages, full_message)
else:
print(f"Function not required, responding to user")
return response.json()
# Start with a system message
paper_system_message = """You are arXivGPT, a helpful assistant pulls academic papers to answer user questions.
You summarize the papers clearly so the customer can decide which to read to answer their question.
You always provide the article_url and title so the user can understand the name of the paper and click through to access it.
Begin!"""
paper_conversation = Conversation()
paper_conversation.add_message("system", paper_system_message)
# Add a user message
paper_conversation.add_message("user", "What are recent papers on the use of llms in the construction industry?")
chat_response = chat_completion_with_function_execution(
paper_conversation.conversation_history, functions=arxiv_functions
)
assistant_message = chat_response["choices"][0]["message"]["content"]
paper_conversation.add_message("assistant", assistant_message)
html = markdown.markdown(assistant_message)
with open('temp.html', 'w') as f:
f.write(html)
# Add another user message to induce our system to use the second tool
paper_conversation.add_message(
"user",
"Read the most related paper to the subject discussed and give me a summary",
)
updated_response = chat_completion_with_function_execution(
paper_conversation.conversation_history, functions=arxiv_functions
)
html = markdown.markdown(updated_response["choices"][0]["message"]["content"])
with open('temp.html', 'a') as f:
f.write(html)
# Show conversation using a browser
webbrowser.open('file://' + os.path.realpath('temp.html'))