cmgramse commited on
Commit
ec3181a
·
verified ·
1 Parent(s): a095268

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -210
app.py CHANGED
@@ -1,214 +1,20 @@
1
- from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
2
- import datetime
3
- import requests
4
- import pytz
5
- import yaml
6
- import json
7
  import gradio as gr
8
-
9
- # Import additional tools
10
- from tools.final_answer import FinalAnswerTool
11
- from Gradio_UI import GradioUI
 
 
 
12
 
13
  # Initialize Perplexity without API key and model
14
  perplexity_api_key = None
15
  perplexity_model = "sonar-pro" # Default model
16
 
17
- @tool
18
- def initialize_perplexity(api_key: str, model: str) -> str:
19
- """Initialize Perplexity API with your API key and model.
20
- Args:
21
- api_key: Your Perplexity API key
22
- model: The Perplexity model to use
23
- """
24
- global perplexity_api_key, perplexity_model
25
- perplexity_api_key = api_key
26
- perplexity_model = model
27
- return f"Perplexity API initialized successfully with model: {model}!"
28
-
29
- def call_perplexity_api(query: str):
30
- """Calls the Perplexity API with the provided query and parameters."""
31
- global perplexity_api_key, perplexity_model
32
- if not perplexity_api_key:
33
- return "Error: Perplexity API not initialized. Please initialize it first."
34
-
35
- url = "https://api.perplexity.ai/chat/completions"
36
-
37
- # System prompt
38
- system_prompt = """
39
- You are a helpful AI assistant.
40
-
41
- Rules:
42
- 1. Provide only the final answer. It is important that you do not include any explanation on the steps below.
43
- 2. Do not show the intermediate steps information.
44
-
45
- Steps:
46
- 1. Decide if the answer should be a brief sentence or a list of suggestions.
47
- 2. If it is a list of suggestions, first, write a brief and natural introduction based on the original query.
48
- 3. Followed by a list of suggestions, each suggestion should be split by two newlines.
49
- """
50
-
51
- payload = {
52
- "model": perplexity_model, # Use the selected model
53
- "messages": [
54
- {
55
- "role": "system",
56
- "content": system_prompt.strip() # Add the system prompt
57
- },
58
- {
59
- "role": "user",
60
- "content": query
61
- }
62
- ],
63
- "max_tokens": 8000 if perplexity_model in ["sonar-reasoning-pro", "sonar-pro"] else 1000,
64
- "temperature": 0.2,
65
- "top_p": 0.9,
66
- "search_domain_filter": None,
67
- "return_images": False,
68
- "return_related_questions": False,
69
- "search_recency_filter": "month", # Limit recency of search to this month
70
- "top_k": 0,
71
- "stream": False,
72
- "presence_penalty": 0,
73
- "frequency_penalty": 1,
74
- "response_format": None
75
- }
76
- headers = {
77
- "Authorization": f"Bearer {perplexity_api_key}",
78
- "Content-Type": "application/json"
79
- }
80
-
81
- try:
82
- response = requests.post(url, json=payload, headers=headers)
83
- response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
84
- return response.json() # Return the JSON response
85
- except requests.exceptions.RequestException as e:
86
- # Provide detailed error information
87
- error_details = {
88
- "error_type": type(e).__name__,
89
- "error_message": str(e),
90
- "response_status_code": getattr(e.response, "status_code", None),
91
- "response_text": getattr(e.response, "text", None),
92
- "request_payload": payload,
93
- "request_headers": headers
94
- }
95
- return f"Request failed. Details:\n{json.dumps(error_details, indent=2)}"
96
-
97
- @tool
98
- def get_ai_research_papers(query: str) -> str:
99
- """A tool that fetches relevant AI research papers using Perplexity API.
100
- Args:
101
- query: The search query for AI research papers.
102
- """
103
- try:
104
- response_json = call_perplexity_api(f"search AI research papers about: {query}")
105
- if isinstance(response_json, str): # Error message
106
- return response_json
107
-
108
- if response_json and "choices" in response_json:
109
- content = response_json["choices"][0]["message"]["content"]
110
- citations = response_json.get("citations", [])
111
- citation_string = "\n".join([f"{i+1}. {citation}" for i, citation in enumerate(citations)])
112
-
113
- return f"AI Research Papers:\n{content}\n\nCitations:\n{citation_string if citation_string else 'No citations found.'}"
114
-
115
- return f"No relevant AI papers found for your query: {query}"
116
- except Exception as e:
117
- return f"Error fetching research papers: {str(e)}"
118
-
119
- @tool
120
- def summarize_paper(paper_title: str) -> str:
121
- """A tool that summarizes an AI research paper.
122
- Args:
123
- paper_title: Title of the paper to summarize.
124
- """
125
- try:
126
- response_json = call_perplexity_api(f"Summarize AI research paper: {paper_title}")
127
- if isinstance(response_json, str): # Error message
128
- return response_json
129
-
130
- if response_json and "choices" in response_json:
131
- content = response_json["choices"][0]["message"]["content"]
132
- return f"Summary of '{paper_title}':\n{content}"
133
- return f"Could not summarize paper '{paper_title}'"
134
- except Exception as e:
135
- return f"Error summarizing paper: {str(e)}"
136
-
137
- @tool
138
- def get_citation(paper_title: str) -> str:
139
- """A tool that generates a citation for an AI research paper.
140
- Args:
141
- paper_title: Title of the paper to cite.
142
- """
143
- try:
144
- response_json = call_perplexity_api(f"Generate citation for AI research paper: {paper_title}")
145
- if isinstance(response_json, str): # Error message
146
- return response_json
147
-
148
- if response_json and "choices" in response_json:
149
- content = response_json["choices"][0]["message"]["content"]
150
- return f"Citation for '{paper_title}':\n{content}"
151
- return f"Could not generate citation for '{paper_title}'"
152
- except Exception as e:
153
- return f"Error generating citation: {str(e)}"
154
-
155
- @tool
156
- def explain_concept(concept: str) -> str:
157
- """A tool that explains an AI-related concept in simple terms.
158
- Args:
159
- concept: The concept to explain.
160
- """
161
- try:
162
- response_json = call_perplexity_api(f"Explain the AI concept: {concept}")
163
- if isinstance(response_json, str): # Error message
164
- return response_json
165
-
166
- if response_json and "choices" in response_json:
167
- content = response_json["choices"][0]["message"]["content"]
168
- return f"Explanation of {concept}:\n{content}"
169
- return f"Could not explain the concept '{concept}'"
170
- except Exception as e:
171
- return f"Error explaining concept: {str(e)}"
172
-
173
- final_answer = FinalAnswerTool()
174
-
175
- # Initialize the model
176
- model = HfApiModel(
177
- max_tokens=2096,
178
- temperature=0.5,
179
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
180
- )
181
-
182
- # Load additional tools
183
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
184
-
185
- with open("prompts.yaml", 'r') as stream:
186
- prompt_templates = yaml.safe_load(stream)
187
-
188
- # Create the enhanced research agent
189
- agent = CodeAgent(
190
- model=model,
191
- tools=[
192
- final_answer,
193
- initialize_perplexity,
194
- get_ai_research_papers,
195
- summarize_paper,
196
- get_citation,
197
- explain_concept,
198
- image_generation_tool,
199
- ],
200
- max_steps=6,
201
- verbosity_level=1,
202
- grammar=None,
203
- planning_interval=None,
204
- name="AI Research Assistant",
205
- description="An AI-powered research assistant for exploring AI-related papers and concepts using Perplexity API.",
206
- prompt_templates=prompt_templates
207
- )
208
-
209
  # Function to handle chat UI interactions
