murphynetworks commited on
Commit
e365088
·
1 Parent(s): 90d7802

feat: Improve web search reliability with API support

Browse files

- Add support for Serper.dev and SerpAPI search APIs
- Implement more robust search fallback mechanisms
- Update .env.example with search API key details
- Improve search and browser methods with better error handling

Files changed (2) hide show
  1. .env.example +11 -0
  2. tools/enhanced_web_search.py +228 -80
.env.example CHANGED
@@ -2,4 +2,15 @@
2
  OPENROUTER_API_KEY=your_openrouter_api_key_here
3
  OPENROUTER_MODEL=anthropic/claude-3-5-sonnet
4
 
 
 
 
 
 
 
 
 
 
 
 
5
  # Save this file as .env and add your actual API key
 
2
  OPENROUTER_API_KEY=your_openrouter_api_key_here
3
  OPENROUTER_MODEL=anthropic/claude-3-5-sonnet
4
 
5
+ # Submission details
6
+ USERNAME=your_username_here
7
+ CODE_LINK=your_github_repo_link_here
8
+
9
+ # Optional: OpenAI API key for audio transcription
10
+ # OPENAI_API_KEY=your_openai_api_key_here
11
+
12
+ # Optional: Search API keys
13
+ # SERPER_API_KEY=your_serper_api_key_here # https://serper.dev/
14
+ # SERPAPI_API_KEY=your_serpapi_api_key_here # https://serpapi.com/
15
+
16
  # Save this file as .env and add your actual API key
tools/enhanced_web_search.py CHANGED
@@ -11,6 +11,10 @@ import logging
11
  import concurrent.futures
12
  from bs4 import BeautifulSoup
13
  from urllib.parse import quote, urlparse, urlencode, parse_qs
 
 
 
 
14
 
15
  # Configure logging
16
  logger = logging.getLogger(__name__)
@@ -21,77 +25,207 @@ class EnhancedWebSearchTool:
21
  """
22
  def __init__(self):
23
  self.user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"
 
 
 
 
 
 
24
  self.search_engines = {
25
- "google": self._search_google,
26
  "duckduckgo": self._search_duckduckgo,
27
  "bing": self._search_bing,
28
  "wikipedia": self._search_wikipedia
29
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  self.session = requests.Session()
31
- self.session.headers.update({"User-Agent": self.user_agent})
 
 
 
 
 
 
32
 
33
- def search(self, query, max_results=5, search_engine="google"):
34
  """
35
  Search the web for information.
36
 
37
  Args:
38
  query (str): The search query
39
  max_results (int): Maximum number of results to return
40
- search_engine (str): Search engine to use ("google", "duckduckgo", "bing", "wikipedia")
41
 
42
  Returns:
43
  str: Formatted search results or error message
44
  """
 
 
 
 
45
  if search_engine not in self.search_engines:
46
- logger.warning(f"Unsupported search engine: {search_engine}, falling back to google")
47
- search_engine = "google"
 
 
 
48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  try:
50
- # Try the primary search engine
51
- logger.info(f"Searching with {search_engine} for: {query}")
52
- results = self.search_engines[search_engine](query, max_results)
53
-
54
- # If no results, try other engines automatically
55
- if not results.get("results"):
56
- logger.info(f"No results from {search_engine}, trying alternative engines")
57
- for engine in ["google", "duckduckgo", "bing", "wikipedia"]:
58
- if engine != search_engine:
59
- logger.info(f"Trying {engine} as fallback")
60
- retry_results = self.search_engines[engine](query, max_results)
61
- if retry_results.get("results"):
62
- logger.info(f"Found results with {engine}")
63
- results = retry_results
64
- results["search_engine"] = engine # Update the engine info
65
- break
66
 
67
- # Format the results
68
- formatted_results = self._format_results(results, query)
 
69
 
70
- # Check if we got meaningful results
71
- if "No results found" in formatted_results:
72
- # Try a modified query by removing some special characters or reformulating
73
- simplified_query = self._simplify_query(query)
74
- if simplified_query != query:
75
- logger.info(f"Trying simplified query: {simplified_query}")
76
- simplified_results = self.search_engines[search_engine](simplified_query, max_results)
77
- if simplified_results.get("results"):
78
- logger.info(f"Found results with simplified query")
79
- return self._format_results(simplified_results, simplified_query)
80
 
81
- return formatted_results
 
 
 
 
 
82
 
83
  except Exception as e:
84
- logger.error(f"Error searching for '{query}': {str(e)}", exc_info=True)
85
- # Try another engine as fallback
86
- fallback_engine = "duckduckgo" if search_engine != "duckduckgo" else "google"
87
- try:
88
- logger.info(f"Using fallback search engine {fallback_engine}")
89
- fallback_results = self.search_engines[fallback_engine](query, max_results)
90
- return self._format_results(fallback_results, query)
91
- except Exception as e2:
92
- logger.error(f"Fallback search also failed: {str(e2)}", exc_info=True)
93
- return f"Error searching for '{query}'. Multiple search engines failed."
94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  def _simplify_query(self, query):
96
  """Simplify a complex query to increase chances of finding results."""
97
  # Remove special characters that might be causing issues
@@ -528,49 +662,63 @@ class EnhancedWebSearchTool:
528
 
529
  def search_with_all_engines(self, query, max_results=3):
530
  """
