Kackle commited on
Commit
1d0f146
·
verified ·
1 Parent(s): 60f4659

Update gemini_agent.py

Browse files
Files changed (1) hide show
  1. gemini_agent.py +43 -40
gemini_agent.py CHANGED
@@ -125,8 +125,9 @@ class GeminiAgent:
125
  async def _google_search(self, query: str, num_results: int = 5, exact_terms: str = None, site_restrict: str = None) -> str:
126
  """Perform a Google search using the Custom Search API with enhanced options"""
127
  if not self.google_search_api_key or not self.google_search_cx:
128
- print("Google Search API key or CX not configured, falling back to DuckDuckGo")
129
- return self.ddg_tool.run(query)
 
130
 
131
  try:
132
  url = "https://www.googleapis.com/customsearch/v1"
@@ -145,15 +146,16 @@ class GeminiAgent:
145
  if site_restrict:
146
  params['siteSearch'] = site_restrict
147
 
148
- response = requests.get(url, params=params)
 
149
  if response.status_code != 200:
150
  print(f"Google Search API error: {response.status_code}")
151
- return self.ddg_tool.run(query) # Fall back to DuckDuckGo
152
 
153
  results = response.json()
154
  if 'items' not in results:
155
  print("No search results found")
156
- return self.ddg_tool.run(query) # Fall back to DuckDuckGo
157
 
158
  # Extract and format search results
159
  formatted_results = ""
@@ -176,9 +178,13 @@ class GeminiAgent:
176
 
177
  return formatted_results
178
 
 
 
 
 
179
  except Exception as e:
180
  print(f"Google Search API error: {str(e)}")
181
- return self.ddg_tool.run(query) # Fall back to DuckDuckGo
182
 
183
  async def _handle_actor_show_question(self, question: str) -> str:
184
  """Handle questions about actors, TV shows, and movies with enhanced search"""
@@ -258,55 +264,52 @@ If the answer is a person's name, provide ONLY their first name as requested."""
258
  async def _multi_search(self, queries: list, num_results: int = 5, include_sites: list = None) -> str:
259
  """Perform multiple searches and combine the results with enhanced options"""
260
  combined_results = ""
 
261
 
262
- # Define authoritative sites for different domains
263
  authoritative_sites = {
264
- "music": ["grammy.org", "billboard.com", "allmusic.com", "musicbrainz.org"],
265
- "competition": ["wikipedia.org", "britannica.com"],
266
- "awards": ["nobelprize.org", "pulitzer.org", "oscars.org"],
267
- "classical": ["classicalmusic.org", "gramophone.co.uk", "medici.tv"]
268
  }
269
 
270
- # Process each query
271
- for i, query in enumerate(queries):
272
- print(f"Searching for query {i+1}/{len(queries)}: {query[:50]}...")
 
273
  try:
274
  # Standard search
275
  result = await self._google_search(query, num_results)
276
- if result:
277
  combined_results += f"=== Results for query: {query} ===\n{result}\n\n"
 
278
 
279
- # If specific sites are provided, search those too
280
- if include_sites:
281
- for site in include_sites:
282
- site_result = await self._google_search(query, num_results=3, site_restrict=site)
283
- if site_result and "no results" not in site_result.lower():
284
- combined_results += f"=== Results from {site} for: {query} ===\n{site_result}\n\n"
285
-
286
- # For competition questions, try some authoritative sites
287
  if "competition" in query.lower() or "award" in query.lower() or "prize" in query.lower():
288
- for site in authoritative_sites["competition"] + authoritative_sites["awards"]:
289
- site_result = await self._google_search(query, num_results=2, site_restrict=site)
290
- if site_result and "no results" not in site_result.lower():
291
- combined_results += f"=== Results from {site} for: {query} ===\n{site_result}\n\n"
292
 
293
- # For classical music questions, try classical music sites
294
- if "classical" in query.lower() or "conductor" in query.lower() or "orchestra" in query.lower():
295
- for site in authoritative_sites["classical"]:
296
- site_result = await self._google_search(query, num_results=2, site_restrict=site)
297
- if site_result and "no results" not in site_result.lower():
298
- combined_results += f"=== Results from {site} for: {query} ===\n{site_result}\n\n"
299
-
300
- # Try exact term matching for key entities
301
- key_terms = self._extract_key_terms(query)
302
- if key_terms:
303
- exact_result = await self._google_search(query, num_results=3, exact_terms=key_terms)
304
- if exact_result and "no results" not in exact_result.lower():
305
- combined_results += f"=== Results with exact match for '{key_terms}' ===\n{exact_result}\n\n"
306
 
