ProximileAdmin commited on
Commit
d5035f7
·
verified ·
1 Parent(s): 73381ed

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +339 -0
app.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import datetime
3
+ import json
4
+ import gradio as gr
5
+ from openai import OpenAI
6
+ import urllib.request
7
+ import feedparser
8
+ import time
9
+ from typing import Dict, List, Optional
10
+
11
+ ENDPOINT_URL = "https://api.hyperbolic.xyz/v1"
12
+
13
+ OAI_API_KEY = os.getenv('HYPERBOLIC_XYZ_KEY')
14
+
15
+ VERBOSE_SHELL = True
16
+
17
+ todays_date_string = datetime.date.today().strftime("%d %B %Y")
18
+
19
+
20
+ NAME_OF_SERVICE = "arXiv Paper Search"
21
+ DESCRIPTION_OF_SERVICE = (
22
+ "a service that searches and retrieves academic papers from arXiv based on various criteria"
23
+ )
24
+ PAPER_SEARCH_FUNCTION_NAME = "search_arxiv_papers"
25
+
26
+ functions_list = [
27
+ {
28
+ "type": "function",
29
+ "function": {
30
+ "name": PAPER_SEARCH_FUNCTION_NAME,
31
+ "description": DESCRIPTION_OF_SERVICE,
32
+ "parameters": {
33
+ "type": "object",
34
+ "properties": {
35
+ "query": {
36
+ "type": "string", # function names for AI agents should be chosen carefully to avoid confusion
37
+ "description": "Search query (e.g., 'deep learning', 'quantum computing')" # descriptions help the AI agent's LLM backend understand the function
38
+ },
39
+ "max_results": {
40
+ "type": "integer",
41
+ "description": "Maximum number of results to return (default: 5)",
42
+ "optional": True
43
+ },
44
+ "sort_by": {
45
+ "type": "string",
46
+ "description": "Sort criteria (e.g., 'relevance', 'lastUpdatedDate', 'submittedDate')",
47
+ "optional": True
48
+ }
49
+ },
50
+ "required": ["query"]
51
+ }
52
+ }
53
+ }
54
+ ]
55
+
56
+ system_prompt = """Cutting Knowledge Date: December 2023
57
+ Today Date: """ + todays_date_string + """
58
+
59
+ You are a helpful assistant with tool calling capabilities.
60
+
61
+ You can search for academic papers on arXiv. When given a research topic or paper query, you should call the search_arxiv_papers function to find relevant papers.
62
+ If you choose to use one of the following functions, respond with a JSON for a function call with its proper arguments that best answers the given prompt.
63
+
64
+ Your tool request should be in the format {{"name": function name, "parameters": dictionary of argument name and its value}}. Do not use variables. Just a two-key dictionary, starting with the function name, followed by a dictionary of parameters.
65
+
66
+ {{functions}}
67
+
68
+ After receiving the results back from a function (formatted as {{"name": function name, "return": returned data after running function}}) formulate your response to the user. If the information needed is not found in the returned data, either attempt a new function call, or inform the user that you cannot answer based on your available knowledge. The user cannot see the function results. You have to interpret the data and provide a response based on it.
69
+
70
+ If the user request does not necessitate a function call, simply respond to the user's query directly."""
71
+
72
+ def search_arxiv_papers(
73
+ query: str,
74
+ max_results: int = 5,
75
+ sort_by: str = 'relevance'
76
+ ) -> Dict:
77
+ """
78
+ Search for papers on arXiv using their API.
79
+
80
+ Args:
81
+ query: Search query string
82
+ max_results: Maximum number of results to return (default: 5)
83
+ sort_by: Sorting criteria (default: 'relevance')
84
+
85
+ Returns:
86
+ Dictionary containing search results and metadata
87
+ """
88
+ try:
89
+ # Construct the search query
90
+ search_query = f'all:{query}'
91
+
92
+ # Construct the API URL
93
+ base_url = 'http://export.arxiv.org/api/query?'
94
+ params = {
95
+ 'search_query': search_query,
96
+ 'start': 0,
97
+ 'max_results': max_results,
98
+ 'sortBy': sort_by,
99
+ 'sortOrder': 'descending'
100
+ }
101
+ query_string = '&'.join([f'{k}={urllib.parse.quote(str(v))}' for k, v in params.items()])
102
+ url = base_url + query_string
103
+
104
+ # Make the API request
105
+ response = urllib.request.urlopen(url)
106
+ feed = feedparser.parse(response.read().decode('utf-8'))
107
+
108
+ # Process the results
109
+ papers = []
110
+ for entry in feed.entries:
111
+ paper = {
112
+ 'id': entry.id.split('/abs/')[-1],
113
+ 'title': entry.title,
114
+ 'authors': [author.name for author in entry.authors],
115
+ 'summary': entry.summary,
116
+ 'published': entry.published,
117
+ 'link': entry.link,
118
+ 'primary_category': entry.tags[0]['term']
119
+ }
120
+ papers.append(paper)
121
+
122
+ # Add a delay to respect API rate limits
123
+ time.sleep(3)
124
+
125
+ return {
126
+ 'status': 'success',
127
+ 'total_results': len(papers),
128
+ 'papers': papers
129
+ }
130
+
131
+ except Exception as e:
132
+ return {
133
+ 'status': 'error',
134
+ 'message': str(e)
135
+ }
136
+
137
+ functions_dict = {f["function"]["name"]: f for f in functions_list}
138
+ FUNCTION_BACKENDS = {
139
+ #WALLET_CHECK_FUNCTION_NAME: check_wallet_balance,
140
+ PAPER_SEARCH_FUNCTION_NAME: search_arxiv_papers,
141
+ }
142
+
143
+ EOT_STRING = "<|eot_id|>"
144
+ FUNCTION_EOT_STRING = "<|eom_id|>"
145
+ ROLE_HEADER = "<|start_header_id|>{role}<|end_header_id|>"
146
+
147
+ class LLM:
148
+ def __init__(self, max_model_len: int = 4096):
149
+ self.api_key = OAI_API_KEY
150
+ self.max_model_len = max_model_len
151
+ self.client = OpenAI(base_url=ENDPOINT_URL, api_key=self.api_key)
152
+ #models_list = self.client.models.list()
153
+ #self.model_name = models_list.data[0].id
154
+ self.model_name = "meta-llama/Llama-3.3-70B-Instruct"
155
+
156
+ def generate(self, prompt: str, sampling_params: dict) -> dict:
157
+ completion_params = {
158
+ "model": self.model_name,
159
+ "prompt": prompt,
160
+ "max_tokens": sampling_params.get("max_tokens", 2048),
161
+ "temperature": sampling_params.get("temperature", 0.8),
162
+ "top_p": sampling_params.get("top_p", 0.95),
163
+ "n": sampling_params.get("n", 1),
164
+ "stream": False,
165
+ }
166
+
167
+ if "stop" in sampling_params:
168
+ completion_params["stop"] = sampling_params["stop"]
169
+ if "presence_penalty" in sampling_params:
170
+ completion_params["presence_penalty"] = sampling_params["presence_penalty"]
171
+ if "frequency_penalty" in sampling_params:
172
+ completion_params["frequency_penalty"] = sampling_params["frequency_penalty"]
173
+
174
+ return self.client.completions.create(**completion_params)
175
+
176
+ def form_chat_prompt(message_history, functions=functions_dict.keys()):
177
+ """Builds the chat prompt for the LLM."""
178
+ functions_string = "\n\n".join([json.dumps(functions_dict[f], indent=4) for f in functions])
179
+ full_prompt = (
180
+ ROLE_HEADER.format(role="system")
181
+ + "\n\n"
182
+ + system_prompt.format(functions=functions_string)
183
+ + EOT_STRING
184
+ )
185
+ for message in message_history:
186
+ full_prompt += (
187
+ ROLE_HEADER.format(role=message["role"])
188
+ + "\n\n"
189
+ + message["content"]
190
+ + EOT_STRING
191
+ )
192
+ full_prompt += ROLE_HEADER.format(role="assistant")
193
+ return full_prompt
194
+
195
+ def check_assistant_response_for_tool_calls(response):
196
+ """Check if the LLM response contains a function call."""
197
+ response = response.split(FUNCTION_EOT_STRING)[0].split(EOT_STRING)[0]
198
+ for tool_name in functions_dict.keys():
199
+ if f"\"{tool_name}\"" in response and "{" in response:
200
+ response = "{" + "{".join(response.split("{")[1:])
201
+ for _ in range(10):
202
+ response = "}".join(response.split("}")[:-1]) + "}"
203
+ try:
204
+ return json.loads(response)
205
+ except json.JSONDecodeError:
206
+ continue
207
+ return None
208
+
209
+ def process_tool_request(tool_request_data):
210
+ """Process tool requests from the LLM."""
211
+ tool_name = tool_request_data["name"]
212
+ tool_parameters = tool_request_data["parameters"]
213
+
214
+ if tool_name == PAPER_SEARCH_FUNCTION_NAME:
215
+ query = tool_parameters["query"]
216
+ max_results = tool_parameters.get("max_results", 5)
217
+ sort_by = tool_parameters.get("sort_by", "relevance")
218
+ search_results = FUNCTION_BACKENDS[tool_name](query, max_results, sort_by)
219
+ return {"name": PAPER_SEARCH_FUNCTION_NAME, "results": search_results}
220
+
221
+ return None
222
+
223
+ def restore_message_history(full_history):
224
+ """Restore the complete message history including tool interactions."""
225
+ restored = []
226
+ for message in full_history:
227
+ if message["role"] == "assistant" and "metadata" in message:
228
+ tool_interactions = message["metadata"].get("tool_interactions", [])
229
+ if tool_interactions:
230
+ for tool_msg in tool_interactions:
231
+ restored.append(tool_msg)
232
+ final_msg = message.copy()
233
+ del final_msg["metadata"]["tool_interactions"]
234
+ restored.append(final_msg)
235
+ else:
236
+ restored.append(message)
237
+ else:
238
+ restored.append(message)
239
+ return restored
240
+
241
+ def iterate_chat(llm, sampling_params, full_history):
242
+ """Handle conversation turns with tool calling."""
243
+ tool_interactions = []
244
+
245
+ for _ in range(10):
246
+ prompt = form_chat_prompt(restore_message_history(full_history) + tool_interactions)
247
+ output = llm.generate(prompt, sampling_params)
248
+
249
+ if VERBOSE_SHELL:
250
+ print(f"Input prompt: {prompt}")
251
+ print("-" * 50)
252
+ print(f"Model response: {output.choices[0].text}")
253
+ print("=" * 50)
254
+ if not output or not output.choices:
255
+ raise ValueError("Invalid completion response")
256
+
257
+ assistant_response = output.choices[0].text.strip()
258
+ assistant_response = assistant_response.split(FUNCTION_EOT_STRING)[0].split(EOT_STRING)[0]
259
+
260
+ tool_request_data = check_assistant_response_for_tool_calls(assistant_response)
261
+ if not tool_request_data:
262
+ final_message = {
263
+ "role": "assistant",
264
+ "content": assistant_response,
265
+ "metadata": {
266
+ "tool_interactions": tool_interactions
267
+ }
268
+ }
269
+ full_history.append(final_message)
270
+ return full_history
271
+ else:
272
+ assistant_message = {
273
+ "role": "assistant",
274
+ "content": json.dumps(tool_request_data),
275
+ }
276
+ tool_interactions.append(assistant_message)
277
+ tool_return_data = process_tool_request(tool_request_data)
278
+
279
+ tool_message = {
280
+ "role": "function",
281
+ "content": json.dumps(tool_return_data)
282
+ }
283
+ tool_interactions.append(tool_message)
284
+
285
+ return full_history
286
+
287
+ def user_conversation(user_message, chat_history, full_history):
288
+ """Handle user input and maintain conversation state."""
289
+ if full_history is None:
290
+ full_history = []
291
+
292
+ full_history.append({"role": "user", "content": user_message})
293
+ updated_history = iterate_chat(llm, sampling_params, full_history)
294
+ assistant_answer = updated_history[-1]["content"]
295
+ chat_history.append((user_message, assistant_answer))
296
+
297
+ return "", chat_history, updated_history
298
+
299
+ sampling_params = {
300
+ "temperature": 0.8,
301
+ "top_p": 0.95,
302
+ "max_tokens": 512,
303
+ "stop_token_ids": [128001,128008,128009,128006],
304
+ }
305
+
306
+ # Initialize LLM
307
+ llm = LLM(max_model_len=8096)
308
+
309
+ def build_demo():
310
+ """Build the Gradio interface."""
311
+ with gr.Blocks() as demo:
312
+ gr.Markdown(f"<h2>{NAME_OF_SERVICE}</h2>")
313
+ chat_state = gr.State([])
314
+ chatbot = gr.Chatbot(label="Chat with the arXiv Paper Search Assistant")
315
+ user_input = gr.Textbox(
316
+ lines=1,
317
+ placeholder="Type your message here...",
318
+ )
319
+
320
+ user_input.submit(
321
+ fn=user_conversation,
322
+ inputs=[user_input, chatbot, chat_state],
323
+ outputs=[user_input, chatbot, chat_state],
324
+ queue=False
325
+ )
326
+
327
+ send_button = gr.Button("Check Balance")
328
+ send_button.click(
329
+ fn=user_conversation,
330
+ inputs=[user_input, chatbot, chat_state],
331
+ outputs=[user_input, chatbot, chat_state],
332
+ queue=False
333
+ )
334
+
335
+ return demo
336
+
337
+ if __name__ == "__main__":
338
+ demo = build_demo()
339
+ demo.launch()