210
  def chat_ui_interaction(query: str, chat_history: list):
211
  """Handles user queries in the chat UI, showing the agent's thought process."""
 
212
  # Add user message to chat history
213
  chat_history.append(("user", query))
214
 
@@ -221,16 +27,16 @@ def chat_ui_interaction(query: str, chat_history: list):
221
  # Example: Decide which tool to use based on the query
222
  if "explain" in query.lower():
223
  thought_process.append("🔍 Using the 'explain_concept' tool...")
224
- result = explain_concept(query)
225
  elif "summarize" in query.lower():
226
  thought_process.append("📄 Using the 'summarize_paper' tool...")
227
- result = summarize_paper(query)
228
  elif "citation" in query.lower():
229
  thought_process.append("📚 Using the 'get_citation' tool...")
230
- result = get_citation(query)
231
  else:
232
  thought_process.append("🔎 Using the 'get_ai_research_papers' tool...")
233
- result = get_ai_research_papers(query)
234
 
235
  # Add thought process to chat history
236
  for step in thought_process:
@@ -289,7 +95,7 @@ def create_ui():
289
  search_results = gr.Textbox(label="Search Results")
290
  search_button.click(
291
  fn=get_ai_research_papers,
292
- inputs=input_query,
293
  outputs=search_results
294
  )