531
- Search all available search engines and combine results.
532
 
533
  Args:
534
  query (str): The search query
535
- max_results (int): Maximum results per search engine
536
 
537
  Returns:
538
- str: Combined results from all search engines
539
  """
540
- all_results = []
541
- errors = []
542
-
543
- # Execute searches in parallel
544
- with concurrent.futures.ThreadPoolExecutor(max_workers=len(self.search_engines)) as executor:
545
- future_to_engine = {
546
- executor.submit(self._safe_search, engine_name, query, max_results): engine_name
547
- for engine_name in self.search_engines
548
- }
549
-
550
- for future in concurrent.futures.as_completed(future_to_engine):
551
- engine_name = future_to_engine[future]
552
- try:
553
- engine_results = future.result()
554
- if engine_results.get("results"):
555
- all_results.append({
556
- "engine": engine_name,
557
- "results": engine_results.get("results", [])
558
- })
559
- elif "error" in engine_results:
560
- errors.append(f"{engine_name}: {engine_results['error']}")
561
- except Exception as e:
562
- errors.append(f"{engine_name}: {str(e)}")
563
-
564
- if not all_results:
565
- error_msg = f"No results found for '{query}' across any search engines."
566
- if errors:
567
- error_msg += f" Errors encountered: {', '.join(errors)}"
568
- return error_msg
569
 
570
- # Format the combined results
571
- formatted_results = f"Combined search results for '{query}':\n\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
572
 
573
- for engine_results in all_results:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
574
  engine_name = engine_results["engine"].title()
575
  formatted_results += f"=== Results from {engine_name} ===\n\n"
576
 
 
11
  import concurrent.futures
12
  from bs4 import BeautifulSoup
13
  from urllib.parse import quote, urlparse, urlencode, parse_qs
14
+ from dotenv import load_dotenv
15
+
16
+ # Load environment variables
17
+ load_dotenv()
18
 
19
  # Configure logging
20
  logger = logging.getLogger(__name__)
 
25
  """
26
  def __init__(self):
27
  self.user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"
28
+
29
+ # Get API keys from environment
30
+ self.serper_api_key = os.getenv("SERPER_API_KEY")
31
+ self.serpapi_api_key = os.getenv("SERPAPI_API_KEY")
32
+
33
+ # Set up search engines - use API methods if keys are available
34
  self.search_engines = {
35
+ "google": self._search_google_api if self.serper_api_key else self._search_google,
36
  "duckduckgo": self._search_duckduckgo,
37
  "bing": self._search_bing,
38
  "wikipedia": self._search_wikipedia
39
  }
40
+
41
+ # Add API-based search engines if keys are available
42
+ if self.serper_api_key:
43
+ self.search_engines["serper"] = self._search_serper_api
44
+ logger.info("Serper API enabled for web search")
45
+
46
+ if self.serpapi_api_key:
47
+ self.search_engines["serpapi"] = self._search_serpapi
48
+ logger.info("SerpAPI enabled for web search")
49
+
50
+ # Configure preferred search order based on what's available
51
+ self.search_order = []
52
+ if self.serper_api_key:
53
+ self.search_order.append("serper")
54
+ if self.serpapi_api_key:
55
+ self.search_order.append("serpapi")
56
+ self.search_order.extend(["google", "duckduckgo", "bing", "wikipedia"])
57
+
58
+ # Create session with reasonable headers
59
  self.session = requests.Session()
