Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix: add rate limiting to google_pse, remove circular import for config and web_search_engines

hashedviking4f3980f7306d
diff --git a/config.py b/config.py
index 7aa7e4bd13..45ae9dc9ca 100644
--- a/config.py
+++ b/config.py
@@ -44,7 +44,6 @@ from langchain_openai import ChatOpenAI
from langchain_ollama import ChatOllama
from langchain_community.llms import VLLM # Added VLLM import
from dotenv import load_dotenv
-from web_search_engines.search_engine_factory import get_search as factory_get_search
from utilties.enums import KnowledgeAccumulationApproach
import os
@@ -239,6 +238,9 @@ def get_llm(model_name=DEFAULT_MODEL, temperature=DEFAULT_TEMPERATURE):
def get_search():
"""Get search tool instance based on config settings"""
+ # Import here to avoid circular import
+ from web_search_engines.search_engine_factory import get_search as factory_get_search
+
print(f"Creating search engine with tool: {search_tool}")
engine = factory_get_search(
search_tool=search_tool,
diff --git a/tests/test_google_pse.py b/tests/test_google_pse.py
index 6a6baa62da..a6419d747c 100644
--- a/tests/test_google_pse.py
+++ b/tests/test_google_pse.py
@@ -5,7 +5,17 @@ Run this script to verify that your Google PSE API key and search engine ID are
import os
import sys
+import time
+import logging
from dotenv import load_dotenv
+import random
+import requests
+from requests.exceptions import RequestException
+
+# Set up logging
+logging.basicConfig(level=logging.DEBUG,
+ format='%(asctime)s - %(levelname)s - %(message)s')
+logger = logging.getLogger(__name__)
# Load environment variables from .env file
load_dotenv()
@@ -16,74 +26,181 @@ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from web_search_engines.search_engine_factory import create_search_engine
from config import get_llm
-def test_google_pse_search():
- """Test Google PSE search engine"""
- print("Testing Google Programmable Search Engine...")
+def print_step(message):
+ """Helper function to print and log a step with a timestamp"""
+ print(f"[{time.strftime('%H:%M:%S')}] {message}")
+ logger.info(message)
+
+def check_api_quota(api_key, search_engine_id):
+ """
+ Make a direct minimal request to check API quota status
+ Returns a tuple of (is_quota_ok, error_message)
+ """
+ url = "https://www.googleapis.com/customsearch/v1"
+ params = {
+ "key": api_key,
+ "cx": search_engine_id,
+ "q": "test", # Minimal query
+ "num": 1 # Request only 1 result
+ }
+
+ try:
+ response = requests.get(url, params=params, timeout=10)
+
+ # Check for quota errors specifically
+ if response.status_code == 429:
+ return False, "API quota exceeded. Google PSE has a limit of 100 requests per day on the free tier."
+ elif response.status_code != 200:
+ return False, f"API error: {response.status_code} - {response.text}"
+
+ # If we get here, the API is working
+ return True, None
+
+ except Exception as e:
+ return False, f"Error checking API: {str(e)}"
+
+def test_google_pse_search(max_retries=3, retry_delay=2):
+ """
+ Test Google PSE search engine with retry logic and rate limiting
+
+ Args:
+ max_retries: Maximum number of retries on failure
+ retry_delay: Base delay between retries in seconds
+ """
+ print_step("Starting Google Programmable Search Engine test...")
# Check if API key and search engine ID are set
api_key = os.getenv("GOOGLE_PSE_API_KEY")
search_engine_id = os.getenv("GOOGLE_PSE_ENGINE_ID")
+ # Mask the key for logging but show if it exists
+ api_key_masked = f"{api_key[:4]}...{api_key[-4:]}" if api_key and len(api_key) > 8 else None
+ print_step(f"API Key found: {api_key_masked is not None}")
+ print_step(f"Search Engine ID: {search_engine_id}")
+
if not api_key:
- print("❌ GOOGLE_PSE_API_KEY not set in environment variables")
+ print_step("❌ GOOGLE_PSE_API_KEY not set in environment variables")
return False
if not search_engine_id:
- print("❌ GOOGLE_PSE_ENGINE_ID not set in environment variables")
+ print_step("❌ GOOGLE_PSE_ENGINE_ID not set in environment variables")
return False
- print("✅ API key and search engine ID found")
+ print_step("✅ API key and search engine ID found")
+ # Check API quota before proceeding
+ print_step("Checking API quota status...")
+ quota_ok, error_message = check_api_quota(api_key, search_engine_id)
+
+ if not quota_ok:
+ print_step(f"❌ {error_message}")
+ print_step("Please wait for quota to reset (typically after 24 hours) or use a different API key.")
+ return False
+
+ print_step("✅ API quota check passed")
+
+ # Create search engine with reduced max_results to minimize API usage
try:
- # Create search engine
+ print_step("Creating search engine instance...")
+ # Create search engine without LLM to avoid hanging or errors if Ollama is not running
+ # Using None instead of get_llm() to skip LLM initialization
engine = create_search_engine(
"google_pse",
- llm=get_llm(),
- max_results=5,
+ llm=None, # Skip LLM to avoid potential connection issues
+ max_results=3, # Reduced from 5 to minimize API usage
region="us",
safe_search=True,
search_language="English"
)
if not engine:
- print("❌ Failed to create Google PSE search engine")
+ print_step("❌ Failed to create Google PSE search engine")
return False
- print("✅ Search engine created successfully")
+ print_step("✅ Search engine created successfully")
- # Run a simple test query
+ # Run a simple test query with retry logic
query = "artificial intelligence latest developments"
- print(f"Running test query: '{query}'")
+ print_step(f"Running test query: '{query}'")
+
+ attempt = 0
+ results = None
+ rate_limited = False
- results = engine.run(query)
+ while attempt < max_retries:
+ try:
+ # Add a small random jitter to the delay to avoid thundering herd
+ if attempt > 0:
+ jitter = random.uniform(0.5, 1.5)
+ sleep_time = retry_delay * (2 ** (attempt - 1)) * jitter
+ print_step(f"Retry attempt {attempt}/{max_retries}. Waiting {sleep_time:.2f} seconds...")
+ time.sleep(sleep_time)
+
+ # Execute the search
+ print_step(f"Executing search, attempt {attempt+1}/{max_retries}...")
+ results = engine.run(query)
+
+ # If successful, break out of the retry loop
+ if results:
+ print_step("Search successful!")
+ break
+ else:
+ print_step("Search returned no results")
+
+ except RequestException as e:
+ print_step(f"Network error on attempt {attempt+1}/{max_retries}: {str(e)}")
+
+ # Check for rate limiting
+ if "429" in str(e):
+ rate_limited = True
+ print_step("⚠️ API quota has been exceeded")
+ break
+
+ except Exception as e:
+ print_step(f"Error on attempt {attempt+1}/{max_retries}: {str(e)}")
+
+ attempt += 1
+
+ # Special handling for rate limiting
+ if rate_limited:
+ print_step("❌ Google PSE API quota exceeded (HTTP 429)")
+ print_step("The free tier of Google PSE allows 100 requests per day. Please wait for quota to reset or use a different API key.")
+ return False
+ # Check results after all retry attempts
if not results:
- print("❌ No results returned")
+ print_step("❌ No results returned after all retry attempts")
return False
- print(f"✅ {len(results)} results returned")
+ print_step(f"✅ {len(results)} results returned")
# Print the first result
- print("\nFirst result:")
+ print_step("\nFirst result:")
first_result = results[0]
- print(f"Title: {first_result['title']}")
- print(f"URL: {first_result['url']}")
- print(f"Snippet: {first_result['snippet'][:100]}...")
+ print_step(f"Title: {first_result['title']}")
+ print_step(f"URL: {first_result['url']}")
+ print_step(f"Snippet: {first_result['snippet'][:100]}...")
return True
except Exception as e:
- print(f"❌ Error: {str(e)}")
+ print_step(f"❌ Error: {str(e)}")
+ logger.exception("Exception in test_google_pse_search")
return False
if __name__ == "__main__":
- success = test_google_pse_search()
- if success:
- print("\n✅ Google Programmable Search Engine test completed successfully")
- else:
- print("\n❌ Google Programmable Search Engine test failed")
- print("\nPlease check that:")
- print("1. You have set GOOGLE_PSE_API_KEY and GOOGLE_PSE_ENGINE_ID in .env file")
- print("2. The API key is valid and has not reached its quota")
- print("3. The search engine ID is correct and the search engine is properly configured")
- print("4. Your network connection allows access to Google APIs")
\ No newline at end of file
+ try:
+ print_step("Test script started")
+ success = test_google_pse_search()
+ if success:
+ print_step("\n✅ Google Programmable Search Engine test completed successfully")
+ else:
+ print_step("\n❌ Google Programmable Search Engine test failed")
+ print_step("\nPlease check that:")
+ print_step("1. You have set GOOGLE_PSE_API_KEY and GOOGLE_PSE_ENGINE_ID in .env file")
+ print_step("2. The API key is valid and has not reached its quota")
+ print_step("3. The search engine ID is correct and the search engine is properly configured")
+ print_step("4. Your network connection allows access to Google APIs")
+ except Exception as e:
+ logger.exception("Unhandled exception in main")
+ print(f"Critical error: {str(e)}")
\ No newline at end of file
diff --git a/web_search_engines/engines/search_engine_google_pse.py b/web_search_engines/engines/search_engine_google_pse.py
index e442f341a7..b21b0554ed 100644
--- a/web_search_engines/engines/search_engine_google_pse.py
+++ b/web_search_engines/engines/search_engine_google_pse.py
@@ -1,11 +1,18 @@
from typing import Dict, List, Any, Optional
import os
import requests
+import time
+import random
+import logging
+from requests.exceptions import RequestException
from urllib.parse import quote_plus
from langchain_core.language_models import BaseLLM
from web_search_engines.search_engine_base import BaseSearchEngine
+# Set up logging
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)
class GooglePSESearchEngine(BaseSearchEngine):
"""Google Programmable Search Engine implementation"""
@@ -20,6 +27,8 @@ class GooglePSESearchEngine(BaseSearchEngine):
llm: Optional[BaseLLM] = None,
include_full_content: bool = False,
max_filtered_results: Optional[int] = None,
+ max_retries: int = 3,
+ retry_delay: float = 2.0,
**kwargs):
"""
Initialize the Google Programmable Search Engine.
@@ -34,6 +43,8 @@ class GooglePSESearchEngine(BaseSearchEngine):
llm: Language model for relevance filtering
include_full_content: Whether to include full webpage content in results
max_filtered_results: Maximum number of results to keep after filtering
+ max_retries: Maximum number of retry attempts for API requests
+ retry_delay: Base delay in seconds between retry attempts
**kwargs: Additional parameters (ignored but accepted for compatibility)
"""
# Initialize the BaseSearchEngine with the LLM and max_filtered_results
@@ -42,6 +53,14 @@ class GooglePSESearchEngine(BaseSearchEngine):
self.max_results = max_results
self.include_full_content = include_full_content
+ # Retry configuration
+ self.max_retries = max_retries
+ self.retry_delay = retry_delay
+
+ # Rate limiting - keep track of last request time
+ self.last_request_time = 0
+ self.min_request_interval = 0.5 # Minimum time between requests in seconds
+
# Language code mapping
language_code_mapping = {
"english": "en",
@@ -90,15 +109,42 @@ class GooglePSESearchEngine(BaseSearchEngine):
raise ValueError(f"Google PSE API error: {error_msg}")
# If we get here, the connection is valid
+ logger.info("Google PSE connection validated successfully")
return True
except Exception as e:
# Log the error and re-raise
- print(f"Error validating Google PSE connection: {str(e)}")
+ logger.error(f"Error validating Google PSE connection: {str(e)}")
raise
+
+ def _respect_rate_limit(self):
+ """Ensure we don't exceed rate limits by adding appropriate delay between requests"""
+ current_time = time.time()
+ elapsed = current_time - self.last_request_time
+
+ # If we've made a request recently, wait until the minimum interval has passed
+ if elapsed < self.min_request_interval:
+ sleep_time = self.min_request_interval - elapsed
+ logger.debug(f"Rate limiting: sleeping for {sleep_time:.2f}s")
+ time.sleep(sleep_time)
+
+ # Update the last request time
+ self.last_request_time = time.time()
def _make_request(self, query: str, start_index: int = 1) -> Dict:
- """Make a request to the Google PSE API"""
+ """
+ Make a request to the Google PSE API with retry logic and rate limiting
+
+ Args:
+ query: Search query string
+ start_index: Starting index for pagination
+
+ Returns:
+ JSON response from the API
+
+ Raises:
+ RequestException: If all retry attempts fail
+ """
# Base URL for the API
url = "https://www.googleapis.com/customsearch/v1"
@@ -114,14 +160,49 @@ class GooglePSESearchEngine(BaseSearchEngine):
"gl": self.region
}
- # Make the request
- response = requests.get(url, params=params)
+ # Implement retry logic with exponential backoff
+ attempt = 0
+ last_exception = None
- # Check for HTTP errors
- response.raise_for_status()
+ while attempt < self.max_retries:
+ try:
+ # Respect rate limits
+ self._respect_rate_limit()
+
+ # Add jitter to retries after the first attempt
+ if attempt > 0:
+ jitter = random.uniform(0.5, 1.5)
+ sleep_time = self.retry_delay * (2 ** (attempt - 1)) * jitter
+ logger.info(f"Retry attempt {attempt+1}/{self.max_retries} for query '{query}'. Waiting {sleep_time:.2f}s")
+ time.sleep(sleep_time)
+
+ # Make the request
+ logger.debug(f"Making request to Google PSE API: {query} (start_index={start_index})")
+ response = requests.get(url, params=params, timeout=10)
+
+ # Check for HTTP errors
+ response.raise_for_status()
+
+ # Return the JSON response
+ return response.json()
+
+ except RequestException as e:
+ logger.warning(f"Request error on attempt {attempt+1}/{self.max_retries}: {str(e)}")
+ last_exception = e
+ except Exception as e:
+ logger.warning(f"Error on attempt {attempt+1}/{self.max_retries}: {str(e)}")
+ last_exception = e
+
+ attempt += 1
- # Return the JSON response
- return response.json()
+ # If we get here, all retries failed
+ error_msg = f"Failed to get response from Google PSE API after {self.max_retries} attempts"
+ logger.error(error_msg)
+
+ if last_exception:
+ raise RequestException(f"{error_msg}: {str(last_exception)}")
+ else:
+ raise RequestException(error_msg)
def _get_previews(self, query: str) -> List[Dict[str, Any]]:
"""Get search result previews/snippets"""
@@ -170,10 +251,15 @@ class GooglePSESearchEngine(BaseSearchEngine):
# Update start index for next request
start_index += len(items)
+ # Add a small delay between multiple requests to be respectful of the API
+ if total_results < self.max_results:
+ time.sleep(self.min_request_interval)
+
except Exception as e:
- print(f"Error getting search results: {str(e)}")
+ logger.error(f"Error getting search results: {str(e)}")
break
+ logger.info(f"Retrieved {len(results)} search results for query: '{query}'")
return results
def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
diff --git a/web_search_engines/search_engine_base.py b/web_search_engines/search_engine_base.py
index 99e13e1e3e..a6cb61867c 100644
--- a/web_search_engines/search_engine_base.py
+++ b/web_search_engines/search_engine_base.py
@@ -4,7 +4,6 @@ from langchain_core.language_models import BaseLLM
from datetime import datetime
import json
from utilties.search_utilities import remove_think_tags
-import config
class BaseSearchEngine(ABC):
"""
@@ -29,38 +28,47 @@ class BaseSearchEngine(ABC):
def run(self, query: str) -> List[Dict[str, Any]]:
"""
- Execute a search using the two-phase approach as the default behavior.
- Gets previews, filters for relevance, then gets full content.
- This is more efficient as it only retrieves full content for relevant results.
-
- Respects config parameters:
- - SEARCH_SNIPPETS_ONLY: If True, only returns snippets without full content
- - SKIP_RELEVANCE_FILTER: If True, returns all results without filtering
+ Run the search engine with a given query, retrieving and filtering results.
+ This implements a two-phase retrieval approach:
+ 1. Get preview information for many results
+ 2. Filter the previews for relevance
+ 3. Get full content for only the relevant results
Args:
query: The search query
Returns:
- List of search result dictionaries with full content
+ List of search results with full content (if available)
"""
- # Phase 1: Get previews (titles, summaries)
- previews = self._get_previews(query)
+ # Ensure we're measuring time correctly for citation tracking
+ start_time = datetime.now()
+ # Step 1: Get preview information for items
+ previews = self._get_previews(query)
if not previews:
+ print(f"Search engine {self.__class__.__name__} returned no preview results for query: {query}")
return []
+
+ # Step 2: Filter previews for relevance with LLM
+ filtered_items = self._filter_for_relevance(previews, query)
+ if not filtered_items:
+ print(f"All preview results were filtered out as irrelevant for query: {query}")
+ # Fall back to preview items if everything was filtered
+ # Access config inside the method to avoid circular import
+ import config
+ if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:
+ return previews[:self.max_filtered_results or 5] # Return unfiltered but limited results
+ else:
+ filtered_items = previews[:self.max_filtered_results or 5]
- # Phase 2: Filter for relevance
- relevant_items = self._filter_for_relevance(previews, query)
-
- if not relevant_items:
- return []
-
- # Phase 3: Get full content for relevant items (unless SEARCH_SNIPPETS_ONLY is True)
+ # Step 3: Get full content for filtered items
+ # Import config inside the method to avoid circular import
+ import config
if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:
print("Returning snippet-only results as per config")
- results = relevant_items
+ results = filtered_items
else:
- results = self._get_full_content(relevant_items)
+ results = self._get_full_content(filtered_items)
return results
@@ -70,24 +78,25 @@ class BaseSearchEngine(ABC):
def _filter_for_relevance(self, previews: List[Dict[str, Any]], query: str) -> List[Dict[str, Any]]:
"""
- Filter previews for relevance using JSON array of indices approach.
+ Filter search results for relevance to the query using an LLM.
+
Checks config.SKIP_RELEVANCE_FILTER to determine whether to perform filtering.
- Returns ranked results, with option to limit to top N results.
Args:
- previews: List of preview dictionaries
+ previews: List of search result dictionaries with preview information
query: The original search query
Returns:
- List of relevant preview dictionaries in order of relevance
+ Filtered list of the most relevant search results
"""
- # Check if filtering should be skipped based on config
+ # Import config inside the method to avoid circular import
+ import config
+
+ # Skip filtering if configured to do so or if no LLM is available
if hasattr(config, 'SKIP_RELEVANCE_FILTER') and config.SKIP_RELEVANCE_FILTER:
- print("Skipping relevance filtering as per config")
- if self.max_filtered_results and len(previews) > self.max_filtered_results:
- print(f"Limiting results to top {self.max_filtered_results}")
- return previews[:self.max_filtered_results]
- return previews
+ # Return all previews up to max_filtered_results if no filtering is performed
+ limit = self.max_filtered_results or 5
+ return previews[:limit]
# Default implementation uses LLM if available
if not self.llm or not previews: