Final_Assignment_Template / tools /enhanced_web_search.py
murphynetworks's picture
feat: Improve web search reliability with API support
e365088
Raw History Blame Contribute Delete
37.2 kB
#!/usr/bin/env python3
"""
Enhanced web search tool with multiple search strategies and advanced scraping.
"""
import os
import re
import json
import requests
import time
import logging
import concurrent.futures
from bs4 import BeautifulSoup
from urllib.parse import quote, urlparse, urlencode, parse_qs
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Configure logging
logger = logging.getLogger(__name__)
class EnhancedWebSearchTool:
"""
An advanced web search tool that uses multiple search engines and strategies.
"""
def __init__(self):
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"
# Get API keys from environment
self.serper_api_key = os.getenv("SERPER_API_KEY")
self.serpapi_api_key = os.getenv("SERPAPI_API_KEY")
# Set up search engines - use API methods if keys are available
self.search_engines = {
"google": self._search_google_api if self.serper_api_key else self._search_google,
"duckduckgo": self._search_duckduckgo,
"bing": self._search_bing,
"wikipedia": self._search_wikipedia
}
# Add API-based search engines if keys are available
if self.serper_api_key:
self.search_engines["serper"] = self._search_serper_api
logger.info("Serper API enabled for web search")
if self.serpapi_api_key:
self.search_engines["serpapi"] = self._search_serpapi
logger.info("SerpAPI enabled for web search")
# Configure preferred search order based on what's available
self.search_order = []
if self.serper_api_key:
self.search_order.append("serper")
if self.serpapi_api_key:
self.search_order.append("serpapi")
self.search_order.extend(["google", "duckduckgo", "bing", "wikipedia"])
# Create session with reasonable headers
self.session = requests.Session()
self.session.headers.update({
"User-Agent": self.user_agent,
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.5",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1"
})
def search(self, query, max_results=5, search_engine=None):
"""
Search the web for information.
Args:
query (str): The search query
max_results (int): Maximum number of results to return
search_engine (str): Search engine to use (None for automatic selection)
Returns:
str: Formatted search results or error message
"""
# If no search engine specified, use the first one in our preferred order
if search_engine is None:
search_engine = self.search_order[0] if self.search_order else "google"
if search_engine not in self.search_engines:
logger.warning(f"Unsupported search engine: {search_engine}, falling back to preferred order")
search_engine = self.search_order[0] if self.search_order else "google"
# Record all errors we encounter
all_errors = []
# Try the search using our preferred order
for engine in [search_engine] + [e for e in self.search_order if e != search_engine]:
try:
logger.info(f"Searching with {engine} for: {query}")
results = self.search_engines[engine](query, max_results)
if results.get("results"):
# We found results, format and return them
logger.info(f"Found results with {engine}")
formatted_results = self._format_results(results, query)
# Check if meaningful results were found
if "No results found" not in formatted_results:
return formatted_results
except Exception as e:
error_msg = f"Error with {engine} search: {str(e)}"
logger.warning(error_msg)
all_errors.append(error_msg)
continue # Try the next engine
# If we reach here, we haven't found results with any engine
# Try with a simplified query
simplified_query = self._simplify_query(query)
if simplified_query != query:
logger.info(f"Trying simplified query: {simplified_query}")
# Start again with the preferred search order
for engine in self.search_order:
try:
results = self.search_engines[engine](simplified_query, max_results)
if results.get("results"):
logger.info(f"Found results with {engine} using simplified query")
return self._format_results(results, simplified_query)
except Exception as e:
logger.warning(f"Error with {engine} simplified search: {str(e)}")
continue # Try the next engine
# If we still have no results, return a helpful error message
logger.error(f"All search engines failed for query: {query}")
return f"No results found for '{query}'. Multiple search engines were tried but none returned relevant information."
def _search_serper_api(self, query, max_results=5):
"""
Search using the Serper.dev API (Google search API).
Args:
query (str): Search query
max_results (int): Maximum number of results to return
Returns:
dict: Dictionary with search results
"""
try:
url = "https://google.serper.dev/search"
headers = {
"X-API-KEY": self.serper_api_key,
"Content-Type": "application/json"
}
payload = {
"q": query,
"num": max_results
}
response = requests.post(url, headers=headers, json=payload, timeout=10)
response.raise_for_status()
data = response.json()
# Extract organic results
results = []
if "organic" in data:
for item in data["organic"][:max_results]:
results.append({
"title": item.get("title", ""),
"link": item.get("link", ""),
"snippet": item.get("snippet", "")
})
return {
"query": query,
"results": results,
"search_engine": "serper",
"total_results": len(results)
}
except Exception as e:
logger.error(f"Error with Serper API search: {str(e)}")
raise
def _search_serpapi(self, query, max_results=5):
"""
Search using the SerpAPI.
Args:
query (str): Search query
max_results (int): Maximum number of results to return
Returns:
dict: Dictionary with search results
"""
try:
params = {
"q": query,
"api_key": self.serpapi_api_key,
"num": max_results
}
url = f"https://serpapi.com/search?{urlencode(params)}"
response = requests.get(url, timeout=10)
response.raise_for_status()
data = response.json()
# Extract organic results
results = []
if "organic_results" in data:
for item in data["organic_results"][:max_results]:
results.append({
"title": item.get("title", ""),
"link": item.get("link", ""),
"snippet": item.get("snippet", "")
})
return {
"query": query,
"results": results,
"search_engine": "serpapi",
"total_results": len(results)
}
except Exception as e:
logger.error(f"Error with SerpAPI search: {str(e)}")
raise
def _search_google_api(self, query, max_results=5):
"""
Search using the Serper API specifically for Google results.
This is an alias for _search_serper_api for compatibility.
"""
return self._search_serper_api(query, max_results)
def _simplify_query(self, query):
"""Simplify a complex query to increase chances of finding results."""
# Remove special characters that might be causing issues
simplified = re.sub(r'[^\w\s]', ' ', query)
simplified = re.sub(r'\s+', ' ', simplified).strip()
# Remove very specific dates or numbers if present
simplified = re.sub(r'\b\d{1,2}/\d{1,2}/\d{2,4}\b', '', simplified)
# If query is about a person, try to extract just the name
if 'who' in query.lower():
name_match = re.search(r'([A-Z][a-z]+ [A-Z][a-z]+)', query)
if name_match:
return name_match.group(1)
# If query is very long, take just the key parts
if len(simplified.split()) > 10:
# Extract key nouns and names (capitalized words are often important)
important_words = re.findall(r'\b[A-Z][a-z]+\b', query)
if len(important_words) >= 2:
return ' '.join(important_words)
# Add "wikipedia" to the query if it might be an encyclopedia question
if any(word in query.lower() for word in ['who', 'what', 'when', 'where', 'why']):
if 'wikipedia' not in query.lower():
return simplified + " wikipedia"
return simplified if simplified != query else query
def _search_google(self, query, max_results=5):
"""Perform a Google search."""
try:
url = f"https://www.google.com/search?q={quote(query)}"
try:
response = self.session.get(url, timeout=10)
response.raise_for_status()
except requests.exceptions.RequestException as e:
logger.warning(f"Google search request failed: {str(e)}")
# Try with different parameters
url = f"https://www.google.com/search?{urlencode({'q': query})}"
response = self.session.get(url, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
search_results = []
# Try multiple CSS selectors for Google results (they change frequently)
selectors = [
".tF2Cxc", ".g", ".Gx5Zad", "div.iDjcJe", "div.yuRUbf",
"div[data-sokoban-container]", ".v5yQqb"
]
for selector in selectors:
results_found = False
for result in soup.select(selector):
# Try different patterns to extract title, link, and snippet
title_elem = (
result.select_one(".DKV0Md") or
result.select_one("h3") or
result.select_one(".LC20lb")
)
link_elem = result.select_one("a")
snippet_elem = (
result.select_one(".VwiC3b") or
result.select_one(".st") or
result.select_one(".UiGGAb") or
result.select_one(".lEBKkf")
)
title = title_elem.text.strip() if title_elem else ""
link = link_elem["href"] if link_elem and "href" in link_elem.attrs else ""
# Clean up the link (remove Google redirects)
if link.startswith("/url?") or "google.com/url" in link:
try:
query_params = parse_qs(urlparse(link).query)
if 'q' in query_params and query_params['q']:
link = query_params['q'][0]
except:
pass
snippet = snippet_elem.text.strip() if snippet_elem else ""
if title and link and 'google.com/search' not in link:
search_results.append({
"title": title,
"link": link,
"snippet": snippet
})
results_found = True
if results_found:
break
# If still no results, try looking for featured snippets
if not search_results:
featured_snippet = soup.select_one(".hgKElc") or soup.select_one(".kno-rdesc")
if featured_snippet:
search_results.append({
"title": "Featured Snippet",
"link": url,
"snippet": featured_snippet.text.strip()
})
return {
"search_engine": "google",
"query": query,
"results": search_results[:max_results]
}
except Exception as e:
logger.error(f"Error in Google search: {str(e)}", exc_info=True)
return {
"search_engine": "google",
"query": query,
"error": str(e),
"results": []
}
def _search_duckduckgo(self, query, max_results=5):
"""Perform a DuckDuckGo search."""
try:
url = f"https://html.duckduckgo.com/html/?q={quote(query)}"
response = self.session.get(url, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
search_results = []
# Extract search results from DuckDuckGo
for result in soup.select(".result"):
title_elem = result.select_one(".result__title")
link_elem = result.select_one(".result__url")
snippet_elem = result.select_one(".result__snippet")
title = title_elem.text.strip() if title_elem else ""
link = link_elem.text.strip() if link_elem else ""
snippet = snippet_elem.text.strip() if snippet_elem else ""
# Get actual URL from href
if title_elem and title_elem.find("a"):
href = title_elem.find("a").get("href", "")
if href:
try:
# DuckDuckGo uses redirects, extract the actual URL
# Parse parameters like 'uddg='
if "?" in href:
params = dict(pair.split('=') for pair in href.split('?')[1].split('&') if '=' in pair)
if 'uddg' in params:
link = params['uddg']
except Exception as e:
logger.debug(f"Error parsing DuckDuckGo URL: {str(e)}")
if title and (link or href):
final_link = link if link else href
search_results.append({
"title": title,
"link": final_link,
"snippet": snippet
})
# If no results found with the main approach, try an alternative approach
if not search_results:
for result in soup.select(".links_main"):
title_elem = result.select_one("a")
snippet_elem = result.select_one(".result__snippet")
if title_elem:
title = title_elem.text.strip()
href = title_elem.get("href", "")
snippet = snippet_elem.text.strip() if snippet_elem else ""
if title and href:
search_results.append({
"title": title,
"link": href,
"snippet": snippet
})
return {
"search_engine": "duckduckgo",
"query": query,
"results": search_results[:max_results]
}
except Exception as e:
logger.error(f"Error in DuckDuckGo search: {str(e)}", exc_info=True)
return {
"search_engine": "duckduckgo",
"query": query,
"error": str(e),
"results": []
}
def _search_bing(self, query, max_results=5):
"""Perform a Bing search."""
try:
url = f"https://www.bing.com/search?q={quote(query)}"
response = self.session.get(url, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
search_results = []
# Extract search results from Bing
for result in soup.select(".b_algo"):
title_elem = result.select_one("h2")
link_elem = result.select_one("a")
snippet_elem = result.select_one(".b_caption p") or result.select_one(".b_snippet")
title = title_elem.text.strip() if title_elem else ""
link = link_elem["href"] if link_elem and "href" in link_elem.attrs else ""
snippet = snippet_elem.text.strip() if snippet_elem else ""
if title and link:
search_results.append({
"title": title,
"link": link,
"snippet": snippet
})
# If no results found with the main approach, try an alternative approach
if not search_results:
for result in soup.select("#b_results > li"):
title_elem = result.select_one("h2 a")
if title_elem:
title = title_elem.text.strip()
href = title_elem.get("href", "")
# Try to find the snippet in various locations
snippet_elem = (
result.select_one(".b_caption p") or
result.select_one(".b_snippet") or
result.select_one(".b_richcard") or
result.select_one(".b_vPanel")
)
snippet = snippet_elem.text.strip() if snippet_elem else ""
if title and href:
search_results.append({
"title": title,
"link": href,
"snippet": snippet
})
return {
"search_engine": "bing",
"query": query,
"results": search_results[:max_results]
}
except Exception as e:
logger.error(f"Error in Bing search: {str(e)}", exc_info=True)
return {
"search_engine": "bing",
"query": query,
"error": str(e),
"results": []
}
def _search_wikipedia(self, query, max_results=5):
"""Perform a Wikipedia search."""
try:
# First search for Wikipedia articles
search_url = f"https://en.wikipedia.org/w/api.php?action=opensearch&search={quote(query)}&limit={max_results}&namespace=0&format=json"
response = self.session.get(search_url, timeout=10)
response.raise_for_status()
data = response.json()
if len(data) < 4:
return {
"search_engine": "wikipedia",
"query": query,
"error": "Invalid response format from Wikipedia API",
"results": []
}
titles = data[1]
links = data[3]
if not titles:
# Try with a simplified query
simplified_query = re.sub(r'[^\w\s]', ' ', query)
simplified_query = re.sub(r'\s+', ' ', simplified_query).strip()
if simplified_query != query:
search_url = f"https://en.wikipedia.org/w/api.php?action=opensearch&search={quote(simplified_query)}&limit={max_results}&namespace=0&format=json"
response = self.session.get(search_url, timeout=10)
response.raise_for_status()
data = response.json()
if len(data) >= 4:
titles = data[1]
links = data[3]
search_results = []
# Only use ThreadPoolExecutor if we have results to process
if titles and len(titles) > 0:
# Process search results in parallel for speed
with concurrent.futures.ThreadPoolExecutor(max_workers=min(5, max(1, len(titles)))) as executor:
future_to_idx = {
executor.submit(self._get_wikipedia_snippet, title, link): i
for i, (title, link) in enumerate(zip(titles, links)) if i < max_results
}
for future in concurrent.futures.as_completed(future_to_idx):
result = future.result()
if result:
search_results.append(result)
# Sort results back to original order since they might come back in any order
search_results.sort(key=lambda x: links.index(x['link']) if x['link'] in links else 999)
return {
"search_engine": "wikipedia",
"query": query,
"results": search_results[:max_results]
}
except Exception as e:
logger.error(f"Error in Wikipedia search: {str(e)}", exc_info=True)
# Try direct article lookup as fallback
try:
# Format query to look like a Wikipedia title
direct_title = query.strip().replace(' ', '_')
article_url = f"https://en.wikipedia.org/wiki/{quote(direct_title)}"
article_response = self.session.get(article_url, timeout=10)
if article_response.status_code == 200:
# Successfully found a direct article
soup = BeautifulSoup(article_response.text, 'html.parser')
title = soup.select_one("#firstHeading").text.strip() if soup.select_one("#firstHeading") else direct_title
# Get the first paragraph
paragraphs = soup.select("#mw-content-text p")
snippet = ""
for p in paragraphs:
if p.text.strip():
snippet = p.text.strip()
break
return {
"search_engine": "wikipedia",
"query": query,
"results": [{
"title": title,
"link": article_url,
"snippet": snippet[:250] + "..." if len(snippet) > 250 else snippet
}]
}
except Exception as e2:
logger.error(f"Wikipedia direct lookup also failed: {str(e2)}")
return {
"search_engine": "wikipedia",
"query": query,
"error": str(e),
"results": []
}
def _get_wikipedia_snippet(self, title, link):
"""Helper method to get a snippet from a Wikipedia article."""
try:
# Extract page title from URL
page_title = link.split("/wiki/")[1] if "/wiki/" in link else title
# Get article snippet
snippet_url = f"https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro=true&explaintext=true&titles={page_title}&format=json"
snippet_response = self.session.get(snippet_url, timeout=5)
snippet_data = snippet_response.json()
# Extract snippet from response
pages = snippet_data.get("query", {}).get("pages", {})
snippet = ""
for page_id in pages:
snippet = pages[page_id].get("extract", "")
break
return {
"title": title,
"link": link,
"snippet": snippet[:250] + "..." if len(snippet) > 250 else snippet
}
except Exception as e:
logger.warning(f"Error getting Wikipedia snippet for {title}: {str(e)}")
return {
"title": title,
"link": link,
"snippet": "Error retrieving article snippet."
}
def _format_results(self, results, query):
"""Format search results into a readable string."""
search_engine = results.get("search_engine", "unknown")
if "error" in results:
return f"Error searching for '{query}' on {search_engine}: {results['error']}"
search_results = results.get("results", [])
if not search_results:
return f"No results found for '{query}' on {search_engine}."
formatted_results = f"Search results for '{query}' from {search_engine.title()}:\n\n"
for i, result in enumerate(search_results, 1):
formatted_results += f"{i}. {result['title']}\n"
formatted_results += f" URL: {result['link']}\n"
if result.get('snippet'):
# Clean up the snippet to make it more readable
snippet = result['snippet']
# Remove excessive whitespace
snippet = re.sub(r'\s+', ' ', snippet).strip()
# Remove HTML tags that might have been missed
snippet = re.sub(r'<[^>]+>', '', snippet)
formatted_results += f" Summary: {snippet}\n"
formatted_results += "\n"
return formatted_results
def search_with_all_engines(self, query, max_results=3):
"""
Search with all available engines and combine results.
Args:
query (str): The search query
max_results (int): Maximum number of results per engine
Returns:
str: Combined search results
"""
combined_results = []
# Use our preferred search order
for engine in self.search_order:
try:
logger.info(f"Searching with {engine} for: {query}")
results = self.search_engines[engine](query, max_results)
if results.get("results"):
engine_results = results["results"][:max_results]
# Add source engine to each result
for result in engine_results:
result["engine"] = engine
combined_results.extend(engine_results)
except Exception as e:
logger.warning(f"Error with {engine} search: {str(e)}")
# If we found results, format them
if combined_results:
# Sort by relevance (assuming first results from each engine are more relevant)
# and remove duplicates by URL
seen_urls = set()
unique_results = []
for result in combined_results:
url = result.get("link", "")
if url and url not in seen_urls:
seen_urls.add(url)
unique_results.append(result)
# Format the results nicely
formatted_results = f"Combined results for '{query}' from multiple search engines:\n\n"
for i, result in enumerate(unique_results[:max_results*2], 1):
title = result.get("title", "No title")
link = result.get("link", "No URL")
snippet = result.get("snippet", "No description")
engine = result.get("engine", "unknown")
formatted_results += f"{i}. {title} [{engine}]\n"
formatted_results += f" URL: {link}\n"
formatted_results += f" Summary: {snippet}\n\n"
return formatted_results
else:
return f"No results found for '{query}' across any search engines."
engine_name = engine_results["engine"].title()
formatted_results += f"=== Results from {engine_name} ===\n\n"
for i, result in enumerate(engine_results["results"], 1):
formatted_results += f"{i}. {result['title']}\n"
formatted_results += f" URL: {result['link']}\n"
if result.get('snippet'):
# Clean up the snippet
snippet = result['snippet']
snippet = re.sub(r'\s+', ' ', snippet).strip()
snippet = re.sub(r'<[^>]+>', '', snippet)
formatted_results += f" Summary: {snippet}\n"
formatted_results += "\n"
return formatted_results
def _safe_search(self, engine_name, query, max_results):
"""Execute a search with error handling for parallel execution."""
try:
return self.search_engines[engine_name](query, max_results)
except Exception as e:
logger.error(f"Error in {engine_name} search: {str(e)}", exc_info=True)
return {
"search_engine": engine_name,
"query": query,
"error": str(e),
"results": []
}
def browse_webpage(self, url):
"""
Browse a webpage and extract its content.
Args:
url (str): URL of the webpage to browse
Returns:
str: Extracted content from the webpage
"""
try:
max_retries = 3
retry_delay = 2 # seconds
for attempt in range(max_retries):
try:
response = self.session.get(url, timeout=15)
response.raise_for_status()
break
except requests.exceptions.RequestException as e:
if attempt == max_retries - 1:
raise
logger.warning(f"Retry {attempt+1}/{max_retries} failed: {str(e)}")
time.sleep(retry_delay)
retry_delay *= 2 # Exponential backoff
content_type = response.headers.get('Content-Type', '').lower()
# Check if the response is HTML
if 'text/html' not in content_type:
return f"The URL {url} returned non-HTML content (type: {content_type})."
soup = BeautifulSoup(response.text, 'html.parser')
# Remove script, style, and other non-content elements
for element in soup(["script", "style", "header", "footer", "nav", "aside", "iframe", "noscript"]):
element.extract()
# Extract the page title
title = soup.title.string if soup.title else "No title found"
# Try to extract the main content
main_content = None
# Common selectors for main content
main_selectors = [
"main", "article", "#content", ".content", "#main", ".main",
"[role='main']", "#article", ".article", "#post", ".post"
]
for selector in main_selectors:
content_elements = soup.select(selector)
if content_elements:
main_content = "\n".join(elem.get_text(separator="\n", strip=True) for elem in content_elements)
break
# If no main content found, use all paragraph text
if not main_content or len(main_content) < 100:
paragraphs = soup.find_all('p')
main_content = "\n".join(p.get_text(separator="\n", strip=True) for p in paragraphs)
# If still no substantial content, get all text
if not main_content or len(main_content) < 100:
main_content = soup.get_text(separator="\n", strip=True)
# Clean up text
main_content = re.sub(r'\n+', '\n', main_content)
# Extract metadata if available
metadata = {}
meta_tags = soup.find_all('meta')
for tag in meta_tags:
# Get description and keywords
if tag.get('name') == 'description' and tag.get('content'):
metadata['description'] = tag.get('content')
elif tag.get('name') == 'keywords' and tag.get('content'):
metadata['keywords'] = tag.get('content')
# Construct the result
result = f"Title: {title}\nURL: {url}\n"
if metadata:
if 'description' in metadata:
result += f"\nDescription: {metadata['description']}\n"
if 'keywords' in metadata:
result += f"\nKeywords: {metadata['keywords']}\n"
result += "\nContent:\n"
# Limit text length, keeping proportion from beginning and end
if len(main_content) > 10000:
# Take first 70% from the beginning and 30% from the end
beginning_len = int(10000 * 0.7)
ending_len = 10000 - beginning_len
result += main_content[:beginning_len] + "\n\n[...Content truncated...]\n\n" + main_content[-ending_len:]
result += "\n\n[Content truncated due to length]"
else:
result += main_content
return result
except Exception as e:
logger.error(f"Error accessing {url}: {str(e)}", exc_info=True)
return f"Error accessing {url}: {str(e)}"
# Test code
if __name__ == "__main__":
# Configure logging for testing
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
search_tool = EnhancedWebSearchTool()
# Test basic search
query = "Who won the Nobel Prize in Physics in 2023"
print(f"\nSearching for: {query}")
results = search_tool.search(query)
print(results)
# Test multi-engine search
print("\nTesting multi-engine search...")
combined_results = search_tool.search_with_all_engines(query, max_results=2)
print("\n" + combined_results)
# Test webpage browsing
url = "https://en.wikipedia.org/wiki/Nobel_Prize_in_Physics"
print(f"\nBrowsing webpage: {url}")
content = search_tool.browse_webpage(url)
print("\nWebpage content preview:")
print(content[:500] + "...")