307
  except Exception as e:
308
  print(f"Search failed for query {i+1}: {e}")
309
 
 
 
 
 
310
  return combined_results
311
 
312
  def _extract_key_terms(self, query: str) -> str:
 
125
  async def _google_search(self, query: str, num_results: int = 5, exact_terms: str = None, site_restrict: str = None) -> str:
126
  """Perform a Google search using the Custom Search API with enhanced options"""
127
  if not self.google_search_api_key or not self.google_search_cx:
128
+ print("Google Search API key or CX not configured, using direct search")
129
+ # Instead of falling back to DuckDuckGo, return a simple message
130
+ return f"Search for: {query} (API keys not configured)"
131
 
132
  try:
133
  url = "https://www.googleapis.com/customsearch/v1"
 
146
  if site_restrict:
147
  params['siteSearch'] = site_restrict
148
 
149
+ # Add timeout to prevent hanging
150
+ response = requests.get(url, params=params, timeout=10)
151
  if response.status_code != 200:
152
  print(f"Google Search API error: {response.status_code}")
153
+ return f"Search failed for: {query} (Status code: {response.status_code})"
154
 
155
  results = response.json()
156
  if 'items' not in results:
157
  print("No search results found")
158
+ return f"No search results found for: {query}"
159
 
160
  # Extract and format search results
161
  formatted_results = ""
 
178
 
179
  return formatted_results
180
 
181
+ except requests.exceptions.Timeout:
182
+ print(f"Google Search API timeout for query: {query}")
183
+ return f"Search timed out for: {query}"
184
+
185
  except Exception as e:
186
  print(f"Google Search API error: {str(e)}")
187
+ return f"Search error for: {query} ({str(e)})"
188
 
189
  async def _handle_actor_show_question(self, question: str) -> str:
190
  """Handle questions about actors, TV shows, and movies with enhanced search"""
 
264
  async def _multi_search(self, queries: list, num_results: int = 5, include_sites: list = None) -> str:
265
  """Perform multiple searches and combine the results with enhanced options"""
266
  combined_results = ""
267
+ success_count = 0
268
 
269
+ # Define authoritative sites for different domains - just use Wikipedia for now
270
  authoritative_sites = {
271
+ "competition": ["wikipedia.org"],
272
+ "awards": ["wikipedia.org"]
 
 
273
  }
274
 
275
+ # Process each query - limit to max 3 queries to avoid timeouts
276
+ max_queries = min(3, len(queries))
277
+ for i, query in enumerate(queries[:max_queries]):
278
+ print(f"Searching for query {i+1}/{max_queries}: {query[:50]}...")
279
  try:
280
  # Standard search
281
  result = await self._google_search(query, num_results)
282
+ if result and not result.startswith("Search"):
283
  combined_results += f"=== Results for query: {query} ===\n{result}\n\n"
284
+ success_count += 1
285
 
286
+ # If we already have good results, don't do site-specific searches
287
+ if success_count >= 2:
288
+ continue
289
+
290
+ # For competition questions, try Wikipedia
 
 
 
291
  if "competition" in query.lower() or "award" in query.lower() or "prize" in query.lower():
292
+ site_result = await self._google_search(query, num_results=2, site_restrict="wikipedia.org")
293
+ if site_result and not site_result.startswith("Search"):
294
+ combined_results += f"=== Results from wikipedia.org for: {query} ===\n{site_result}\n\n"
295
+ success_count += 1
296
 
297
+ # Try exact term matching for key entities if we still need results
298
+ if success_count < 2:
299
+ key_terms = self._extract_key_terms(query)
300
+ if key_terms:
301
+ exact_result = await self._google_search(query, num_results=3, exact_terms=key_terms)
302
+ if exact_result and not exact_result.startswith("Search"):
303
+ combined_results += f"=== Results with exact match for '{key_terms}' ===\n{exact_result}\n\n"
304
+ success_count += 1
 
 
 
 
 
305
 
306
  except Exception as e:
307
  print(f"Search failed for query {i+1}: {e}")
308
 
309
+ # If we didn't get any results, add a fallback message
310
+ if not combined_results:
311
+ combined_results = "No search results found. Using model knowledge to answer the question."
312
+
313
  return combined_results
314
 
315
  def _extract_key_terms(self, query: str) -> str: