~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
now more filtered results
LearningCircuitbccbb6e3c668
diff --git a/config.py b/config.pyindex 386ae84bc6..1c491965a5 100644--- a/config.py+++ b/config.py@@ -33,12 +33,15 @@ ENABLE_FACT_CHECKING = False # comes with pros and cons. Maybe works better wit# URL Quality Check (applies to both DDG and SerpAPI)QUALITY_CHECK_DDG_URLS = True # Keep True for better quality results.+SEARCH_SNIPPETS_ONLY = False+SKIP_RELEVANCE_FILTER = False+# Search Configuration (applies to both DDG and SerpAPI)-MAX_SEARCH_RESULTS = 5+MAX_SEARCH_RESULTS = 30+MAX_FILTERED_RESULTS = 5SEARCH_REGION = "us"TIME_PERIOD = "y"SAFE_SEARCH = True-SEARCH_SNIPPETS_ONLY = FalseSEARCH_LANGUAGE = "English"# Output Configuration@@ -72,13 +75,20 @@ def get_llm(model_name=DEFAULT_MODEL, temperature=DEFAULT_TEMPERATURE):def get_search():"""Get search tool instance based on config settings"""- return factory_get_search(- search_tool=search_tool, # From config.py+ print(f"Creating search engine with tool: {search_tool}")+ engine = factory_get_search(+ search_tool=search_tool,llm_instance=get_llm(),max_results=MAX_SEARCH_RESULTS,region=SEARCH_REGION,time_period=TIME_PERIOD,safe_search=SAFE_SEARCH,search_snippets_only=SEARCH_SNIPPETS_ONLY,- search_language=SEARCH_LANGUAGE- )\ No newline at end of file+ search_language=SEARCH_LANGUAGE,+ max_filtered_results=MAX_FILTERED_RESULTS+ )++ if engine is None:+ print(f"Failed to create search engine with tool: {search_tool}")++ return engine\ No newline at end of filediff --git a/web_search_engines/engines/meta_search_engine.py b/web_search_engines/engines/meta_search_engine.pyindex 1f5cdc1e36..3152697897 100644--- a/web_search_engines/engines/meta_search_engine.py+++ b/web_search_engines/engines/meta_search_engine.py@@ -6,6 +6,7 @@ from web_search_engines.search_engine_base import BaseSearchEnginefrom web_search_engines.search_engines_config import SEARCH_ENGINESfrom web_search_engines.search_engine_factory import create_search_enginefrom web_search_engines.engines.search_engine_wikipedia import WikipediaSearchEngine+import config# Setup logginglogging.basicConfig(level=logging.INFO)@@ -22,17 +23,23 @@ class MetaSearchEngine(BaseSearchEngine):llm,max_results: int = 10,use_api_key_services: bool = True,- max_engines_to_try: int = 3):+ max_engines_to_try: int = 3,+ max_filtered_results: Optional[int] = None,+ **kwargs):"""Initialize the meta search engine.Args:- llm: Language model instance for query classification+ llm: Language model instance for query classification and relevance filteringmax_results: Maximum number of search results to returnuse_api_key_services: Whether to include services that require API keysmax_engines_to_try: Maximum number of engines to try before giving up+ max_filtered_results: Maximum number of results to keep after filtering+ **kwargs: Additional parameters (ignored but accepted for compatibility)"""- self.llm = llm+ # Initialize the BaseSearchEngine with the LLM and max_filtered_results+ super().__init__(llm=llm, max_filtered_results=max_filtered_results)+self.max_results = max_resultsself.use_api_key_services = use_api_key_servicesself.max_engines_to_try = max_engines_to_try@@ -45,14 +52,18 @@ class MetaSearchEngine(BaseSearchEngine):logger.info(f"Meta Search Engine initialized with {len(self.available_engines)} available engines: {', '.join(self.available_engines)}")# Create a fallback engine in case everything else fails- self.fallback_engine = WikipediaSearchEngine(max_results=max_results)+ self.fallback_engine = WikipediaSearchEngine(+ max_results=max_results,+ llm=llm,+ max_filtered_results=max_filtered_results+ )def _get_available_engines(self) -> List[str]:"""Get list of available engines, excluding 'meta' and 'auto'"""# Filter out 'meta' and 'auto' and check API key availabilityavailable = []for name, config in SEARCH_ENGINES.items():- if name in ["auto", "auto"]:+ if name in ["meta", "auto"]:continueif config.get("requires_api_key", False) and not self.use_api_key_services:@@ -66,6 +77,10 @@ class MetaSearchEngine(BaseSearchEngine):available.append(name)+ # Make sure we have at least one engine available+ if not available and "wikipedia" in SEARCH_ENGINES:+ available.append("wikipedia")+return availabledef analyze_query(self, query: str) -> List[str]:@@ -129,14 +144,22 @@ Do not include any engines that are not listed above. Only return the comma-separeverse=True)- def run(self, query: str) -> List[Dict[str, Any]]:- """Execute a search using the recommended engines in order"""+ def _get_previews(self, query: str) -> List[Dict[str, Any]]:+ """+ Get preview information by selecting the best search engine for this query.++ Args:+ query: The search query++ Returns:+ List of preview dictionaries+ """# Get ranked list of engines for this queryranked_engines = self.analyze_query(query)if not ranked_engines:logger.warning("No suitable search engines found for query, using fallback engine")- return self.fallback_engine.run(query)+ return self.fallback_engine._get_previews(query)# Limit the number of engines to tryengines_to_try = ranked_engines[:self.max_engines_to_try]@@ -157,26 +180,61 @@ Do not include any engines that are not listed above. Only return the comma-sepacontinuetry:- # Execute the search- results = engine.run(query)+ # Get previews from this engine+ previews = engine._get_previews(query)# If search was successful, return results- if results and len(results) > 0:- logger.info(f"Successfully got {len(results)} results from {engine_name}")- return results+ if previews and len(previews) > 0:+ logger.info(f"Successfully got {len(previews)} preview results from {engine_name}")+ # Store selected engine for later use+ self._selected_engine = engine+ self._selected_engine_name = engine_name+ return previews- logger.info(f"{engine_name} returned no results")- all_errors.append(f"{engine_name} returned no results")+ logger.info(f"{engine_name} returned no previews")+ all_errors.append(f"{engine_name} returned no previews")except Exception as e:- error_msg = f"Error using {engine_name} search engine: {str(e)}"+ error_msg = f"Error getting previews from {engine_name}: {str(e)}"logger.error(error_msg)all_errors.append(error_msg)# If we reach here, all engines failed, use fallback- logger.warning(f"All engines failed or returned no results: {', '.join(all_errors)}")- logger.info("Using fallback Wikipedia engine")- return self.fallback_engine.run(query)+ logger.warning(f"All engines failed or returned no preview results: {', '.join(all_errors)}")+ logger.info("Using fallback Wikipedia engine for previews")+ self._selected_engine = self.fallback_engine+ self._selected_engine_name = "wikipedia"+ return self.fallback_engine._get_previews(query)++ def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ """+ Get full content using the engine that provided the previews.++ Args:+ relevant_items: List of relevant preview dictionaries++ Returns:+ List of result dictionaries with full content+ """+ # Check if we should get full content+ if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:+ logger.info("Snippet-only mode, skipping full content retrieval")+ return relevant_items++ logger.info("Getting full content for relevant items")++ # Use the selected engine to get full content+ if hasattr(self, '_selected_engine'):+ try:+ logger.info(f"Using {self._selected_engine_name} to get full content")+ return self._selected_engine._get_full_content(relevant_items)+ except Exception as e:+ logger.error(f"Error getting full content from {self._selected_engine_name}: {str(e)}")+ # Fall back to returning relevant items without full content+ return relevant_items+ else:+ logger.warning("No engine was selected during preview phase, returning relevant items as-is")+ return relevant_itemsdef _get_engine_instance(self, engine_name: str) -> Optional[BaseSearchEngine]:"""Get or create an instance of the specified search engine"""@@ -187,10 +245,19 @@ Do not include any engines that are not listed above. Only return the comma-sepa# Create a new instanceengine = Nonetry:+ # Only pass parameters that all engines accept+ common_params = {+ "llm": self.llm,+ "max_results": self.max_results+ }++ # Add max_filtered_results if specified+ if self.max_filtered_results is not None:+ common_params["max_filtered_results"] = self.max_filtered_results+engine = create_search_engine(engine_name,- llm=self.llm,- max_results=self.max_results+ **common_params)except Exception as e:logger.error(f"Error creating engine instance for {engine_name}: {str(e)}")diff --git a/web_search_engines/engines/search_engine_arxiv.py b/web_search_engines/engines/search_engine_arxiv.pyindex 9c709fd7de..2f40057634 100644--- a/web_search_engines/engines/search_engine_arxiv.py+++ b/web_search_engines/engines/search_engine_arxiv.py@@ -1,17 +1,22 @@-import arxivfrom typing import Dict, List, Any, Optional-from web_search_engines.search_engine_base import BaseSearchEngine+from langchain_core.language_models import BaseLLM+from web_search_engines.search_engine_base import BaseSearchEngine+import config+import arxivclass ArXivSearchEngine(BaseSearchEngine):- """arXiv search engine implementation"""+ """arXiv search engine implementation with two-phase approach"""def __init__(self,max_results: int = 10,sort_by: str = "relevance",sort_order: str = "descending",include_full_text: bool = False,- download_dir: Optional[str] = None):+ download_dir: Optional[str] = None,+ max_full_text: int = 1,+ llm: Optional[BaseLLM] = None,+ max_filtered_results: Optional[int] = None): # Added this parameter"""Initialize the arXiv search engine.@@ -21,12 +26,19 @@ class ArXivSearchEngine(BaseSearchEngine):sort_order: Sort order ('ascending' or 'descending')include_full_text: Whether to include full paper content in results (downloads PDF)download_dir: Directory to download PDFs to (if include_full_text is True)+ max_full_text: Maximum number of PDFs to download and process (default: 1)+ llm: Language model for relevance filtering+ max_filtered_results: Maximum number of results to keep after filtering"""+ # Initialize the BaseSearchEngine with the LLM and max_filtered_results+ super().__init__(llm=llm, max_filtered_results=max_filtered_results)+self.max_results = max_resultsself.sort_by = sort_byself.sort_order = sort_orderself.include_full_text = include_full_textself.download_dir = download_dir+ self.max_full_text = max_full_text# Map sort parameters to arxiv package parametersself.sort_criteria = {@@ -39,65 +51,204 @@ class ArXivSearchEngine(BaseSearchEngine):'ascending': arxiv.SortOrder.Ascending,'descending': arxiv.SortOrder.Descending}++ def _get_search_results(self, query: str) -> List[Any]:+ """+ Helper method to get search results from arXiv API.++ Args:+ query: The search query++ Returns:+ List of arXiv paper objects+ """+ # Configure the search client+ sort_criteria = self.sort_criteria.get(self.sort_by, arxiv.SortCriterion.Relevance)+ sort_order = self.sort_directions.get(self.sort_order, arxiv.SortOrder.Descending)++ # Create the search client+ client = arxiv.Client()++ # Create the search query+ search = arxiv.Search(+ query=query,+ max_results=self.max_results,+ sort_by=sort_criteria,+ sort_order=sort_order+ )++ # Get the search results+ papers = list(client.results(search))++ return papers- def run(self, query: str) -> List[Dict[str, Any]]:- print("""Execute a search using arXiv""")+ def _get_previews(self, query: str) -> List[Dict[str, Any]]:+ """+ Get preview information for arXiv papers.++ Args:+ query: The search query++ Returns:+ List of preview dictionaries+ """+ print("Getting paper previews from arXiv")+try:- # Configure the search client- sort_criteria = self.sort_criteria.get(self.sort_by, arxiv.SortCriterion.Relevance)- sort_order = self.sort_directions.get(self.sort_order, arxiv.SortOrder.Descending)+ # Get search results from arXiv+ papers = self._get_search_results(query)- # Create the search client- client = arxiv.Client()+ # Store the paper objects for later use+ self._papers = {paper.entry_id: paper for paper in papers}- # Create the search query- search = arxiv.Search(- query=query,- max_results=self.max_results,- sort_by=sort_criteria,- sort_order=sort_order- )-- # Process results- results = []- for paper in client.results(search):- # Basic paper information- result = {+ # Format results as previews with basic information+ previews = []+ for paper in papers:+ preview = {+ "id": paper.entry_id, # Use entry_id as ID"title": paper.title,"link": paper.entry_id, # arXiv URL+ "snippet": paper.summary[:250] + "..." if len(paper.summary) > 250 else paper.summary,+ "authors": [author.name for author in paper.authors[:3]], # First 3 authors+ "published": paper.published.strftime("%Y-%m-%d") if paper.published else None+ }++ previews.append(preview)++ return previews++ except Exception as e:+ print(f"Error getting arXiv previews: {e}")+ return []++ def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ """+ Get full content for the relevant arXiv papers.+ Downloads PDFs and extracts text when include_full_text is True.+ Limits the number of PDFs processed to max_full_text.++ Args:+ relevant_items: List of relevant preview dictionaries++ Returns:+ List of result dictionaries with full content+ """+ # Check if we should get full content+ if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:+ print("Snippet-only mode, skipping full content retrieval")+ return relevant_items++ print("Getting full content for relevant arXiv papers")++ results = []+ pdf_count = 0 # Track number of PDFs processed++ for item in relevant_items:+ # Start with the preview data+ result = item.copy()++ # Get the paper ID+ paper_id = item.get("id")++ # Try to get the full paper from our cache+ paper = None+ if hasattr(self, '_papers') and paper_id in self._papers:+ paper = self._papers[paper_id]++ if paper:+ # Add complete paper information+ result.update({"pdf_url": paper.pdf_url,- "authors": [author.name for author in paper.authors],+ "authors": [author.name for author in paper.authors], # All authors"published": paper.published.strftime("%Y-%m-%d") if paper.published else None,"updated": paper.updated.strftime("%Y-%m-%d") if paper.updated else None,"categories": paper.categories,- "summary": paper.summary,+ "summary": paper.summary, # Full summary"comment": paper.comment,"journal_ref": paper.journal_ref,"doi": paper.doi- }+ })- # Download and extract text if requested- if self.include_full_text and self.download_dir:+ # Default to using summary as content+ result["content"] = paper.summary+ result["full_content"] = paper.summary++ # Download PDF and extract text if requested and within limit+ if self.include_full_text and self.download_dir and pdf_count < self.max_full_text:try:# Download the paper+ pdf_count += 1 # Increment counter before attempting downloadpaper_path = paper.download_pdf(dirpath=self.download_dir)result["pdf_path"] = str(paper_path)- # Here you could add PDF text extraction- # For example using PyPDF2, pdfplumber, or other PDF libraries- # This would require additional dependencies-+ # Extract text from PDF+ try:+ # Try PyPDF2 first+ try:+ import PyPDF2+ with open(paper_path, 'rb') as pdf_file:+ pdf_reader = PyPDF2.PdfReader(pdf_file)+ pdf_text = ""+ for page in pdf_reader.pages:+ pdf_text += page.extract_text() + "\n\n"++ if pdf_text.strip(): # Only use if we got meaningful text+ result["content"] = pdf_text+ result["full_content"] = pdf_text+ print(f"Successfully extracted text from PDF using PyPDF2")+ except (ImportError, Exception) as e1:+ # Fall back to pdfplumber+ try:+ import pdfplumber+ with pdfplumber.open(paper_path) as pdf:+ pdf_text = ""+ for page in pdf.pages:+ pdf_text += page.extract_text() + "\n\n"++ if pdf_text.strip(): # Only use if we got meaningful text+ result["content"] = pdf_text+ result["full_content"] = pdf_text+ print(f"Successfully extracted text from PDF using pdfplumber")+ except (ImportError, Exception) as e2:+ print(f"PDF text extraction failed: {str(e1)}, then {str(e2)}")+ print(f"Using paper summary as content instead")+ except Exception as e:+ print(f"Error extracting text from PDF: {e}")+ print(f"Using paper summary as content instead")except Exception as e:print(f"Error downloading paper {paper.title}: {e}")result["pdf_path"] = None-- results.append(result)+ pdf_count -= 1 # Decrement counter if download fails+ elif self.include_full_text and self.download_dir and pdf_count >= self.max_full_text:+ # Reached PDF limit+ print(f"Maximum number of PDFs ({self.max_full_text}) reached. Skipping remaining PDFs.")+ result["content"] = paper.summary+ result["full_content"] = paper.summary++ results.append(result)++ return results++ def run(self, query: str) -> List[Dict[str, Any]]:+ """+ Execute a search using arXiv with the two-phase approach.++ Args:+ query: The search query- return results+ Returns:+ List of search results+ """+ print("---Execute a search using arXiv---")++ # Use the implementation from the parent class which handles all phases+ results = super().run(query)++ # Clean up+ if hasattr(self, '_papers'):+ del self._papers- except Exception as e:- print(f"Error during arXiv search: {e}")- return []+ return resultsdef get_paper_details(self, arxiv_id: str) -> Dict[str, Any]:"""@@ -123,21 +274,41 @@ class ArXivSearchEngine(BaseSearchEngine):paper = papers[0]- # Return the paper details- return {+ # Format result based on config+ result = {"title": paper.title,"link": paper.entry_id,- "pdf_url": paper.pdf_url,- "authors": [author.name for author in paper.authors],- "published": paper.published.strftime("%Y-%m-%d") if paper.published else None,- "updated": paper.updated.strftime("%Y-%m-%d") if paper.updated else None,- "categories": paper.categories,- "summary": paper.summary,- "comment": paper.comment,- "journal_ref": paper.journal_ref,- "doi": paper.doi+ "snippet": paper.summary[:250] + "..." if len(paper.summary) > 250 else paper.summary,+ "authors": [author.name for author in paper.authors[:3]] # First 3 authors}+ # Add full content if not in snippet-only mode+ if not hasattr(config, 'SEARCH_SNIPPETS_ONLY') or not config.SEARCH_SNIPPETS_ONLY:+ result.update({+ "pdf_url": paper.pdf_url,+ "authors": [author.name for author in paper.authors], # All authors+ "published": paper.published.strftime("%Y-%m-%d") if paper.published else None,+ "updated": paper.updated.strftime("%Y-%m-%d") if paper.updated else None,+ "categories": paper.categories,+ "summary": paper.summary, # Full summary+ "comment": paper.comment,+ "journal_ref": paper.journal_ref,+ "doi": paper.doi,+ "content": paper.summary, # Use summary as content+ "full_content": paper.summary # For consistency+ })++ # Download PDF if requested+ if self.include_full_text and self.download_dir:+ try:+ # Download the paper+ paper_path = paper.download_pdf(dirpath=self.download_dir)+ result["pdf_path"] = str(paper_path)+ except Exception as e:+ print(f"Error downloading paper: {e}")++ return result+except Exception as e:print(f"Error getting paper details: {e}")return {}@@ -153,9 +324,18 @@ class ArXivSearchEngine(BaseSearchEngine):Returns:List of papers by the author"""- max_results = max_results or self.max_results- query = f"au:\"{author_name}\""- return self.run(query)+ original_max_results = self.max_results++ try:+ if max_results:+ self.max_results = max_results++ query = f"au:\"{author_name}\""+ return self.run(query)++ finally:+ # Restore original value+ self.max_results = original_max_resultsdef search_by_category(self, category: str, max_results: Optional[int] = None) -> List[Dict[str, Any]]:"""@@ -168,6 +348,15 @@ class ArXivSearchEngine(BaseSearchEngine):Returns:List of papers in the category"""- max_results = max_results or self.max_results- query = f"cat:{category}"- return self.run(query)\ No newline at end of file+ original_max_results = self.max_results++ try:+ if max_results:+ self.max_results = max_results++ query = f"cat:{category}"+ return self.run(query)++ finally:+ # Restore original value+ self.max_results = original_max_results\ No newline at end of filediff --git a/web_search_engines/engines/search_engine_ddg.py b/web_search_engines/engines/search_engine_ddg.pyindex 54f39b0cd2..16ce2dac47 100644--- a/web_search_engines/engines/search_engine_ddg.py+++ b/web_search_engines/engines/search_engine_ddg.py@@ -1,24 +1,123 @@from langchain_community.utilities import DuckDuckGoSearchAPIWrapperfrom typing import Dict, List, Any, Optional+from langchain_core.language_models import BaseLLMfrom web_search_engines.search_engine_base import BaseSearchEngine-+from full_search import FullSearchResults # Import the FullSearchResults classclass DuckDuckGoSearchEngine(BaseSearchEngine):+ """DuckDuckGo search engine implementation with two-phase retrieval"""+def __init__(self,max_results: int = 10,region: str = "us",- safe_search: bool = True):- self.max_results=max_results+ safe_search: bool = True,+ llm: Optional[BaseLLM] = None,+ language: str = "English",+ include_full_content: bool = False):+ """+ Initialize the DuckDuckGo search engine.++ Args:+ max_results: Maximum number of search results+ region: Region code for search results+ safe_search: Whether to enable safe search+ llm: Language model for relevance filtering+ language: Language for content processing+ include_full_content: Whether to include full webpage content in results+ """+ super().__init__(llm=llm)+ self.max_results = max_results+ self.region = region+ self.safe_search = safe_search+ self.language = language+ self.include_full_content = include_full_content++ # Initialize the DuckDuckGo wrapperself.engine = DuckDuckGoSearchAPIWrapper(region=region,max_results=max_results,safesearch="moderate" if safe_search else "off")++ # Initialize FullSearchResults if full content is requested+ if include_full_content and llm:+ self.full_search = FullSearchResults(+ llm=llm,+ web_search=self.engine,+ language=language,+ max_results=max_results,+ region=region,+ time="y",+ safesearch="Moderate" if safe_search else "Off"+ )def run(self, query: str) -> List[Dict[str, Any]]:- print("""---Execute a search using DuckDuckGo ---""")- results = self.engine.results(query, max_results=self.max_results)- if not isinstance(results, list):+ """+ Execute a search using DuckDuckGo with the two-phase approach.+ Respects config parameters:+ - SEARCH_SNIPPETS_ONLY: If True, only returns snippets without full content+ - SKIP_RELEVANCE_FILTER: If True, returns all results without filtering++ Args:+ query: The search query++ Returns:+ List of search results+ """+ print("---Execute a search using DuckDuckGo---")++ # Implementation of the two-phase approach (from parent class)+ return super().run(query)++ def _get_previews(self, query: str) -> List[Dict[str, Any]]:+ """+ Get preview information (titles and snippets) for initial search results.++ Args:+ query: The search query++ Returns:+ List of preview dictionaries with 'id', 'title', and 'snippet' keys+ """+ try:+ # Get search results from DuckDuckGo+ results = self.engine.results(query, max_results=self.max_results)++ if not isinstance(results, list):+ return []++ # Process results to get previews+ previews = []+ for i, result in enumerate(results):+ preview = {+ "id": result.get("link"), # Use URL as ID for DDG+ "title": result.get("title", ""),+ "snippet": result.get("snippet", ""),+ "link": result.get("link", "")+ }++ previews.append(preview)++ return previews++ except Exception as e:+ print(f"Error getting DuckDuckGo previews: {e}")return []- return results\ No newline at end of file++ def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ """+ Get full content for the relevant items by using FullSearchResults.++ Args:+ relevant_items: List of relevant preview dictionaries++ Returns:+ List of result dictionaries with full content+ """+ # If we have FullSearchResults, use it to get full content+ if hasattr(self, 'full_search'):+ return self.full_search._get_full_content(relevant_items)++ # Otherwise, just return the relevant items without full content+ return relevant_items\ No newline at end of filediff --git a/web_search_engines/engines/search_engine_guardian.py b/web_search_engines/engines/search_engine_guardian.pyindex 795ac056de..b0196d9078 100644--- a/web_search_engines/engines/search_engine_guardian.py+++ b/web_search_engines/engines/search_engine_guardian.py@@ -2,8 +2,10 @@ import requestsfrom typing import Dict, List, Any, Optionalimport osfrom datetime import datetime, timedelta+from langchain_core.language_models import BaseLLMfrom web_search_engines.search_engine_base import BaseSearchEngine+import configclass GuardianSearchEngine(BaseSearchEngine):@@ -15,7 +17,8 @@ class GuardianSearchEngine(BaseSearchEngine):from_date: Optional[str] = None,to_date: Optional[str] = None,section: Optional[str] = None,- order_by: str = "relevance"):+ order_by: str = "relevance",+ llm: Optional[BaseLLM] = None):"""Initialize The Guardian search engine.@@ -26,7 +29,11 @@ class GuardianSearchEngine(BaseSearchEngine):to_date: End date for search (YYYY-MM-DD format, default today)section: Filter by section (e.g., "politics", "technology", "sport")order_by: Sort order ("relevance", "newest", "oldest")+ llm: Language model for relevance filtering"""+ # Initialize the BaseSearchEngine with the LLM+ super().__init__(llm=llm)+self.max_results = max_resultsself.api_key = api_key or os.getenv("GUARDIAN_API_KEY")@@ -53,12 +60,19 @@ class GuardianSearchEngine(BaseSearchEngine):# API base URLself.api_url = "https://content.guardianapis.com/search"- def run(self, query: str) -> List[Dict[str, Any]]:- """Execute a search using The Guardian API"""- print("""---Execute a search using The Guardian---""")+ def _get_all_data(self, query: str) -> List[Dict[str, Any]]:+ """+ Get all article data from The Guardian API in a single call.+ Always requests all fields for simplicity.+ Args:+ query: The search query++ Returns:+ List of articles with all data+ """try:- # Build query parameters+ # Always request all fields for simplicityparams = {"q": query,"api-key": self.api_key,@@ -66,7 +80,7 @@ class GuardianSearchEngine(BaseSearchEngine):"to-date": self.to_date,"order-by": self.order_by,"page-size": min(self.max_results, 50), # API maximum is 50- "show-fields": "headline,trailText,body,byline,publication",+ "show-fields": "headline,trailText,byline,body,publication","show-tags": "keyword"}@@ -76,22 +90,24 @@ class GuardianSearchEngine(BaseSearchEngine):# Execute the API requestresponse = requests.get(self.api_url, params=params)- response.raise_for_status() # Raise an error for bad responses+ response.raise_for_status()data = response.json()# Extract results from the responsearticles = data.get("response", {}).get("results", [])- # Format results to match expected structure- results = []+ # Format results to include all data+ formatted_articles = []for i, article in enumerate(articles):if i >= self.max_results:breakfields = article.get("fields", {})+ # Format the article with all fieldsresult = {+ "id": article.get("id", ""),"title": fields.get("headline", article.get("webTitle", "")),"link": article.get("webUrl", ""),"snippet": fields.get("trailText", ""),@@ -99,21 +115,109 @@ class GuardianSearchEngine(BaseSearchEngine):"section": article.get("sectionName", ""),"author": fields.get("byline", ""),"content": fields.get("body", ""),- "full_content": fields.get("body", "") # Match other engines' full content field+ "full_content": fields.get("body", "")}# Extract tags/keywordstags = article.get("tags", [])result["keywords"] = [tag.get("webTitle", "") for tag in tags if tag.get("type") == "keyword"]- results.append(result)+ formatted_articles.append(result)- return results+ return formatted_articlesexcept Exception as e:- print(f"Error during Guardian search: {e}")+ print(f"Error getting data from The Guardian API: {e}")return []+ def _get_previews(self, query: str) -> List[Dict[str, Any]]:+ """+ Get preview information for Guardian articles.+ Actually gets all data but returns only preview fields.++ Args:+ query: The search query++ Returns:+ List of preview dictionaries+ """+ print("Getting articles from The Guardian API")++ # Get all article data+ articles = self._get_all_data(query)++ # Store full articles for later use (implementation detail)+ self._full_articles = {a["id"]: a for a in articles}++ # Return only preview fields for each article+ previews = []+ for article in articles:+ preview = {+ "id": article["id"],+ "title": article["title"],+ "link": article["link"],+ "snippet": article["snippet"],+ "publication_date": article["publication_date"],+ "section": article["section"],+ "author": article["author"],+ "keywords": article.get("keywords", [])+ }+ previews.append(preview)++ return previews++ def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ """+ Get full content for the relevant Guardian articles.+ Restores full content from the cached data.++ Args:+ relevant_items: List of relevant preview dictionaries++ Returns:+ List of result dictionaries with full content+ """+ print("Adding full content to relevant Guardian articles")++ # Check if we should add full content+ if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:+ return relevant_items++ # Get full articles for relevant items+ results = []+ for item in relevant_items:+ article_id = item.get("id", "")++ # Get the full article from our cache+ if hasattr(self, '_full_articles') and article_id in self._full_articles:+ results.append(self._full_articles[article_id])+ else:+ # If not found (shouldn't happen), just use the preview+ results.append(item)++ return results++ def run(self, query: str) -> List[Dict[str, Any]]:+ """+ Execute a search using The Guardian API with the two-phase approach.++ Args:+ query: The search query++ Returns:+ List of search results+ """+ print("---Execute a search using The Guardian---")++ # Use the implementation from the parent class which handles all phases+ results = super().run(query)++ # Clean up the cache after use+ if hasattr(self, '_full_articles'):+ del self._full_articles++ return results+def get_article_by_id(self, article_id: str) -> Dict[str, Any]:"""Get a specific article by its ID.@@ -128,7 +232,7 @@ class GuardianSearchEngine(BaseSearchEngine):# Guardian article API URLurl = f"https://content.guardianapis.com/{article_id}"- # Execute the API request+ # Always request all fieldsresponse = requests.get(url,params={@@ -147,18 +251,22 @@ class GuardianSearchEngine(BaseSearchEngine):fields = article.get("fields", {})- # Format the article+ # Format the article with all fieldsresult = {+ "id": article_id,"title": fields.get("headline", article.get("webTitle", "")),"link": article.get("webUrl", ""),"snippet": fields.get("trailText", ""),"publication_date": article.get("webPublicationDate", ""),"section": article.get("sectionName", ""),- "author": fields.get("byline", ""),- "content": fields.get("body", ""),- "full_content": fields.get("body", "")+ "author": fields.get("byline", "")}+ # Only include full content if not in snippet-only mode+ if not hasattr(config, 'SEARCH_SNIPPETS_ONLY') or not config.SEARCH_SNIPPETS_ONLY:+ result["content"] = fields.get("body", "")+ result["full_content"] = fields.get("body", "")+# Extract tags/keywordstags = article.get("tags", [])result["keywords"] = [tag.get("webTitle", "") for tag in tags if tag.get("type") == "keyword"]@@ -180,8 +288,22 @@ class GuardianSearchEngine(BaseSearchEngine):Returns:List of articles in the section"""- self.section = section- return self.run("") # Empty query to get all articles in the section+ original_section = self.section+ original_max_results = self.max_results++ try:+ # Set section and max_results for this search+ self.section = section+ if max_results:+ self.max_results = max_results++ # Use empty query to get all articles in the section+ return self.run("")++ finally:+ # Restore original values+ self.section = original_section+ self.max_results = original_max_resultsdef get_recent_articles(self, days: int = 7, max_results: Optional[int] = None) -> List[Dict[str, Any]]:"""@@ -194,11 +316,22 @@ class GuardianSearchEngine(BaseSearchEngine):Returns:List of recent articles"""- from_date = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")- self.from_date = from_date- self.order_by = "newest"+ original_from_date = self.from_date+ original_order_by = self.order_by+ original_max_results = self.max_results- if max_results:- self.max_results = max_results+ try:+ # Set parameters for this search+ self.from_date = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")+ self.order_by = "newest"+ if max_results:+ self.max_results = max_results++ # Use empty query to get all recent articles+ return self.run("")- return self.run("") # Empty query to get all recent articles\ No newline at end of file+ finally:+ # Restore original values+ self.from_date = original_from_date+ self.order_by = original_order_by+ self.max_results = original_max_results\ No newline at end of filediff --git a/web_search_engines/engines/search_engine_serpapi.py b/web_search_engines/engines/search_engine_serpapi.pyindex db6f8f5768..bf0d724eac 100644--- a/web_search_engines/engines/search_engine_serpapi.py+++ b/web_search_engines/engines/search_engine_serpapi.py@@ -1,11 +1,14 @@from langchain_community.utilities import SerpAPIWrapperfrom typing import Dict, List, Any, Optionalimport os-from web_search_engines.search_engine_base import BaseSearchEngine+from langchain_core.language_models import BaseLLM+from web_search_engines.search_engine_base import BaseSearchEngine+import configclass SerpAPISearchEngine(BaseSearchEngine):+ """Google search engine implementation using SerpAPI with two-phase approach"""def __init__(self,max_results: int = 10,@@ -14,8 +17,34 @@ class SerpAPISearchEngine(BaseSearchEngine):safe_search: bool = True,search_language: str = "English",api_key: Optional[str] = None,- language_code_mapping: Optional[Dict[str, str]] = None):-+ language_code_mapping: Optional[Dict[str, str]] = None,+ llm: Optional[BaseLLM] = None,+ include_full_content: bool = False,+ max_filtered_results: Optional[int] = None,+ **kwargs):+ """+ Initialize the SerpAPI search engine.++ Args:+ max_results: Maximum number of search results+ region: Region code for search results+ time_period: Time period for search results+ safe_search: Whether to enable safe search+ search_language: Language for search results+ api_key: SerpAPI API key (can also be set in SERP_API_KEY env)+ language_code_mapping: Mapping from language names to codes+ 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+ **kwargs: Additional parameters (ignored but accepted for compatibility)+ """+ # Initialize the BaseSearchEngine with the LLM and max_filtered_results+ super().__init__(llm=llm, max_filtered_results=max_filtered_results)++ self.max_results = max_results+ self.include_full_content = include_full_content++ # Set up language code mappingif language_code_mapping is None:language_code_mapping = {"english": "en",@@ -29,12 +58,15 @@ class SerpAPISearchEngine(BaseSearchEngine):"russian": "ru",}+ # Get API keyserpapi_api_key = api_key or os.getenv("SERP_API_KEY")if not serpapi_api_key:raise ValueError("SERP_API_KEY not found. Please provide api_key or set the SERP_API_KEY environment variable.")+ # Get language codelanguage_code = language_code_mapping.get(search_language.lower(), "en")+ # Initialize SerpAPI wrapperself.engine = SerpAPIWrapper(serpapi_api_key=serpapi_api_key,params={@@ -46,8 +78,153 @@ class SerpAPISearchEngine(BaseSearchEngine):"num": max_results,})++ # If full content is requested, initialize FullSearchResults+ if include_full_content:+ # Import FullSearchResults only if needed+ try:+ from full_search import FullSearchResults+ self.full_search = FullSearchResults(+ llm=llm,+ web_search=self.engine,+ language=search_language,+ max_results=max_results,+ region=region,+ time=time_period,+ safesearch="Moderate" if safe_search else "Off"+ )+ except ImportError:+ print("Warning: FullSearchResults not available. Full content retrieval disabled.")+ self.include_full_content = False++ def _get_previews(self, query: str) -> List[Dict[str, Any]]:+ """+ Get preview information from SerpAPI.++ Args:+ query: The search query++ Returns:+ List of preview dictionaries+ """+ print("Getting search results from SerpAPI")++ try:+ # Get search results from SerpAPI+ organic_results = self.engine.results(query).get("organic_results", [])++ # Format results as previews+ previews = []+ for result in organic_results:+ preview = {+ "id": result.get("position", len(previews)), # Use position as ID+ "title": result.get("title", ""),+ "link": result.get("link", ""),+ "snippet": result.get("snippet", ""),+ "displayed_link": result.get("displayed_link", ""),+ "position": result.get("position")+ }++ # Store full SerpAPI result for later+ preview["_full_result"] = result++ previews.append(preview)++ # Store the previews for potential full content retrieval+ self._search_results = previews++ return previews++ except Exception as e:+ print(f"Error getting SerpAPI results: {e}")+ return []++ def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ """+ Get full content for the relevant search results.+ If include_full_content is True and FullSearchResults is available,+ retrieves full webpage content for the results.++ Args:+ relevant_items: List of relevant preview dictionaries++ Returns:+ List of result dictionaries with full content if requested+ """+ # Check if we should get full content+ if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:+ print("Snippet-only mode, skipping full content retrieval")++ # Return the relevant items with their full SerpAPI information+ results = []+ for item in relevant_items:+ # Use the full result if available, otherwise use the preview+ if "_full_result" in item:+ result = item["_full_result"]+ # Remove temporary field+ if "_full_result" in result:+ del result["_full_result"]+ else:+ result = item++ results.append(result)++ return results++ # If full content retrieval is enabled+ if self.include_full_content and hasattr(self, 'full_search'):+ print("Retrieving full webpage content")++ try:+ # Extract only the links from relevant items+ links = [item.get("link") for item in relevant_items if item.get("link")]++ # Use FullSearchResults to get full content+ # This is a simplified approach - in a real implementation,+ # you would need to fetch and process the URLs+ results_with_content = self.full_search._get_full_content(relevant_items)++ return results_with_content++ except Exception as e:+ print(f"Error retrieving full content: {e}")+ # Fall back to returning the items without full content++ # Return items with their full SerpAPI information+ results = []+ for item in relevant_items:+ # Use the full result if available, otherwise use the preview+ if "_full_result" in item:+ result = item["_full_result"].copy()+ # Remove temporary field+ if "_full_result" in result:+ del result["_full_result"]+ else:+ result = item.copy()+ if "_full_result" in result:+ del result["_full_result"]++ results.append(result)++ return results- def run(self,query) -> List[Dict[str, Any]]:- print("""---Execute a search using SerpAPI (Google)---""")- serp_results = self.engine.results(query).get("organic_results", [])- return serp_results\ No newline at end of file+ def run(self, query: str) -> List[Dict[str, Any]]:+ """+ Execute a search using SerpAPI with the two-phase approach.++ Args:+ query: The search query++ Returns:+ List of search results+ """+ print("---Execute a search using SerpAPI (Google)---")++ # Use the implementation from the parent class which handles all phases+ results = super().run(query)++ # Clean up+ if hasattr(self, '_search_results'):+ del self._search_results++ return results\ No newline at end of filediff --git a/web_search_engines/engines/search_engine_wikipedia.py b/web_search_engines/engines/search_engine_wikipedia.pyindex ce72364507..780db3e715 100644--- a/web_search_engines/engines/search_engine_wikipedia.py+++ b/web_search_engines/engines/search_engine_wikipedia.py@@ -1,17 +1,26 @@import wikipediafrom typing import Dict, List, Any, Optional+from langchain_core.language_models import BaseLLM+import loggingfrom web_search_engines.search_engine_base import BaseSearchEngine+import config++# Setup logging+logger = logging.getLogger(__name__)class WikipediaSearchEngine(BaseSearchEngine):- """Wikipedia search engine implementation"""+ """Wikipedia search engine implementation with two-phase approach"""def __init__(self,max_results: int = 10,language: str = "en",include_content: bool = True,- sentences: int = 5):+ sentences: int = 5,+ llm: Optional[BaseLLM] = None,+ max_filtered_results: Optional[int] = None,+ **kwargs):"""Initialize the Wikipedia search engine.@@ -19,8 +28,14 @@ class WikipediaSearchEngine(BaseSearchEngine):max_results: Maximum number of search resultslanguage: Language code for Wikipedia (e.g., 'en', 'fr', 'es')include_content: Whether to include full page content in results- sentences: Number of sentences to include in summary (if not including full content)+ sentences: Number of sentences to include in summary+ llm: Language model for relevance filtering+ max_filtered_results: Maximum number of results to keep after filtering+ **kwargs: Additional parameters (ignored but accepted for compatibility)"""+ # Initialize the BaseSearchEngine with the LLM and max_filtered_results+ super().__init__(llm=llm, max_filtered_results=max_filtered_results)+self.max_results = max_resultsself.include_content = include_contentself.sentences = sentences@@ -28,48 +43,138 @@ class WikipediaSearchEngine(BaseSearchEngine):# Set the Wikipedia languagewikipedia.set_lang(language)- def run(self, query: str) -> List[Dict[str, Any]]:- print("""Execute a search using Wikipedia""")+ def _get_previews(self, query: str) -> List[Dict[str, Any]]:+ """+ Get preview information (titles and summaries) for Wikipedia pages.++ Args:+ query: The search query++ Returns:+ List of preview dictionaries+ """+ logger.info(f"Getting Wikipedia page previews for query: {query}")+try:- # Get search results+ # Get search results (just titles)search_results = wikipedia.search(query, results=self.max_results)- # Process results- results = []+ logger.info(f"Found {len(search_results)} Wikipedia results: {search_results}")++ if not search_results:+ logger.info(f"No Wikipedia results found for query: {query}")+ return []++ # Create a cache for full pages (will be populated on-demand)+ self._page_cache = {}++ # Generate previews with summaries+ previews = []for title in search_results:try:- # Get page information- page = wikipedia.page(title)+ # Get just the summary, with auto_suggest=False to be more precise+ summary = None+ try:+ summary = wikipedia.summary(title, sentences=self.sentences, auto_suggest=False)+ except wikipedia.exceptions.DisambiguationError as e:+ # If disambiguation error, try the first option+ if e.options and len(e.options) > 0:+ logger.info(f"Disambiguation for '{title}', trying first option: {e.options[0]}")+ try:+ summary = wikipedia.summary(e.options[0], sentences=self.sentences, auto_suggest=False)+ title = e.options[0] # Use the new title+ except Exception as inner_e:+ logger.error(f"Error with disambiguation option: {inner_e}")+ continue+ else:+ logger.warning(f"Disambiguation with no options for '{title}'")+ continue- result = {- "title": page.title,- "link": page.url,- "snippet": wikipedia.summary(title, sentences=self.sentences)- }+ if summary:+ preview = {+ "id": title, # Use title as ID+ "title": title,+ "snippet": summary,+ "link": f"https://en.wikipedia.org/wiki/{title.replace(' ', '_')}"+ }++ previews.append(preview)- # Add additional information if requested- if self.include_content:- result["content"] = page.content- result["categories"] = page.categories- result["references"] = page.references- result["links"] = page.links- result["images"] = page.images- result["sections"] = page.sections-- results.append(result)-- except (wikipedia.exceptions.DisambiguationError,- wikipedia.exceptions.PageError,+ except (wikipedia.exceptions.PageError,wikipedia.exceptions.WikipediaException) as e:# Skip pages with errors+ logger.warning(f"Error getting summary for '{title}': {e}")+ continue+ except Exception as e:+ logger.error(f"Unexpected error for '{title}': {e}")continue- return results+ logger.info(f"Successfully created {len(previews)} previews from Wikipedia")+ return previewsexcept Exception as e:- print(f"Error during Wikipedia search: {e}")+ logger.error(f"Error getting Wikipedia previews: {e}")return []+ def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ """+ Get full content for the relevant Wikipedia pages.++ Args:+ relevant_items: List of relevant preview dictionaries++ Returns:+ List of result dictionaries with full content+ """+ # Check if we should add full content+ if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:+ logger.info("Snippet-only mode, skipping full content retrieval")+ return relevant_items++ logger.info(f"Getting full content for {len(relevant_items)} relevant Wikipedia pages")++ results = []+ for item in relevant_items:+ title = item.get("id") # Title stored as ID++ if not title:+ results.append(item)+ continue++ try:+ # Get the full page+ page = wikipedia.page(title, auto_suggest=False)++ # Create a full result with all information+ result = {+ "title": page.title,+ "link": page.url,+ "snippet": item.get("snippet", "") # Keep existing snippet+ }++ # Add additional information+ result["content"] = page.content+ result["full_content"] = page.content+ result["categories"] = page.categories+ result["references"] = page.references+ result["links"] = page.links+ result["images"] = page.images+ result["sections"] = page.sections++ results.append(result)++ except (wikipedia.exceptions.DisambiguationError,+ wikipedia.exceptions.PageError,+ wikipedia.exceptions.WikipediaException) as e:+ # If error, use the preview+ logger.warning(f"Error getting full content for '{title}': {e}")+ results.append(item)+ except Exception as e:+ logger.error(f"Unexpected error getting full content for '{title}': {e}")+ results.append(item)++ return results+def get_summary(self, title: str, sentences: Optional[int] = None) -> str:"""Get a summary of a specific Wikipedia page.@@ -82,7 +187,12 @@ class WikipediaSearchEngine(BaseSearchEngine):Summary of the page"""sentences = sentences or self.sentences- return wikipedia.summary(title, sentences=sentences)+ try:+ return wikipedia.summary(title, sentences=sentences, auto_suggest=False)+ except wikipedia.exceptions.DisambiguationError as e:+ if e.options and len(e.options) > 0:+ return wikipedia.summary(e.options[0], sentences=sentences, auto_suggest=False)+ raisedef get_page(self, title: str) -> Dict[str, Any]:"""@@ -94,19 +204,33 @@ class WikipediaSearchEngine(BaseSearchEngine):Returns:Dictionary with page information"""- page = wikipedia.page(title)+ # Check if we should include full content+ include_content = not (hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY)- return {- "title": page.title,- "link": page.url,- "summary": wikipedia.summary(title, sentences=self.sentences),- "content": page.content,- "categories": page.categories,- "references": page.references,- "links": page.links,- "images": page.images,- "sections": page.sections- }+ try:+ page = wikipedia.page(title, auto_suggest=False)++ result = {+ "title": page.title,+ "link": page.url,+ "snippet": self.get_summary(title, self.sentences)+ }++ # Add additional information if requested+ if include_content:+ result["content"] = page.content+ result["full_content"] = page.content+ result["categories"] = page.categories+ result["references"] = page.references+ result["links"] = page.links+ result["images"] = page.images+ result["sections"] = page.sections++ return result+ except wikipedia.exceptions.DisambiguationError as e:+ if e.options and len(e.options) > 0:+ return self.get_page(e.options[0])+ raisedef set_language(self, language: str) -> None:"""diff --git a/web_search_engines/full_search.py b/web_search_engines/full_search.pyindex 12bf2688f8..548c55311e 100644--- a/web_search_engines/full_search.py+++ b/web_search_engines/full_search.py@@ -2,25 +2,43 @@ import justextfrom langchain_community.document_loaders import AsyncChromiumLoaderfrom langchain_community.document_transformers import BeautifulSoupTransformerfrom langchain_core.language_models import BaseLLM-from typing import List, Dict-import json, os+from typing import List, Dict, Any, Optional, Union+import json+import osfrom utilities import remove_think_tagsfrom datetime import datetimeimport configclass FullSearchResults:+ """+ Enhanced web content retrieval class that works with the BaseSearchEngine architecture.+ Can be used as a wrapper around web-based search engines like DuckDuckGo and SerpAPI.+ """+def __init__(self,- llm: BaseLLM, # Add LLM parameter- web_search: list,+ llm: BaseLLM,+ web_search,output_format: str = "list",language: str = "English",max_results: int = 10,region: str = "wt-wt",time: str = "y",safesearch: str = "Moderate"-):+ """+ Initialize the full search results processor.++ Args:+ llm: Language model instance for relevance filtering+ web_search: Web search engine instance that provides initial results+ output_format: Format of output ('list' or other formats)+ language: Language for content processing+ max_results: Maximum number of search results+ region: Search region+ time: Time period for search results+ safesearch: Safe search setting+ """self.llm = llmself.output_format = output_formatself.language = language@@ -28,17 +46,88 @@ class FullSearchResults:self.region = regionself.time = timeself.safesearch = safesearch- self.web_search =web_search+ self.web_search = web_searchos.environ["USER_AGENT"] = "Local Deep Research/1.0"-self.bs_transformer = BeautifulSoupTransformer()self.tags_to_extract = ["p", "div", "span"]-- def check_urls(self, results: List[Dict], query: str) -> List[Dict]:- if not results:++ def run(self, query: str) -> List[Dict[str, Any]]:+ """+ Legacy method that performs a full search in one step.+ Respects config parameters:+ - SEARCH_SNIPPETS_ONLY: If True, only returns snippets without full content+ - SKIP_RELEVANCE_FILTER: If True, returns all results without filtering++ Args:+ query: The search query++ Returns:+ List of search results with full content (unless SEARCH_SNIPPETS_ONLY is True)+ """+ # Phase 1: Get search results from the web search engine+ previews = self._get_previews(query)+ if not previews:+ return []++ # Phase 2: Filter URLs using LLM (unless SKIP_RELEVANCE_FILTER is True)+ if hasattr(config, 'SKIP_RELEVANCE_FILTER') and config.SKIP_RELEVANCE_FILTER:+ relevant_items = previews+ print("Skipping relevance filtering as per config")+ else:+ relevant_items = self._filter_relevant_items(previews, query)+ if not relevant_items:+ return []++ # Phase 3: Get full content for relevant items (unless SEARCH_SNIPPETS_ONLY is True)+ if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:+ print("Returning snippet-only results as per config")+ return relevant_items+ else:+ results = self._get_full_content(relevant_items)return results-++ def _get_previews(self, query: str) -> List[Dict[str, Any]]:+ """+ Get preview information from the web search engine.++ Args:+ query: The search query++ Returns:+ List of preview dictionaries+ """+ try:+ # Get search results from the web search engine+ search_results = self.web_search.invoke(query)++ if not isinstance(search_results, list):+ print("Error: Expected search results in list format")+ return []++ # Return the results as previews+ return search_results++ except Exception as e:+ print(f"Error getting previews: {e}")+ return []++ def _filter_relevant_items(self, previews: List[Dict[str, Any]], query: str) -> List[Dict[str, Any]]:+ """+ Filter previews for relevance using LLM.++ Args:+ previews: List of preview dictionaries+ query: The original search query++ Returns:+ List of relevant preview dictionaries+ """+ # Skip filtering if disabled in config or no previews+ if not config.QUALITY_CHECK_DDG_URLS or not previews:+ return previews++ # Format for LLM evaluationnow = datetime.now()current_time = now.strftime("%Y-%m-%d")prompt = f"""ONLY Return a JSON array. The response contains no letters. Evaluate these URLs for:@@ -48,81 +137,118 @@ class FullSearchResults:4. Direct relevance to query: {query}URLs to evaluate:- {results}+ {json.dumps(previews, indent=2)}Return a JSON array of indices (0-based) for sources that meet ALL criteria.ONLY Return a JSON array of indices (0-based) and nothing else. No letters.Example response: \n[0, 2, 4]\n\n"""-+try:# Get LLM's evaluationresponse = self.llm.invoke(prompt)- # print(response)- good_indices = json.loads(remove_think_tags(response.content))-- # Return only the results with good URLs- return [r for i, r in enumerate(results) if i in good_indices]++ # Extract JSON array from response+ response_text = remove_think_tags(response.content)+ # Clean up response to handle potential formatting issues+ response_text = response_text.strip()++ # Find the first occurrence of '[' and the last occurrence of ']'+ start_idx = response_text.find('[')+ end_idx = response_text.rfind(']')++ if start_idx >= 0 and end_idx > start_idx:+ array_text = response_text[start_idx:end_idx+1]+ good_indices = json.loads(array_text)++ # Return only the results with good indices+ return [r for i, r in enumerate(previews) if i in good_indices]+ else:+ print("Could not find JSON array in response, returning all previews")+ return previews+except Exception as e:print(f"URL filtering error: {e}")- return []-- def remove_boilerplate(self, html: str) -> str:- if not html or not html.strip():- return ""- paragraphs = justext.justext(html, justext.get_stoplist(self.language))- cleaned = "\n".join([p.text for p in paragraphs if not p.is_boilerplate])- return cleaned-- def run(self, query: str):+ # Fall back to returning all previews on error+ return previews++ def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ """+ Get full content for the relevant items by retrieving and processing web pages.++ Args:+ relevant_items: List of relevant preview dictionaries++ Returns:+ List of result dictionaries with full content+ """nr_full_text = 0- # Step 1: Get search results from DuckDuckGo- search_results = self.web_search.invoke(query)- #print(type(search_results))- if not isinstance(search_results, list):- raise ValueError("Expected the search results in list format.")-- # Step 2: Filter URLs using LLM- if config.QUALITY_CHECK_DDG_URLS:- filtered_results = self.check_urls(search_results, query)- else:- filtered_results = search_results-- # Extract URLs from filtered results- urls = [result.get("link") for result in filtered_results if result.get("link")]- print(urls)++ # Extract URLs from relevant items+ urls = [item.get("link") for item in relevant_items if item.get("link")]+if not urls:print("\n === NO VALID LINKS ===\n")- return []-- # Step 3: Download the full HTML pages for filtered URLs- loader = AsyncChromiumLoader(urls)- html_docs = loader.load()-- # Step 4: Process the HTML using BeautifulSoupTransformer- full_docs = self.bs_transformer.transform_documents(- html_docs, tags_to_extract=self.tags_to_extract- )-- # Step 5: Remove boilerplate from each document- url_to_content = {}- for doc in full_docs:- nr_full_text = nr_full_text + 1- source = doc.metadata.get("source")- if source:- cleaned_text = self.remove_boilerplate(doc.page_content)- url_to_content[source] = cleaned_text-- # Attach the cleaned full content to each filtered result- for result in filtered_results:- link = result.get("link")- result["full_content"] = url_to_content.get(link, None)-- print("FULL SEARCH WITH FILTERED URLS")- print("Full text retrieved: ", nr_full_text)- return filtered_results-- def invoke(self, query: str):+ return relevant_items++ try:+ # Download the full HTML pages for filtered URLs+ loader = AsyncChromiumLoader(urls)+ html_docs = loader.load()++ # Process the HTML using BeautifulSoupTransformer+ full_docs = self.bs_transformer.transform_documents(+ html_docs, tags_to_extract=self.tags_to_extract+ )++ # Remove boilerplate from each document+ url_to_content = {}+ for doc in full_docs:+ nr_full_text += 1+ source = doc.metadata.get("source")+ if source:+ cleaned_text = self._remove_boilerplate(doc.page_content)+ url_to_content[source] = cleaned_text++ # Attach the cleaned full content to each result+ results = []+ for item in relevant_items:+ new_item = item.copy()+ link = item.get("link")+ new_item["full_content"] = url_to_content.get(link, None)+ results.append(new_item)++ print(f"FULL SEARCH WITH FILTERED URLS - Full text retrieved: {nr_full_text}")+ return results++ except Exception as e:+ print(f"Error retrieving full content: {e}")+ # Return original items if full content retrieval fails+ return relevant_items++ def _remove_boilerplate(self, html: str) -> str:+ """+ Remove boilerplate content from HTML.++ Args:+ html: HTML content++ Returns:+ Cleaned text content+ """+ if not html or not html.strip():+ return ""+ try:+ paragraphs = justext.justext(html, justext.get_stoplist(self.language))+ cleaned = "\n".join([p.text for p in paragraphs if not p.is_boilerplate])+ return cleaned+ except Exception as e:+ print(f"Error removing boilerplate: {e}")+ return html++ def invoke(self, query: str) -> List[Dict[str, Any]]:+ """Compatibility method for LangChain tools"""return self.run(query)-- def __call__(self, query: str):- return self.invoke(query)++ def __call__(self, query: str) -> List[Dict[str, Any]]:+ """Make the class callable like a function"""+ return self.invoke(query)\ No newline at end of filediff --git a/web_search_engines/search_engine_base.py b/web_search_engines/search_engine_base.pyindex 920c78df8c..f197bcfe52 100644--- a/web_search_engines/search_engine_base.py+++ b/web_search_engines/search_engine_base.py@@ -1,20 +1,184 @@-from abc import ABC, abstractmethodfrom typing import Dict, List, Any, Optional----+from langchain_core.language_models import BaseLLM+from datetime import datetime+import json+from utilities import remove_think_tags+import configclass BaseSearchEngine(ABC):- """Abstract base class for search engines"""+ """+ Abstract base class for search engines with two-phase retrieval capability.+ Handles common parameters and implements the two-phase search approach.+ """++ def __init__(self,+ llm: Optional[BaseLLM] = None,+ max_filtered_results: Optional[int] = None,+ **kwargs):+ """+ Initialize the search engine with common parameters.++ Args:+ llm: Optional language model for relevance filtering+ max_filtered_results: Maximum number of results to keep after filtering+ **kwargs: Additional engine-specific parameters+ """+ self.llm = llm # LLM for relevance filtering+ self.max_filtered_results = max_filtered_results # Limit filtered results- @abstractmethoddef run(self, query: str) -> List[Dict[str, Any]]:- """Execute a search and return results"""- pass+ """+ 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++ Args:+ query: The search query++ Returns:+ List of search result dictionaries with full content+ """+ # Phase 1: Get previews (titles, summaries)+ previews = self._get_previews(query)++ if not previews:+ return []++ # 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)+ if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:+ print("Returning snippet-only results as per config")+ results = relevant_items+ else:+ results = self._get_full_content(relevant_items)++ return resultsdef invoke(self, query: str) -> List[Dict[str, Any]]:"""Compatibility method for LangChain tools"""return self.run(query)++ 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.+ 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+ query: The original search query++ Returns:+ List of relevant preview dictionaries in order of relevance+ """+ # Check if filtering should be skipped based on config+ 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++ # Default implementation uses LLM if available+ if not self.llm or not previews:+ # If no LLM available, return all previews as relevant+ if self.max_filtered_results and len(previews) > self.max_filtered_results:+ return previews[:self.max_filtered_results]+ return previews++ now = datetime.now()+ current_time = now.strftime("%Y-%m-%d")+ prompt = f"""Analyze these search results and provide a ranked list of the most relevant ones.+IMPORTANT: Evaluate and rank based on these criteria (in order of importance):+1. [MOST IMPORTANT] Timeliness - current/recent information as of {current_time}+2. Direct relevance to query: "{query}"+3. Source reliability (prefer official sources, established websites)+4. Factual accuracy (cross-reference major claims)++Search results to evaluate:+{json.dumps(previews, indent=2)}++Return ONLY a JSON array of indices (0-based) ranked from most to least relevant.+Include ONLY indices that meet ALL criteria, with the most relevant first.+Example response: [4, 0, 2]++Respond with ONLY the JSON array, no other text."""++ try:+ # Get LLM's evaluation+ response = self.llm.invoke(prompt)++ # Extract JSON array from response+ response_text = remove_think_tags(response.content)+ # Clean up response to handle potential formatting issues+ response_text = response_text.strip()++ # Find the first occurrence of '[' and the last occurrence of ']'+ start_idx = response_text.find('[')+ end_idx = response_text.rfind(']')++ if start_idx >= 0 and end_idx > start_idx:+ array_text = response_text[start_idx:end_idx+1]+ ranked_indices = json.loads(array_text)++ # Return the results in ranked order+ ranked_results = []+ for idx in ranked_indices:+ if idx < len(previews):+ ranked_results.append(previews[idx])++ # Limit to max_filtered_results if specified+ if self.max_filtered_results and len(ranked_results) > self.max_filtered_results:+ print(f"Limiting filtered results to top {self.max_filtered_results}")+ return ranked_results[:self.max_filtered_results]++ return ranked_results+ else:+ print("Could not find JSON array in response, returning all previews")+ if self.max_filtered_results and len(previews) > self.max_filtered_results:+ return previews[:self.max_filtered_results]+ return previews++ except Exception as e:+ print(f"Relevance filtering error: {e}")+ # Fall back to returning all previews (or top N) on error+ if self.max_filtered_results and len(previews) > self.max_filtered_results:+ return previews[:self.max_filtered_results]+ return previews++ @abstractmethod+ def _get_previews(self, query: str) -> List[Dict[str, Any]]:+ """+ Get preview information (titles, summaries) for initial search results.++ Args:+ query: The search query++ Returns:+ List of preview dictionaries with at least 'id', 'title', and 'snippet' keys+ """+ pass++ @abstractmethod+ def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ """+ Get full content for the relevant items.++ Args:+ relevant_items: List of relevant preview dictionaries++ Returns:+ List of result dictionaries with full content+ """+ pass\ No newline at end of filediff --git a/web_search_engines/search_engine_factory.py b/web_search_engines/search_engine_factory.pyindex 8b527bd97a..024fcaf5c5 100644--- a/web_search_engines/search_engine_factory.py+++ b/web_search_engines/search_engine_factory.py@@ -1,5 +1,6 @@import osimport importlib+import inspectimport loggingfrom typing import Dict, List, Any, Optional@@ -53,23 +54,33 @@ def create_search_engine(engine_name: str, llm=None, **kwargs) -> Optional[BaseSmodule = importlib.import_module(module_path)engine_class = getattr(module, class_name)+ # Get the engine class's __init__ parameters to filter out unsupported ones+ engine_init_signature = inspect.signature(engine_class.__init__)+ engine_init_params = list(engine_init_signature.parameters.keys())+# Combine default parameters with provided ones- params = {**engine_config.get("default_params", {}), **kwargs}+ all_params = {**engine_config.get("default_params", {}), **kwargs}++ # Filter out parameters that aren't accepted by the engine class+ # Note: 'self' is always the first parameter of instance methods, so we skip it+ filtered_params = {k: v for k, v in all_params.items() if k in engine_init_params[1:]}# Add LLM if requiredif engine_config.get("requires_llm", False):- params["llm"] = llm+ filtered_params["llm"] = llm- # Add API key if required and not already in params- if engine_config.get("requires_api_key", False) and "api_key" not in params:+ # Add API key if required and not already in filtered_params+ if engine_config.get("requires_api_key", False) and "api_key" not in filtered_params:api_key_env = engine_config.get("api_key_env")if api_key_env:api_key = os.getenv(api_key_env)if api_key:- params["api_key"] = api_key+ filtered_params["api_key"] = api_key++ logger.debug(f"Creating {engine_name} with filtered parameters: {filtered_params.keys()}")- # Create the engine instance- engine = engine_class(**params)+ # Create the engine instance with filtered parameters+ engine = engine_class(**filtered_params)# Check if we need to wrap with full search capabilitiesif kwargs.get("use_full_search", False) and engine_config.get("supports_full_search", False):@@ -99,40 +110,38 @@ def _create_full_search_wrapper(engine_name: str, base_engine: BaseSearchEngine,module = importlib.import_module(module_path)full_search_class = getattr(module, class_name)- # Extract relevant parameters for the full search wrapper- wrapper_params = {}+ # Get the wrapper's __init__ parameters to filter out unsupported ones+ wrapper_init_signature = inspect.signature(full_search_class.__init__)+ wrapper_init_params = list(wrapper_init_signature.parameters.keys())[1:] # Skip 'self'- # Common parameters that full search wrappers might need- common_keys = ["max_results", "region", "time_period", "language", "safesearch", "time"]- for key in common_keys:- if key in params:- wrapper_params[key] = params[key]+ # Extract relevant parameters for the full search wrapper+ wrapper_params = {k: v for k, v in params.items() if k in wrapper_init_params}# Special case for SerpAPI which needs the API key directly- if engine_name == "serpapi":- wrapper_params["serpapi_api_key"] = os.getenv("SERP_API_KEY")-+ if engine_name == "serpapi" and "serpapi_api_key" in wrapper_init_params:+ serpapi_api_key = os.getenv("SERP_API_KEY")+ if serpapi_api_key:+ wrapper_params["serpapi_api_key"] = serpapi_api_key+# Map some parameter names to what the wrapper expects- if "language" in params and "search_language" not in params:+ if "language" in params and "search_language" not in params and "language" in wrapper_init_params:wrapper_params["language"] = params["language"]- if "safesearch" not in wrapper_params and "safe_search" in params:+ if "safesearch" not in wrapper_params and "safe_search" in params and "safesearch" in wrapper_init_params:wrapper_params["safesearch"] = "active" if params["safe_search"] else "off"- # Create the full search wrapper- if engine_name == "serpapi":- # SerpAPI full search takes the API key directly- full_search = full_search_class(- llm=llm,- **wrapper_params- )- else:- # Other full search wrappers take the base engine- full_search = full_search_class(- web_search=base_engine,- llm=llm,- **wrapper_params- )+ # Always include llm if it's a parameter+ if "llm" in wrapper_init_params:+ wrapper_params["llm"] = llm++ # If the wrapper needs the base engine and has a parameter for it+ if "web_search" in wrapper_init_params:+ wrapper_params["web_search"] = base_engine++ logger.debug(f"Creating full search wrapper for {engine_name} with filtered parameters: {wrapper_params.keys()}")++ # Create the full search wrapper with filtered parameters+ full_search = full_search_class(**wrapper_params)return full_search@@ -156,10 +165,10 @@ def get_search(search_tool: str, llm_instance,time_period: str = "y",safe_search: bool = True,search_snippets_only: bool = False,- search_language: str = "English"):+ search_language: str = "English",+ max_filtered_results: Optional[int] = None):"""Get search tool instance based on the provided parameters.- This function can replace the get_search() in config.py.Args:search_tool: Name of the search engine to use@@ -170,6 +179,7 @@ def get_search(search_tool: str, llm_instance,safe_search: Whether to enable safe searchsearch_snippets_only: Whether to return just snippets (vs. full content)search_language: Language for search results+ max_filtered_results: Maximum number of results to keep after filteringReturns:Initialized search engine instance@@ -180,6 +190,10 @@ def get_search(search_tool: str, llm_instance,"llm": llm_instance, # Only used by engines that need it}+ # Add max_filtered_results if provided+ if max_filtered_results is not None:+ params["max_filtered_results"] = max_filtered_results+# Add engine-specific parametersif search_tool in ["duckduckgo", "serpapi"]:params.update({@@ -193,4 +207,4 @@ def get_search(search_tool: str, llm_instance,params["search_language"] = search_language# Create and return the search engine- return create_search_engine(search_tool, **params)+ return create_search_engine(search_tool, **params)\ No newline at end of file