ProximileAdmin commited on
Commit
c077384
·
verified ·
1 Parent(s): 2a53dec

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +549 -0
  2. packages.txt +1 -0
  3. requirements.txt +6 -0
app.py ADDED
@@ -0,0 +1,549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import textwrap
3
+ import datetime
4
+ import json
5
+ import gradio as gr
6
+ from openai import OpenAI
7
+ import urllib.request
8
+ import feedparser
9
+ import time
10
+ from typing import Dict, List, Optional
11
+ import pubmed_parser
12
+ import requests
13
+
14
+ VERBOSE_SHELL = True
15
+ ENDPOINT_URL = "https://api.hyperbolic.xyz/v1"
16
+ OAI_API_KEY = os.environ['HYPERBOLIC_XYZ_API_KEY']
17
+ WEATHER_API_KEY = os.environ["WEATHER_API_KEY"]
18
+ MODEL_NAME = "meta-llama/Llama-3.3-70B-Instruct"
19
+
20
+ def lgs(log_string):
21
+ if VERBOSE_SHELL:
22
+ print(log_string)
23
+
24
+ sampling_params = {
25
+ "temperature": 0.8,
26
+ "top_p": 0.95,
27
+ "max_tokens": 512,
28
+ "stop_token_ids": [128001,128008,128009,128006],
29
+ }
30
+
31
+ EOT_STRING = "<|eot_id|>"
32
+ FUNCTION_EOT_STRING = "<|eom_id|>"
33
+ ROLE_HEADER = "<|start_header_id|>{role}<|end_header_id|>"
34
+
35
+ todays_date_string = datetime.date.today().strftime("%d %B %Y")
36
+
37
+ def system_prompt_format(function_descriptions,function_jsons):
38
+ return """Cutting Knowledge Date: December 2023
39
+ Today Date: """ + todays_date_string + """
40
+
41
+ You are a helpful assistant with tool calling capabilities.
42
+
43
+ """ + "\n".join(function_descriptions) + """
44
+ 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.
45
+
46
+ Your tool request should be in the exact 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.
47
+
48
+ """ + "\n".join([json.dumps(d,indent=2) for d in function_jsons]) + """
49
+
50
+ 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.
51
+
52
+ If the user request does not necessitate a function call, simply respond to the user's query directly."""
53
+
54
+
55
+ def build_sys_prompt(tool_objects):
56
+ function_descriptions = [t.system_prompt_paragraph for t in tool_objects]
57
+ function_jsons = [t.json_definition_of_function for t in tool_objects]
58
+ return system_prompt_format(function_descriptions,function_jsons)
59
+
60
+ class ToolBase:
61
+ def __init__(self,
62
+ programmatic_name: str,
63
+ natural_name: str,
64
+ active_voice_description_of_capability: str,
65
+ passive_voice_description_of_function: str,
66
+ prescriptive_conditional: str,
67
+ input_params: Dict[str, Dict], # Changed this line
68
+ required_params: Optional[List[str]] = None,
69
+ ):
70
+ self.json_name = programmatic_name
71
+ self.json_description = passive_voice_description_of_function
72
+ self.json_definition_of_function = {
73
+ "type": "function",
74
+ "function": {
75
+ "name": self.json_name,
76
+ "description": self.json_description,
77
+ "parameters": {
78
+ "type": "object",
79
+ "properties": input_params,
80
+ "required": required_params,
81
+ }
82
+ }
83
+ }
84
+ self.system_prompt_paragraph = active_voice_description_of_capability + " " + prescriptive_conditional
85
+ def actual_function(self, **kwargs):
86
+ raise NotImplementedError("Subclasses must implement this method.")
87
+
88
+ def search_arxiv_papers(
89
+ query: str,
90
+ max_results: int = 5,
91
+ sort_by: str = 'relevance'
92
+ ) -> Dict:
93
+ """
94
+ Search for papers on arXiv using their API.
95
+
96
+ Args:
97
+ query: Search query string
98
+ max_results: Maximum number of results to return (default: 5)
99
+ sort_by: Sorting criteria (default: 'relevance')
100
+
101
+ Returns:
102
+ Dictionary containing search results and metadata
103
+ """
104
+ try:
105
+ # Construct the search query
106
+ search_query = f'all:{query}'
107
+
108
+ # Construct the API URL
109
+ base_url = 'https://export.arxiv.org/api/query?'
110
+ params = {
111
+ 'search_query': search_query,
112
+ 'start': 0,
113
+ 'max_results': max_results,
114
+ 'sortBy': sort_by,
115
+ 'sortOrder': 'descending'
116
+ }
117
+ query_string = '&'.join([f'{k}={urllib.parse.quote(str(v))}' for k, v in params.items()])
118
+ url = base_url + query_string
119
+
120
+ # Make the API request
121
+ response = urllib.request.urlopen(url)
122
+ feed = feedparser.parse(response.read().decode('utf-8'))
123
+
124
+ # Process the results
125
+ papers = []
126
+ for entry in feed.entries:
127
+ paper = {
128
+ 'id': entry.id.split('/abs/')[-1],
129
+ 'title': entry.title,
130
+ 'authors': [author.name for author in entry.authors],
131
+ 'summary': entry.summary,
132
+ 'published': entry.published,
133
+ 'link': entry.link,
134
+ 'primary_category': entry.tags[0]['term']
135
+ }
136
+ papers.append(paper)
137
+
138
+ time.sleep(1)
139
+
140
+ return {
141
+ 'status': 'success',
142
+ 'total_results': len(papers),
143
+ 'papers': papers
144
+ }
145
+
146
+ except Exception as e:
147
+ return {
148
+ 'status': 'error',
149
+ 'message': str(e)
150
+ }
151
+
152
+ class ArxivSearchTool(ToolBase):
153
+ def __init__(self):
154
+ super().__init__(
155
+ programmatic_name="search_arxiv_papers",
156
+ natural_name="arXiv Paper Search",
157
+ active_voice_description_of_capability="You can search for academic papers on arXiv.",
158
+ passive_voice_description_of_function="a service that searches and retrieves academic papers from arXiv based on various criteria",
159
+ prescriptive_conditional="When given a research topic or paper query, you should call the search_arxiv_papers function to find relevant papers.",
160
+ input_params={
161
+ "query": {
162
+ "type": "string",
163
+ "description": "Search query (e.g., 'deep learning', 'quantum computing')"
164
+ },
165
+ "max_results": {
166
+ "type": "integer",
167
+ "description": "Maximum number of results to return (default: 5)",
168
+ "optional": True
169
+ },
170
+ "sort_by": {
171
+ "type": "string",
172
+ "description": "Sort criteria (e.g., 'relevance', 'lastUpdatedDate', 'submittedDate')",
173
+ "optional": True
174
+ }
175
+ },
176
+ required_params=["query"],
177
+ )
178
+
179
+ def actual_function(self, **kwargs):
180
+ """
181
+ Search for papers on arXiv using their API.
182
+
183
+ Args:
184
+ query: Search query string
185
+ max_results: Maximum number of results to return (default: 5)
186
+ sort_by: Sorting criteria (default: 'relevance')
187
+
188
+ Returns:
189
+ Dictionary containing search results and metadata
190
+ """
191
+ return search_arxiv_papers(**kwargs)
192
+
193
+ arxiv_tool = ArxivSearchTool()
194
+
195
+ def get_snp_info(rsid):
196
+ base_url = "https://api.ncbi.nlm.nih.gov/variation/v0/"
197
+ result = {"rsid": rsid, "error": "No data found"}
198
+
199
+ # Fetch RefSNP data
200
+ snp_url = f"{base_url}refsnp/{rsid}"
201
+ response = requests.get(snp_url)
202
+
203
+ if response.status_code != 200:
204
+ return {"error": f"Failed to retrieve data for rs{rsid}"}
205
+
206
+ data = response.json()
207
+
208
+ # Extract useful information
209
+ result = {
210
+ "create_date": data.get("create_date", "Unknown"),
211
+ "last_update_date": data.get("last_update_date", "Unknown"),
212
+ "genes": [],
213
+ "hgvs": [],
214
+ "spdi": [],
215
+ "clinical_significance": [],
216
+ "frequency_data": {},
217
+ }
218
+
219
+ # Extract gene associations
220
+ primary_data = data.get("primary_snapshot_data", {})
221
+ if "allele_annotations" in primary_data:
222
+ for annotation in primary_data["allele_annotations"]:
223
+ for gene in annotation.get("assembly_annotation", []):
224
+ for gene_info in gene.get("genes", []):
225
+ result["genes"].append(gene_info.get("locus", "Unknown"))
226
+
227
+ # Extract HGVS notation
228
+ for placement in primary_data.get("placements_with_allele", []):
229
+ for allele in placement.get("alleles", []):
230
+ if "hgvs" in allele:
231
+ result["hgvs"].append(allele["hgvs"])
232
+ if "spdi" in allele.get("allele", {}):
233
+ spdi_data = allele["allele"]["spdi"]
234
+ spdi_notation = f"{spdi_data['seq_id']}:{spdi_data['position']}:{spdi_data['deleted_sequence']}:{spdi_data['inserted_sequence']}"
235
+ result["spdi"].append(spdi_notation)
236
+
237
+ # Extract clinical significance from ClinVar
238
+ for annotation in primary_data.get("allele_annotations", []):
239
+ for clinical in annotation.get("clinical", []):
240
+ result["clinical_significance"].extend(clinical.get("clinical_significances", []))
241
+
242
+ # Fetch ALFA frequency data
243
+ freq_url = f"{base_url}refsnp/{rsid}/frequency"
244
+ freq_response = requests.get(freq_url)
245
+
246
+ if freq_response.status_code == 200:
247
+ freq_data = freq_response.json().get("results", {})
248
+ for key, value in freq_data.items():
249
+ if "counts" in value:
250
+ result["frequency_data"] = value["counts"]
251
+ break
252
+ citations = data.get("citations", [])
253
+ lgs("citations: " + str(citations))
254
+ result["citations"] = [pubmed_parser.parse_xml_web(c, sleep=0.5, save_xml=False,) for c in citations]
255
+ lgs("full citations data: " + str(result["citations"]))
256
+ return result
257
+
258
+ class NIHRefSNPTool(ToolBase):
259
+ def __init__(self):
260
+ super().__init__(
261
+ programmatic_name="search_nih_refsnp",
262
+ natural_name="NIH RefSNP Searcher",
263
+ active_voice_description_of_capability=(
264
+ "You can search for refSNP data on the NIH Variation API."
265
+ ),
266
+ passive_voice_description_of_function=(
267
+ "a service that retrieves refSNP data from the NIH Variation API "
268
+ "based on a provided SNP identifier"
269
+ ),
270
+ prescriptive_conditional=(
271
+ "When given a refSNP identifier (e.g., 'rs79220014'), "
272
+ "you should call the search_nih_refsnp function "
273
+ "to find its associated data."
274
+ ),
275
+ input_params={
276
+ "snp": {
277
+ "type": "string",
278
+ "description": "The refSNP identifier (e.g., 'rs79220014')"
279
+ }
280
+ },
281
+ required_params=["snp"],
282
+ )
283
+
284
+ def actual_function(self, **kwargs):
285
+ return get_snp_info(kwargs["snp"][2:])
286
+
287
+ nih_ref_snp_tool=NIHRefSNPTool()
288
+
289
+ def get_weather_data(location):
290
+ """
291
+ Fetch current weather data for a given location using WeatherAPI.com.
292
+
293
+ Args:
294
+ location (str): The location for which to retrieve weather (e.g., "London", "90210", or "48.8567,2.3510").
295
+
296
+ Returns:
297
+ dict: A dictionary containing the current weather data or an error message.
298
+ """
299
+ base_url = "https://api.weatherapi.com/v1/current.json"
300
+ params = {
301
+ "key": WEATHER_API_KEY,
302
+ "q": location,
303
+ "aqi": "no" # Set to "yes" to include air quality data if desired.
304
+ }
305
+ full_url = base_url + "?" + "&".join([f"{k}={urllib.parse.quote(str(v))}" for k, v in params.items()])
306
+ try:
307
+ response = requests.get(full_url)
308
+ except:
309
+ lgs("FAILED PARAMS: " + str(params))
310
+ lgs("FAILED RESPONSE: " + str(response.text))
311
+ lgs("RAW RESPONSE: " + str(response))
312
+ if response.status_code != 200:
313
+ return {"error": f"Failed to retrieve weather data for {location}. Status code: {response.status_code}"}
314
+ data = response.json()
315
+ formatted_data = {
316
+ "location": data.get("location", {}),
317
+ "current": {
318
+ "last_updated": data.get("current", {}).get("last_updated"),
319
+ "temp_c": data.get("current", {}).get("temp_c"),
320
+ "temp_f": data.get("current", {}).get("temp_f"),
321
+ "precip_mm": data.get("current", {}).get("precip_mm"),
322
+ "precip_in": data.get("current", {}).get("precip_in"),
323
+ "humidity": data.get("current", {}).get("humidity"),
324
+ "wind_kph": data.get("current", {}).get("wind_kph"),
325
+ "wind_mph": data.get("current", {}).get("wind_mph"),
326
+ "condition": data.get("current", {}).get("condition", {})
327
+ }
328
+ }
329
+ return formatted_data
330
+
331
+ class WeatherAPITool(ToolBase):
332
+ def __init__(self):
333
+ super().__init__(
334
+ programmatic_name="get_weather_data",
335
+ natural_name="Weather Report Fetcher",
336
+ active_voice_description_of_capability="You can fetch real-time weather data for any location worldwide.",
337
+ passive_voice_description_of_function="a service that retrieves current weather details including temperature, precipitation, humidity, and wind data.",
338
+ prescriptive_conditional="When provided with a location (city, ZIP, or lat,long) call the get_weather_data function to retrieve its weather information.",
339
+ input_params={
340
+ "location": {
341
+ "type": "string",
342
+ "description": "The location to retrieve weather data for (e.g., 'London', '90210', or '48.8567,2.3510')."
343
+ },
344
+ },
345
+ required_params=["location"],
346
+ )
347
+
348
+ def actual_function(self, **kwargs):
349
+ return get_weather_data(kwargs["location"])
350
+
351
+ # Instance of the weather tool.
352
+ weather_tool = WeatherAPITool()
353
+
354
+ tool_objects_list = [arxiv_tool, nih_ref_snp_tool,weather_tool]
355
+ system_prompt = build_sys_prompt(tool_objects_list)
356
+ functions_dict = {t.json_name: t.actual_function for t in tool_objects_list}
357
+
358
+ print(system_prompt)
359
+
360
+ class LLM:
361
+ def __init__(self, max_model_len: int = 4096):
362
+ self.api_key = OAI_API_KEY
363
+ self.max_model_len = max_model_len
364
+ self.client = OpenAI(base_url=ENDPOINT_URL, api_key=self.api_key)
365
+ #models_list = self.client.models.list()
366
+ #self.model_name = models_list.data[0].id
367
+ self.model_name = MODEL_NAME
368
+
369
+ def generate(self, prompt: str, sampling_params: dict) -> dict:
370
+ completion_params = {
371
+ "model": self.model_name,
372
+ "prompt": prompt,
373
+ "max_tokens": sampling_params.get("max_tokens", 2048),
374
+ "temperature": sampling_params.get("temperature", 0.8),
375
+ "top_p": sampling_params.get("top_p", 0.95),
376
+ "n": sampling_params.get("n", 1),
377
+ "stream": False,
378
+ }
379
+
380
+ if "stop" in sampling_params:
381
+ completion_params["stop"] = sampling_params["stop"]
382
+ if "presence_penalty" in sampling_params:
383
+ completion_params["presence_penalty"] = sampling_params["presence_penalty"]
384
+ if "frequency_penalty" in sampling_params:
385
+ completion_params["frequency_penalty"] = sampling_params["frequency_penalty"]
386
+
387
+ return self.client.completions.create(**completion_params)
388
+
389
+ def form_chat_prompt(message_history, functions=functions_dict.keys()):
390
+ """Builds the chat prompt for the LLM."""
391
+
392
+ full_prompt = (
393
+ ROLE_HEADER.format(role="system")
394
+ + "\n\n"
395
+ + system_prompt
396
+ + EOT_STRING
397
+ )
398
+ for message in message_history:
399
+ full_prompt += (
400
+ ROLE_HEADER.format(role=message["role"])
401
+ + "\n\n"
402
+ + message["content"]
403
+ + EOT_STRING
404
+ )
405
+ full_prompt += ROLE_HEADER.format(role="assistant")
406
+ return full_prompt
407
+
408
+ def check_assistant_response_for_tool_calls(response):
409
+ """Check if the LLM response contains a function call."""
410
+ response = response.split(FUNCTION_EOT_STRING)[0].split(EOT_STRING)[0]
411
+ for tool_name in functions_dict.keys():
412
+ if f"\"{tool_name}\"" in response and "{" in response:
413
+ response = "{" + "{".join(response.split("{")[1:])
414
+ for _ in range(10):
415
+ response = "}".join(response.split("}")[:-1]) + "}"
416
+ try:
417
+ return json.loads(response)
418
+ except json.JSONDecodeError:
419
+ continue
420
+ return None
421
+
422
+ def process_tool_request(tool_request_data):
423
+ """Process tool requests from the LLM."""
424
+ tool_name = tool_request_data["name"]
425
+ tool_parameters = tool_request_data["parameters"]
426
+ tool_return = None
427
+ if tool_name == arxiv_tool.json_name:
428
+ query = tool_parameters["query"]
429
+ max_results = tool_parameters.get("max_results", 5)
430
+ sort_by = tool_parameters.get("sort_by", "relevance")
431
+ search_results = arxiv_tool.actual_function(query=query, max_results=max_results, sort_by=sort_by)
432
+ tool_return = {"name": arxiv_tool.json_name, "return": search_results}
433
+ elif tool_name == nih_ref_snp_tool.json_name:
434
+ snp = tool_parameters["snp"]
435
+ search_results = nih_ref_snp_tool.actual_function(snp=snp)
436
+ tool_return = {"name": nih_ref_snp_tool.json_name, "return": search_results}
437
+ elif tool_name == weather_tool.json_name:
438
+ location = tool_parameters["location"]
439
+ search_results = weather_tool.actual_function(location=location)
440
+ tool_return = {"name": weather_tool.json_name, "return": search_results}
441
+ else:
442
+ raise ValueError(f"Unknown tool name: {tool_name}")
443
+ lgs("TOOL: " + str(tool_return))
444
+ return tool_return
445
+
446
+ def restore_message_history(full_history):
447
+ """Restore the complete message history including tool interactions."""
448
+ restored = []
449
+ for message in full_history:
450
+ if message["role"] == "assistant" and "metadata" in message:
451
+ tool_interactions = message["metadata"].get("tool_interactions", [])
452
+ if tool_interactions:
453
+ for tool_msg in tool_interactions:
454
+ restored.append(tool_msg)
455
+ final_msg = message.copy()
456
+ del final_msg["metadata"]["tool_interactions"]
457
+ restored.append(final_msg)
458
+ else:
459
+ restored.append(message)
460
+ else:
461
+ restored.append(message)
462
+ return restored
463
+
464
+ def iterate_chat(llm, sampling_params, full_history):
465
+ """Handle conversation turns with tool calling."""
466
+ tool_interactions = []
467
+
468
+ for _ in range(10):
469
+ prompt = form_chat_prompt(restore_message_history(full_history) + tool_interactions)
470
+ output = llm.generate(prompt, sampling_params)
471
+
472
+ if VERBOSE_SHELL:
473
+ print(f"Input prompt: {prompt}")
474
+ print("-" * 50)
475
+ print(f"Model response: {output.choices[0].text}")
476
+ print("=" * 50)
477
+ if not output or not output.choices:
478
+ raise ValueError("Invalid completion response")
479
+
480
+ assistant_response = output.choices[0].text.strip()
481
+ lgs("ASSISTANT: " + assistant_response.replace("\n", "\\n"))
482
+ assistant_response = assistant_response.split(FUNCTION_EOT_STRING)[0].split(EOT_STRING)[0]
483
+
484
+ tool_request_data = check_assistant_response_for_tool_calls(assistant_response)
485
+ if not tool_request_data:
486
+ final_message = {
487
+ "role": "assistant",
488
+ "content": assistant_response,
489
+ "metadata": {
490
+ "tool_interactions": tool_interactions
491
+ }
492
+ }
493
+ full_history.append(final_message)
494
+ return full_history
495
+ else:
496
+ assistant_message = {
497
+ "role": "assistant",
498
+ "content": json.dumps(tool_request_data),
499
+ }
500
+ tool_interactions.append(assistant_message)
501
+ tool_return_data = process_tool_request(tool_request_data)
502
+
503
+ tool_message = {
504
+ "role": "function",
505
+ "content": json.dumps(tool_return_data)
506
+ }
507
+ tool_interactions.append(tool_message)
508
+
509
+ return full_history
510
+
511
+ def user_conversation(user_message, chat_history, full_history):
512
+ """Handle user input and maintain conversation state."""
513
+ if full_history is None:
514
+ full_history = []
515
+ lgs("USER: " + user_message.replace("\n", "\\n"))
516
+ full_history.append({"role": "user", "content": user_message})
517
+ updated_history = iterate_chat(llm, sampling_params, full_history)
518
+ assistant_answer = updated_history[-1]["content"]
519
+ chat_history.append((user_message, assistant_answer))
520
+
521
+ return "", chat_history, updated_history
522
+
523
+ llm = LLM(max_model_len=32000)
524
+
525
+ lgs("STARTING NEW CHAT")
526
+ with gr.Blocks() as demo:
527
+ gr.Markdown(f"<h2>Tool Calling Bot</h2>")
528
+ chat_state = gr.State([])
529
+ chatbot = gr.Chatbot(label="Chat with the arXiv Paper Search Assistant")
530
+ user_input = gr.Textbox(
531
+ lines=1,
532
+ placeholder="Type your message here...",
533
+ )
534
+
535
+ user_input.submit(
536
+ fn=user_conversation,
537
+ inputs=[user_input, chatbot, chat_state],
538
+ outputs=[user_input, chatbot, chat_state],
539
+ queue=False
540
+ )
541
+
542
+ send_button = gr.Button("Send")
543
+ send_button.click(
544
+ fn=user_conversation,
545
+ inputs=[user_input, chatbot, chat_state],
546
+ outputs=[user_input, chatbot, chat_state],
547
+ queue=False
548
+ )
549
+ demo.launch()
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ xvfb
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio
2
+ openai
3
+ requests
4
+ feedparser
5
+ pubmed_parser
6
+ camoufox[geoip]