60
+ self.session.headers.update({
61
+ "User-Agent": self.user_agent,
62
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
63
+ "Accept-Language": "en-US,en;q=0.5",
64
+ "Connection": "keep-alive",
65
+ "Upgrade-Insecure-Requests": "1"
66
+ })
67
 
68
+ def search(self, query, max_results=5, search_engine=None):
69
  """
70
  Search the web for information.
71
 
72
  Args:
73
  query (str): The search query
74
  max_results (int): Maximum number of results to return
75
+ search_engine (str): Search engine to use (None for automatic selection)
76
 
77
  Returns:
78
  str: Formatted search results or error message
79
  """
80
+ # If no search engine specified, use the first one in our preferred order
81
+ if search_engine is None:
82
+ search_engine = self.search_order[0] if self.search_order else "google"
83
+
84
  if search_engine not in self.search_engines:
85
+ logger.warning(f"Unsupported search engine: {search_engine}, falling back to preferred order")
86
+ search_engine = self.search_order[0] if self.search_order else "google"
87
+
88
+ # Record all errors we encounter
89
+ all_errors = []
90
 
91
+ # Try the search using our preferred order
92
+ for engine in [search_engine] + [e for e in self.search_order if e != search_engine]:
93
+ try:
94
+ logger.info(f"Searching with {engine} for: {query}")
95
+ results = self.search_engines[engine](query, max_results)
96
+
97
+ if results.get("results"):
98
+ # We found results, format and return them
99
+ logger.info(f"Found results with {engine}")
100
+ formatted_results = self._format_results(results, query)
101
+
102
+ # Check if meaningful results were found
103
+ if "No results found" not in formatted_results:
104
+ return formatted_results
105
+ except Exception as e:
106
+ error_msg = f"Error with {engine} search: {str(e)}"
107
+ logger.warning(error_msg)
108
+ all_errors.append(error_msg)
109
+ continue # Try the next engine
110
+
111
+ # If we reach here, we haven't found results with any engine
112
+ # Try with a simplified query
113
+ simplified_query = self._simplify_query(query)
114
+ if simplified_query != query:
115
+ logger.info(f"Trying simplified query: {simplified_query}")
116
+ # Start again with the preferred search order
117
+ for engine in self.search_order:
118
+ try:
119
+ results = self.search_engines[engine](simplified_query, max_results)
120
+ if results.get("results"):
121
+ logger.info(f"Found results with {engine} using simplified query")
122
+ return self._format_results(results, simplified_query)
123
+ except Exception as e:
124
+ logger.warning(f"Error with {engine} simplified search: {str(e)}")
125
+ continue # Try the next engine
126
+
127
+ # If we still have no results, return a helpful error message
128
+ logger.error(f"All search engines failed for query: {query}")
129
+ return f"No results found for '{query}'. Multiple search engines were tried but none returned relevant information."
130
+
131
+ def _search_serper_api(self, query, max_results=5):
132
+ """
133
+ Search using the Serper.dev API (Google search API).
134
+
135
+ Args:
136
+ query (str): Search query
137
+ max_results (int): Maximum number of results to return
138
+
139
+ Returns:
140
+ dict: Dictionary with search results
141
+ """
142
  try:
143
+ url = "https://google.serper.dev/search"
144
+ headers = {
145
+ "X-API-KEY": self.serper_api_key,
146
+ "Content-Type": "application/json"
147
+ }
148
+ payload = {
149
+ "q": query,
150
+ "num": max_results
151
+ }
 
 
 
 
 
 
 
152
 
153
+ response = requests.post(url, headers=headers, json=payload, timeout=10)
154
+ response.raise_for_status()
155
+ data = response.json()
156
 
157
+ # Extract organic results
158
+ results = []
159
+ if "organic" in data:
160
+ for item in data["organic"][:max_results]:
161
+ results.append({
162
+ "title": item.get("title", ""),
163
+ "link": item.get("link", ""),
164
+ "snippet": item.get("snippet", "")
165
+ })
 
166
 
