hari7261 commited on
Commit
a792bab
·
verified ·
1 Parent(s): 015383e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -19
app.py CHANGED
@@ -1,6 +1,6 @@
1
  import gradio as gr
2
  import google.generativeai as genai
3
- from duckduckgo_search import DDGS
4
  import requests
5
  from bs4 import BeautifulSoup
6
  import time
@@ -9,16 +9,57 @@ import re
9
  import json
10
  from typing import List, Dict, Any
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  # Search the web for relevant information using DuckDuckGo
13
  def web_search(query: str, max_results: int = 10) -> List[Dict[str, str]]:
14
  """Search the web for relevant information using DuckDuckGo"""
15
  try:
16
  with DDGS() as ddgs:
17
- results = list(ddgs.text(query, max_results=max_results))
 
 
 
 
 
18
  return results
19
  except Exception as e:
20
  print(f"Search error: {e}")
21
- return []
 
 
 
 
 
 
 
22
 
23
  # Fetch and extract content from a URL
24
  def fetch_url_content(url: str) -> str:
@@ -87,11 +128,15 @@ def perform_research(query: str, max_sources: int = 5) -> Dict[str, Any]:
87
  def generate_research_report(research_data: Dict[str, Any], gemini_api_key: str) -> str:
88
  """Generate a comprehensive research report using Gemini"""
89
  if not gemini_api_key:
90
- return "Gemini API key is required to generate the report."
 
 
 
 
 
91
 
92
  try:
93
- # Initialize Gemini
94
- genai.configure(api_key=gemini_api_key)
95
  model = genai.GenerativeModel('gemini-2.0-flash')
96
 
97
  prompt = f"""
@@ -114,23 +159,36 @@ def generate_research_report(research_data: Dict[str, Any], gemini_api_key: str)
114
  response = model.generate_content(prompt)
115
  return response.text
116
  except Exception as e:
117
- return f"Error generating report: {str(e)}"
 
 
 
 
 
 
 
 
118
 
119
  # Main research function
120
  def run_research(topic: str, gemini_api_key: str):
121
  """Run the complete research process"""
122
- if not gemini_api_key:
123
- return "Please enter your Gemini API key.", None, gr.update(visible=False)
 
 
 
124
 
125
- if not topic:
126
- return "Please enter a research topic.", None, gr.update(visible=False)
 
 
127
 
128
  try:
129
  # Perform research
130
  research_data = perform_research(topic)
131
 
132
  if not research_data['sources']:
133
- return "No relevant sources found. Please try a different search term.", None, gr.update(visible=False)
134
 
135
  # Generate report
136
  report = generate_research_report(research_data, gemini_api_key)
@@ -141,7 +199,7 @@ def run_research(topic: str, gemini_api_key: str):
141
  return report, filename, gr.update(visible=True)
142
 
143
  except Exception as e:
144
- error_msg = f"An error occurred: {str(e)}"
145
  return error_msg, None, gr.update(visible=False)
146
 
147
  # Gradio interface
@@ -150,23 +208,44 @@ def create_interface():
150
  gr.Markdown("# 📘 Gemini Deep Research Agent")
151
  gr.Markdown("This agent performs deep research on any topic using Google's Gemini and DuckDuckGo search")
152
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  with gr.Row():
154
  with gr.Column(scale=1):
155
  gr.Markdown("## API Configuration")
156
  gemini_key = gr.Textbox(
157
  label="Gemini API Key",
158
  type="password",
159
- placeholder="Enter your Gemini API key (get it from https://aistudio.google.com/)"
 
 
 
 
 
 
 
 
 
160
  )
161
 
162
  with gr.Column(scale=2):
163
  research_topic = gr.Textbox(
164
  label="Research Topic",
165
- placeholder="e.g., Latest developments in AI",
166
  lines=2
167
  )
168
 
169
- research_btn = gr.Button("Start Research", variant="primary")
170
 
171
  output = gr.Markdown(
172
  label="Research Report",
@@ -174,11 +253,29 @@ def create_interface():
174
  )
175
 
176
  download_btn = gr.DownloadButton(
177
- "Download Report",
178
  visible=False
179
  )
180
 
181
- # Set up the button action
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
  research_btn.click(
183
  fn=run_research,
184
  inputs=[research_topic, gemini_key],
@@ -200,4 +297,4 @@ def create_interface():
200
  # Main execution
201
  if __name__ == "__main__":
202
  demo = create_interface()
203
- demo.launch()
 
1
  import gradio as gr
2
  import google.generativeai as genai
3
+ from ddgs import DDGS
4
  import requests
5
  from bs4 import BeautifulSoup
6
  import time
 
9
  import json
10
  from typing import List, Dict, Any
11
 
12
+ # Validate Gemini API key
13
+ def validate_api_key(api_key: str) -> tuple[bool, str]:
14
+ """Validate if the Gemini API key is working"""
15
+ if not api_key or not api_key.strip():
16
+ return False, "API key is empty. Please enter a valid Gemini API key."
17
+
18
+ if not api_key.startswith('AI'):
19
+ return False, "Invalid API key format. Gemini API keys should start with 'AI'."
20
+
21
+ try:
22
+ # Test the API key with a simple request
23
+ genai.configure(api_key=api_key.strip())
24
+ model = genai.GenerativeModel('gemini-2.0-flash')
25
+
26
+ # Try a minimal test generation
27
+ response = model.generate_content("Hello")
28
+ return True, "API key is valid."
29
+
30
+ except Exception as e:
31
+ error_msg = str(e).lower()
32
+ if "api key not valid" in error_msg or "api_key_invalid" in error_msg:
33
+ return False, "Invalid API key. Please check your Gemini API key and try again."
34
+ elif "quota" in error_msg:
35
+ return False, "API quota exceeded. Please check your Gemini API usage limits."
36
+ elif "permission" in error_msg:
37
+ return False, "API key doesn't have required permissions. Please check your API key settings."
38
+ else:
39
+ return False, f"API key validation failed: {str(e)}"
40
+
41
  # Search the web for relevant information using DuckDuckGo
42
  def web_search(query: str, max_results: int = 10) -> List[Dict[str, str]]:
43
  """Search the web for relevant information using DuckDuckGo"""
44
  try:
45
  with DDGS() as ddgs:
46
+ # Add timeout and retry logic
47
+ results = []
48
+ for result in ddgs.text(query, max_results=max_results):
49
+ results.append(result)
50
+ if len(results) >= max_results:
51
+ break
52
  return results
53
  except Exception as e:
54
  print(f"Search error: {e}")
55
+ # Try with a simpler approach if the first fails
56
+ try:
57
+ with DDGS() as ddgs:
58
+ results = list(ddgs.text(query, max_results=min(max_results, 5)))
59
+ return results
60
+ except Exception as e2:
61
+ print(f"Retry search error: {e2}")
62
+ return []
63
 
64
  # Fetch and extract content from a URL
65
  def fetch_url_content(url: str) -> str:
 
128
  def generate_research_report(research_data: Dict[str, Any], gemini_api_key: str) -> str:
129
  """Generate a comprehensive research report using Gemini"""
130
  if not gemini_api_key:
131
+ return "Gemini API key is required to generate the report."
132
+
133
+ # Validate API key first
134
+ is_valid, validation_message = validate_api_key(gemini_api_key)
135
+ if not is_valid:
136
+ return f"❌ {validation_message}"
137
 
138
  try:
139
+ # Initialize Gemini (already configured in validation)
 
140
  model = genai.GenerativeModel('gemini-2.0-flash')
141
 
142
  prompt = f"""
 
159
  response = model.generate_content(prompt)
160
  return response.text
161
  except Exception as e:
162
+ error_msg = str(e).lower()
163
+ if "api key not valid" in error_msg or "api_key_invalid" in error_msg:
164
+ return "❌ Invalid API key. Please check your Gemini API key and try again."
165
+ elif "quota" in error_msg:
166
+ return "❌ API quota exceeded. Please check your Gemini API usage limits."
167
+ elif "permission" in error_msg:
168
+ return "❌ API key doesn't have required permissions. Please check your API key settings."
169
+ else:
170
+ return f"❌ Error generating report: {str(e)}"
171
 
172
  # Main research function
173
  def run_research(topic: str, gemini_api_key: str):
174
  """Run the complete research process"""
175
+ if not gemini_api_key.strip():
176
+ return "Please enter your Gemini API key.", None, gr.update(visible=False)
177
+
178
+ if not topic.strip():
179
+ return "❌ Please enter a research topic.", None, gr.update(visible=False)
180
 
181
+ # First validate the API key
182
+ is_valid, validation_message = validate_api_key(gemini_api_key)
183
+ if not is_valid:
184
+ return f"❌ {validation_message}", None, gr.update(visible=False)
185
 
186
  try:
187
  # Perform research
188
  research_data = perform_research(topic)
189
 
190
  if not research_data['sources']:
191
+ return "No relevant sources found. Please try a different search term.", None, gr.update(visible=False)
192
 
193
  # Generate report
194
  report = generate_research_report(research_data, gemini_api_key)
 
199
  return report, filename, gr.update(visible=True)
200
 
201
  except Exception as e:
202
+ error_msg = f"An error occurred: {str(e)}"
203
  return error_msg, None, gr.update(visible=False)
204
 
205
  # Gradio interface
 
208
  gr.Markdown("# 📘 Gemini Deep Research Agent")
209
  gr.Markdown("This agent performs deep research on any topic using Google's Gemini and DuckDuckGo search")
210
 
211
+ # Add API key help section
212
+ with gr.Accordion("🔑 How to get your Gemini API Key", open=False):
213
+ gr.Markdown("""
214
+ 1. Visit [Google AI Studio](https://aistudio.google.com/)
215
+ 2. Sign in with your Google account
216
+ 3. Click "Get API Key"
217
+ 4. Create a new API key
218
+ 5. Copy and paste it below
219
+
220
+ **Note:** Your API key should start with "AI" and be kept secure.
221
+ """)
222
+
223
  with gr.Row():
224
  with gr.Column(scale=1):
225
  gr.Markdown("## API Configuration")
226
  gemini_key = gr.Textbox(
227
  label="Gemini API Key",
228
  type="password",
229
+ placeholder="Enter your Gemini API key (starts with 'AI')",
230
+ info="Get your free API key from https://aistudio.google.com/"
231
+ )
232
+
233
+ # Add API key validation button
234
+ validate_btn = gr.Button("🔍 Validate API Key", size="sm")
235
+ validation_output = gr.Textbox(
236
+ label="Validation Status",
237
+ interactive=False,
238
+ visible=False
239
  )
240
 
241
  with gr.Column(scale=2):
242
  research_topic = gr.Textbox(
243
  label="Research Topic",
244
+ placeholder="e.g., Latest developments in AI, Climate change solutions, Cryptocurrency trends",
245
  lines=2
246
  )
247
 
248
+ research_btn = gr.Button("🚀 Start Research", variant="primary")
249
 
250
  output = gr.Markdown(
251
  label="Research Report",
 
253
  )
254
 
255
  download_btn = gr.DownloadButton(
256
+ "📥 Download Report",
257
  visible=False
258
  )
259
 
260
+ # API key validation function
261
+ def validate_key(api_key):
262
+ if not api_key:
263
+ return gr.update(visible=True, value="❌ Please enter an API key"), gr.update()
264
+
265
+ is_valid, message = validate_api_key(api_key)
266
+ if is_valid:
267
+ return gr.update(visible=True, value=f"✅ {message}"), gr.update()
268
+ else:
269
+ return gr.update(visible=True, value=f"❌ {message}"), gr.update()
270
+
271
+ # Set up the validation button
272
+ validate_btn.click(
273
+ fn=validate_key,
274
+ inputs=[gemini_key],
275
+ outputs=[validation_output, validation_output]
276
+ )
277
+
278
+ # Set up the research button
279
  research_btn.click(
280
  fn=run_research,
281
  inputs=[research_topic, gemini_key],
 
297
  # Main execution
298
  if __name__ == "__main__":
299
  demo = create_interface()
300
+ demo.launch()