295
 
@@ -300,7 +106,7 @@ def create_ui():
300
  paper_summary = gr.Textbox(label="Paper Summary")
301
  summarize_button.click(
302
  fn=summarize_paper,
303
- inputs=input_paper_title,
304
  outputs=paper_summary
305
  )
306
 
@@ -311,7 +117,7 @@ def create_ui():
311
  citation_output = gr.Textbox(label="Citation")
312
  citation_button.click(
313
  fn=get_citation,
314
- inputs=input_citation_title,
315
  outputs=citation_output
316
  )
317
 
@@ -322,7 +128,7 @@ def create_ui():
322
  explanation_output = gr.Textbox(label="Explanation")
323
  explain_button.click(
324
  fn=explain_concept,
325
- inputs=input_concept,
326
  outputs=explanation_output
327
  )
328
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from tools.perplexity_tools import (
3
+ get_ai_research_papers,
4
+ summarize_paper,
5
+ get_citation,
6
+ explain_concept,
7
+ )
8
+ from tools.general_tools import initialize_perplexity
9
 
10
  # Initialize Perplexity without API key and model
11
  perplexity_api_key = None
12
  perplexity_model = "sonar-pro" # Default model
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  # Function to handle chat UI interactions
15
  def chat_ui_interaction(query: str, chat_history: list):
16
  """Handles user queries in the chat UI, showing the agent's thought process."""
17
+ global perplexity_api_key, perplexity_model
18
  # Add user message to chat history
19
  chat_history.append(("user", query))
20
 
 
27
  # Example: Decide which tool to use based on the query
28
  if "explain" in query.lower():
29
  thought_process.append("🔍 Using the 'explain_concept' tool...")
30
+ result = explain_concept(query, perplexity_api_key, perplexity_model)
31
  elif "summarize" in query.lower():
32
  thought_process.append("📄 Using the 'summarize_paper' tool...")
33
+ result = summarize_paper(query, perplexity_api_key, perplexity_model)
34
  elif "citation" in query.lower():
35
  thought_process.append("📚 Using the 'get_citation' tool...")
36
+ result = get_citation(query, perplexity_api_key, perplexity_model)
37
  else:
38
  thought_process.append("🔎 Using the 'get_ai_research_papers' tool...")
39
+ result = get_ai_research_papers(query, perplexity_api_key, perplexity_model)
40
 
41
  # Add thought process to chat history
42
  for step in thought_process:
 
95
  search_results = gr.Textbox(label="Search Results")
96
  search_button.click(
97
  fn=get_ai_research_papers,
98
+ inputs=[input_query, input_api_key, model_dropdown],
99
  outputs=search_results
100
  )
101
 
 
106
  paper_summary = gr.Textbox(label="Paper Summary")
107
  summarize_button.click(
108
  fn=summarize_paper,
109
+ inputs=[input_paper_title, input_api_key, model_dropdown],
110
  outputs=paper_summary
111
  )
112
 
 
117
  citation_output = gr.Textbox(label="Citation")
118
  citation_button.click(
119
  fn=get_citation,
120
+ inputs=[input_citation_title, input_api_key, model_dropdown],
121
  outputs=citation_output
122
  )
123
 
 
128
  explanation_output = gr.Textbox(label="Explanation")
129
  explain_button.click(
130
  fn=explain_concept,
131
+ inputs=[input_concept, input_api_key, model_dropdown],
132
  outputs=explanation_output
133
  )
134