167
+ return {
168
+ "query": query,
169
+ "results": results,
170
+ "search_engine": "serper",
171
+ "total_results": len(results)
172
+ }
173
 
174
  except Exception as e:
175
+ logger.error(f"Error with Serper API search: {str(e)}")
176
+ raise
 
 
 
 
 
 
 
 
177
 
178
+ def _search_serpapi(self, query, max_results=5):
179
+ """
180
+ Search using the SerpAPI.
181
+
182
+ Args:
183
+ query (str): Search query
184
+ max_results (int): Maximum number of results to return
185
+
186
+ Returns:
187
+ dict: Dictionary with search results
188
+ """
189
+ try:
190
+ params = {
191
+ "q": query,
192
+ "api_key": self.serpapi_api_key,
193
+ "num": max_results
194
+ }
195
+
196
+ url = f"https://serpapi.com/search?{urlencode(params)}"
197
+ response = requests.get(url, timeout=10)
198
+ response.raise_for_status()
199
+ data = response.json()
200
+
201
+ # Extract organic results
202
+ results = []
203
+ if "organic_results" in data:
204
+ for item in data["organic_results"][:max_results]:
205
+ results.append({
206
+ "title": item.get("title", ""),
207
+ "link": item.get("link", ""),
208
+ "snippet": item.get("snippet", "")
209
+ })
210
+
211
+ return {
212
+ "query": query,
213
+ "results": results,
214
+ "search_engine": "serpapi",
215
+ "total_results": len(results)
216
+ }
217
+
218
+ except Exception as e:
219
+ logger.error(f"Error with SerpAPI search: {str(e)}")
220
+ raise
221
+
222
+ def _search_google_api(self, query, max_results=5):
223
+ """
224
+ Search using the Serper API specifically for Google results.
225
+ This is an alias for _search_serper_api for compatibility.
226
+ """
227
+ return self._search_serper_api(query, max_results)
228
+
229
  def _simplify_query(self, query):
230
  """Simplify a complex query to increase chances of finding results."""
231
  # Remove special characters that might be causing issues
 
662
 
663
  def search_with_all_engines(self, query, max_results=3):
664
  """
665
+ Search with all available engines and combine results.
666
 
667
  Args:
668
  query (str): The search query
669
+ max_results (int): Maximum number of results per engine
670
 
671
  Returns:
672
+ str: Combined search results
673
  """
674
+ combined_results = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
675
 
676
+ # Use our preferred search order
677
+ for engine in self.search_order:
678
+ try:
679
+ logger.info(f"Searching with {engine} for: {query}")
680
+ results = self.search_engines[engine](query, max_results)
681
+
682
+ if results.get("results"):
683
+ engine_results = results["results"][:max_results]
684
+
685
+ # Add source engine to each result
686
+ for result in engine_results:
687
+ result["engine"] = engine
688
+
689
+ combined_results.extend(engine_results)
690
+ except Exception as e:
691
+ logger.warning(f"Error with {engine} search: {str(e)}")
692
 
693
+ # If we found results, format them
694
+ if combined_results:
695
+ # Sort by relevance (assuming first results from each engine are more relevant)
696
+ # and remove duplicates by URL
697
+ seen_urls = set()
698
+ unique_results = []
699
+
700
+ for result in combined_results:
701
+ url = result.get("link", "")
702
+ if url and url not in seen_urls:
703
+ seen_urls.add(url)
704
+ unique_results.append(result)
705
+
706
+ # Format the results nicely
707
+ formatted_results = f"Combined results for '{query}' from multiple search engines:\n\n"
708
+
709
+ for i, result in enumerate(unique_results[:max_results*2], 1):
710
+ title = result.get("title", "No title")
711
+ link = result.get("link", "No URL")
712
+ snippet = result.get("snippet", "No description")
713
+ engine = result.get("engine", "unknown")
714
+
715
+ formatted_results += f"{i}. {title} [{engine}]\n"
716
+ formatted_results += f" URL: {link}\n"
717
+ formatted_results += f" Summary: {snippet}\n\n"
718
+
719
+ return formatted_results
720
+ else:
721
+ return f"No results found for '{query}' across any search engines."
722
  engine_name = engine_results["engine"].title()
723
  formatted_results += f"=== Results from {engine_name} ===\n\n"
724