cmgramse commited on
Commit
1507317
·
verified ·
1 Parent(s): 7eed6a8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -110
app.py CHANGED
@@ -3,14 +3,16 @@ import datetime
3
  import requests
4
  import pytz
5
  import yaml
6
- from transformers import PerplexityForTextGeneration
 
 
7
 
8
  # Import additional tools
9
  from tools.final_answer import FinalAnswerTool
10
  from Gradio_UI import GradioUI
11
 
12
- # Initialize Perplexity without API key - we'll get it from the user
13
- perplexity = None
14
 
15
  @tool
16
  def initialize_perplexity(api_key: str) -> str:
@@ -18,12 +20,55 @@ def initialize_perplexity(api_key: str) -> str:
18
  Args:
19
  api_key: Your Perplexity API key
20
  """
21
- global perplexity
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  try:
23
- perplexity = PerplexityForTextGeneration(api_key=api_key)
24
- return "Perplexity API initialized successfully!"
25
- except Exception as e:
26
- return f"Error initializing Perplexity API: {str(e)}"
 
 
27
 
28
  @tool
29
  def get_ai_research_papers(query: str) -> str:
@@ -31,18 +76,18 @@ def get_ai_research_papers(query: str) -> str:
31
  Args:
32
  query: The search query for AI research papers.
33
  """
34
- if not perplexity:
35
- return "Error: Perplexity API not initialized. Please initialize it first."
36
-
37
  try:
38
- response = perplexity.search(
39
- query=query,
40
- max_results=3,
41
- filters={"domain": "AI"}
42
- )
43
- if response:
44
- papers = "\n".join([f" {paper.title}" for paper in response])
45
- return f"Found these relevant AI papers about {query}:\n{papers}"
 
 
 
46
  return f"No relevant AI papers found for your query: {query}"
47
  except Exception as e:
48
  return f"Error fetching research papers: {str(e)}"
@@ -53,21 +98,15 @@ def summarize_paper(paper_title: str) -> str:
53
  Args:
54
  paper_title: Title of the paper to summarize.
55
  """
56
- if not perplexity:
57
- return "Error: Perplexity API not initialized. Please initialize it first."
58
-
59
  try:
60
- try:
61
- response = perplexity.search(
62
- query=paper_title,
63
- max_results=1
64
- )
65
- if response:
66
- paper = response[0]
67
- summary = paper.summary
68
- return f"Summary of '{paper_title}':\n{summary}"
69
- except IndexError:
70
- return f"Could not find a paper titled '{paper_title}"
71
  except Exception as e:
72
  return f"Error summarizing paper: {str(e)}"
73
 
@@ -77,25 +116,15 @@ def get_citation(paper_title: str) -> str:
77
  Args:
78
  paper_title: Title of the paper to cite.
79
  """
80
- if not perplexity:
81
- return "Error: Perplexity API not initialized. Please initialize it first."
82
-
83
  try:
84
- try:
85
- response = perplexity.search(
86
- query=paper_title,
87
- max_results=1
88
- )
89
- if response:
90
- paper = response[0]
91
- citation = f"""{paper.title}
92
- Author(s): {paper.authors}
93
- Published in: {paper.venue}
94
- Year: {paper.year}
95
- DOI: {paper.doi if paper.doi else 'Not available'}"""
96
- return citation
97
- except IndexError:
98
- return f"Could not find a paper titled '{paper_title}"
99
  except Exception as e:
100
  return f"Error generating citation: {str(e)}"
101
 
@@ -105,20 +134,15 @@ def explain_concept(concept: str) -> str:
105
  Args:
106
  concept: The concept to explain.
107
  """
108
- if not perplexity:
109
- return "Error: Perplexity API not initialized. Please initialize it first."
110
-
111
  try:
112
- try:
113
- response = perplexity.search(
114
- query=f"explain {concept}",
115
- max_results=1
116
- )
117
- if response:
118
- explanation = response[0].summary
119
- return f"Explanation of {concept}:\n{explanation}"
120
- except IndexError:
121
- return f"Could not find an explanation for '{concept}"
122
  except Exception as e:
123
  return f"Error explaining concept: {str(e)}"
124
 
@@ -154,70 +178,69 @@ agent = CodeAgent(
154
  grammar=None,
155
  planning_interval=None,
156
  name="AI Research Assistant",
157
- description="An AI-powered research assistant for exploring AI-related papers and concepts.",
158
  prompt_templates=prompt_templates
159
  )
160
 
161
- # Modified UI with API key input
162
  def create_ui():
163
- from gradio import Blocks
164
  with Blocks() as demo:
165
- with gradio.Row():
166
- gradio.Markdown("# AI Research Assistant")
167
- gradio.Markdown("Your AI-powered research companion")
168
 
169
- with gradio.Row():
170
- input_api_key = gradio.Textbox(label="Enter your Perplexity API Key:")
171
- initialize_button = gradio.Button("Initialize Perplexity API")
 
 
172
 
173
  initialize_button.click(
174
  fn=initialize_perplexity,
175
  inputs=input_api_key,
176
- outputs=gradio.Output(label="Initialization Status")
177
- )
178
-
179
- with gradio.Row():
180
- input_query = gradio.Textbox(label="Search query for AI papers:")
181
- search_button = gradio.Button("Search Papers")
182
-
183
- search_button.click(
184
- fn=get_ai_research_papers,
185
- inputs=input_query,
186
- outputs=gradio.Output(label="Search Results")
187
  )
188
-
189
- with gradio.Row():
190
- input_paper_title = gradio.Textbox(label="Paper title to summarize:")
191
- summarize_button = gradio.Button("Summarize Paper")
192
-
 
 
 
 
 
 
 
 
 
193
  summarize_button.click(
194
  fn=summarize_paper,
195
  inputs=input_paper_title,
196
- outputs=gradio.Output(label="Paper Summary")
197
  )
198
-
199
- with gradio.Row():
200
- input_citation_title = gradio.Textbox(label="Paper title to cite:")
201
- citation_button = gradio.Button("Generate Citation")
202
-
203
  citation_button.click(
204
- fn=get_citation,
205
- inputs=input_citation_title,
206
- outputs=gradio.Output(label="Citation")
207
- )
208
-
209
- with gradio.Row():
210
- input_concept = gradio.Textbox(label="Concept to explain:")
211
- explain_button = gradio.Button("Explain Concept")
212
-
213
  explain_button.click(
214
- fn=explain_concept,
215
- inputs=input_concept,
216
- outputs=gradio.Output(label="Explanation")
217
- )
218
-
219
  return demo
220
 
221
  # Launch the enhanced UI
222
  if __name__ == "__main__":
223
- create_ui()
 
 
3
  import requests
4
  import pytz
5
  import yaml
6
+ import importlib
7
+ from gradio import Blocks
8
+ import json
9
 
10
  # Import additional tools
11
  from tools.final_answer import FinalAnswerTool
12
  from Gradio_UI import GradioUI
13
 
14
+ # Initialize Perplexity without API key
15
+ perplexity_api_key = None
16
 
17
  @tool
18
  def initialize_perplexity(api_key: str) -> str:
 
20
  Args:
21
  api_key: Your Perplexity API key
22
  """
23
+ global perplexity_api_key
24
+ perplexity_api_key = api_key
25
+ return "Perplexity API initialized successfully!"
26
+
27
+ def call_perplexity_api(query: str):
28
+ """Calls the Perplexity API with the provided query and parameters."""
29
+ global perplexity_api_key
30
+ if not perplexity_api_key:
31
+ return "Error: Perplexity API not initialized. Please initialize it first."
32
+
33
+ url = "https://api.perplexity.ai/chat/completions"
34
+
35
+ payload = {
36
+ "model": "sonar-medium-online", # online models are better for research
37
+ "messages": [
38
+ {
39
+ "role": "system",
40
+ "content": "Be precise and concise."
41
+ },
42
+ {
43
+ "role": "user",
44
+ "content": query
45
+ }
46
+ ],
47
+ "max_tokens": 1000,
48
+ "temperature": 0.2,
49
+ "top_p": 0.9,
50
+ "search_domain_filter": None,
51
+ "return_images": False,
52
+ "return_related_questions": False,
53
+ "search_recency_filter": "month", #limit recency of search to this month
54
+ "top_k": 0,
55
+ "stream": False,
56
+ "presence_penalty": 0,
57
+ "frequency_penalty": 1,
58
+ "response_format": None
59
+ }
60
+ headers = {
61
+ "Authorization": f"Bearer {perplexity_api_key}",
62
+ "Content-Type": "application/json"
63
+ }
64
+
65
  try:
66
+ response = requests.post(url, json=payload, headers=headers)
67
+ response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
68
+ return response.json() # Return the JSON response
69
+ except requests.exceptions.RequestException as e:
70
+ return f"Request failed: {e}" # Handle request exceptions
71
+
72
 
73
  @tool
74
  def get_ai_research_papers(query: str) -> str:
 
76
  Args:
77
  query: The search query for AI research papers.
78
  """
 
 
 
79
  try:
80
+ response_json = call_perplexity_api(f"search AI research papers about: {query}")
81
+ if isinstance(response_json, str): #Error message
82
+ return response_json
83
+
84
+ if response_json and "choices" in response_json:
85
+ content = response_json["choices"][0]["message"]["content"]
86
+ citations = response_json.get("citations", [])
87
+ citation_string = "\n".join([f"{i+1}. {citation}" for i, citation in enumerate(citations)])
88
+
89
+ return f"AI Research Papers:\n{content}\n\nCitations:\n{citation_string if citation_string else 'No citations found.'}"
90
+
91
  return f"No relevant AI papers found for your query: {query}"
92
  except Exception as e:
93
  return f"Error fetching research papers: {str(e)}"
 
98
  Args:
99
  paper_title: Title of the paper to summarize.
100
  """
 
 
 
101
  try:
102
+ response_json = call_perplexity_api(f"Summarize AI research paper: {paper_title}")
103
+ if isinstance(response_json, str): #Error message
104
+ return response_json
105
+
106
+ if response_json and "choices" in response_json:
107
+ content = response_json["choices"][0]["message"]["content"]
108
+ return f"Summary of '{paper_title}':\n{content}"
109
+ return f"Could not summarize paper '{paper_title}'"
 
 
 
110
  except Exception as e:
111
  return f"Error summarizing paper: {str(e)}"
112
 
 
116
  Args:
117
  paper_title: Title of the paper to cite.
118
  """
 
 
 
119
  try:
120
+ response_json = call_perplexity_api(f"Generate citation for AI research paper: {paper_title}")
121
+ if isinstance(response_json, str): #Error message
122
+ return response_json
123
+
124
+ if response_json and "choices" in response_json:
125
+ content = response_json["choices"][0]["message"]["content"]
126
+ return f"Citation for '{paper_title}':\n{content}"
127
+ return f"Could not generate citation for '{paper_title}'"
 
 
 
 
 
 
 
128
  except Exception as e:
129
  return f"Error generating citation: {str(e)}"
130
 
 
134
  Args:
135
  concept: The concept to explain.
136
  """
 
 
 
137
  try:
138
+ response_json = call_perplexity_api(f"Explain the AI concept: {concept}")
139
+ if isinstance(response_json, str): #Error message
140
+ return response_json
141
+
142
+ if response_json and "choices" in response_json:
143
+ content = response_json["choices"][0]["message"]["content"]
144
+ return f"Explanation of {concept}:\n{content}"
145
+ return f"Could not explain the concept '{concept}'"
 
 
146
  except Exception as e:
147
  return f"Error explaining concept: {str(e)}"
148
 
 
178
  grammar=None,
179
  planning_interval=None,
180
  name="AI Research Assistant",
181
+ description="An AI-powered research assistant for exploring AI-related papers and concepts using Perplexity API.",
182
  prompt_templates=prompt_templates
183
  )
184
 
185
+ # Enhanced UI with automatic dependency installation
186
  def create_ui():
187
+ from gradio import Blocks,Markdown, Row, Textbox, Button, Output
188
  with Blocks() as demo:
189
+ with Row():
190
+ Markdown("# AI Research Assistant")
191
+ Markdown("Your AI-powered research companion")
192
 
193
+ with Row():
194
+ Markdown("## Setup Required")
195
+ Markdown("1. Enter Perplexity API key")
196
+ input_api_key = Textbox(label="Enter your Perplexity API Key:")
197
+ initialize_button = Button("Initialize Perplexity API")
198
 
199
  initialize_button.click(
200
  fn=initialize_perplexity,
201
  inputs=input_api_key,
202
+ outputs=Output(label="Initialization Status")
 
 
 
 
 
 
 
 
 
 
203
  )
204
+ with Row():
205
+ Markdown("## Research Tools")
206
+ input_query = Textbox(label="Search query for AI papers:")
207
+ search_button = Button("Search Papers")
208
+ search_button.click(
209
+ fn=get_ai_research_papers,
210
+ inputs=input_query,
211
+ outputs=Output(label="Search Results")
212
+ )
213
+
214
+ with Row():
215
+ input_paper_title = Textbox(label="Paper title to summarize:")
216
+ summarize_button = Button("Summarize Paper")
217
+
218
  summarize_button.click(
219
  fn=summarize_paper,
220
  inputs=input_paper_title,
221
+ outputs=Output(label="Paper Summary")
222
  )
223
+ with Row():
224
+ input_citation_title = Textbox(label="Paper title to cite:")
225
+ citation_button = Button("Generate Citation")
226
+
 
227
  citation_button.click(
228
+ fn=get_citation,
229
+ inputs=input_citation_title,
230
+ outputs=Output(label="Citation")
231
+ )
232
+ with Row():
233
+ input_concept = Textbox(label="Concept to explain:")
234
+ explain_button = Button("Explain Concept")
235
+
 
236
  explain_button.click(
237
+ fn=explain_concept,
238
+ inputs=input_concept,
239
+ outputs=Output(label="Explanation")
240
+ )
 
241
  return demo
242
 
243
  # Launch the enhanced UI
244
  if __name__ == "__main__":
245
+ demo = create_ui()
246
+ demo.launch()