~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
working on auto search engine that selects the source based on the search question,
LearningCircuit2c0cb0ca2c6c
diff --git a/.env.template b/.env.templateindex 0b920df6e8..148224cd72 100644--- a/.env.template+++ b/.env.template@@ -1,6 +1,7 @@# API Keys-ANTHROPIC_API_KEY=your-api-key-here+# ANTHROPIC_API_KEY=your-api-key-here# Add other API keys as needed# OPENAI_API_KEY=your-openai-key-here# GOOGLE_API_KEY=your-google-key-here-# SERP_API_KEY=your-api-key-here\ No newline at end of file+# SERP_API_KEY=your-api-key-here+# GUARDIAN_API_KEY=your-api-key-here\ No newline at end of filediff --git a/README.md b/README.mdindex 5cf3e9fe3d..89b1e1680d 100644--- a/README.md+++ b/README.md@@ -32,6 +32,7 @@ A powerful AI-powered research assistant that performs deep, iterative analysis- arXiv integration for scientific papers and academic research- DuckDuckGo integration for web searches (may experience rate limiting)- SerpAPI integration for Google search results (requires API key)+ - The Guardian integration for news articles and journalism (requires API key)- Full webpage content retrieval- Source filtering and validation- Configurable search parameters@@ -63,6 +64,7 @@ cp .env.template .env# Edit .env with your API keys (if using cloud LLMs)ANTHROPIC_API_KEY=your-api-key-here # For ClaudeOPENAI_API_KEY=your-openai-key-here # For GPT models+GUARDIAN_API_KEY=your-guardian-api-key-here # For The Guardian search```## Usage@@ -102,7 +104,7 @@ TIME_PERIOD = "y"SAFE_SEARCH = TrueSEARCH_SNIPPETS_ONLY = False-# Choose search tool: "wiki", "arxiv", "duckduckgo", or "serp" (serp requires API key)+# Choose search tool: "wiki", "arxiv", "duckduckgo", "guardian", or "serp" (serp requires API key)search_tool = "wiki" # Change this variable to switch between search options```@@ -113,10 +115,17 @@ The system supports multiple search engines that can be selected by changing the- **Wikipedia** (`wiki`): Default option. Best for general knowledge, facts, and overview information- **arXiv** (`arxiv`): Great for scientific and academic research, accessing preprints and papers- **DuckDuckGo** (`duckduckgo`): General web search that doesn't require an API key (Note: May experience rate limiting issues)+- **The Guardian** (`guardian`): Quality journalism and news articles (requires an API key)- **SerpAPI** (`serp`): Google search results (requires an API key)> **Note:** Due to recent DuckDuckGo rate limiting issues, Wikipedia is now the default search engine.+> **Support Free Knowledge:** If you frequently use the search engines in this tool, please consider making a donation to these organizations. They provide valuable services and rely on user support to maintain their operations:+> - [Donate to Wikipedia](https://donate.wikimedia.org)+> - [Support The Guardian](https://support.theguardian.com)+> - [Support arXiv](https://arxiv.org/about/give)+> - [Donate to DuckDuckGo](https://duckduckgo.com/donations)+#### Using arXiv SearchTo use the arXiv search for scientific and academic papers:@@ -160,7 +169,10 @@ Choose your model based on available computing power and needs:- `search_engine_wikipedia.py` - Wikipedia search implementation- `search_engine_arxiv.py` - arXiv search implementation- `search_engine_ddg.py` - DuckDuckGo search implementation+ - `search_engine_guardian.py` - The Guardian search implementation- `search_engine_serpapi.py` - SerpAPI (Google) search implementation+ - `meta_search_engine.py` - Intelligent search engine selector+ - `search_engines_config.py` - Configuration for all search engines## Output Files@@ -181,6 +193,7 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file- [Wikipedia](https://www.wikipedia.org/) for factual knowledge (default search engine)- [arXiv](https://arxiv.org/) for scientific papers- [DuckDuckGo](https://duckduckgo.com) for web search+ - [The Guardian](https://www.theguardian.com/) for quality journalism- [SerpAPI](https://serpapi.com) for Google search results (requires API key)- Built on [LangChain](https://github.com/hwchase17/langchain) framework- Uses [justext](https://github.com/miso-belica/justext) for content extraction@@ -194,4 +207,4 @@ Contributions are welcome! Please feel free to submit a Pull Request.2. Create your feature branch (`git checkout -b feature/AmazingFeature`)3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)4. Push to the branch (`git push origin feature/AmazingFeature`)-5. Open a Pull Request+5. Open a Pull Request\ No newline at end of filediff --git a/app.py b/app.pyindex ec489e533e..9ce992bd4b 100644--- a/app.py+++ b/app.py@@ -790,4 +790,4 @@ def delete_research(research_id):if __name__ == '__main__':# Set server name explicitly to avoid DNS resolution issues- socketio.run(app, debug=False, host='127.0.0.1', port=5000, allow_unsafe_werkzeug=True)\ No newline at end of file+ socketio.run(app, debug=True, host='0.0.0.0', port=5000, allow_unsafe_werkzeug=True)\ No newline at end of filediff --git a/config.py b/config.pyindex 8ac8242870..386ae84bc6 100644--- a/config.py+++ b/config.py@@ -3,17 +3,15 @@ from langchain_anthropic import ChatAnthropicfrom langchain_openai import ChatOpenAIfrom langchain_ollama import ChatOllamafrom dotenv import load_dotenv+from web_search_engines.search_engine_factory import get_search as factory_get_search-from web_search_engines.full_serp_search_results_old import FullSerpAPISearchResults # Added import for SerpAPI class-from web_search_engines.full_search import FullSearchResults-from web_search_engines.search_engine_arxiv import ArXivSearchEngine-from web_search_engines.search_engine_ddg import DuckDuckGoSearchEngine-from web_search_engines.search_engine_wikipedia import WikipediaSearchEngine-from web_search_engines.search_engine_serpapi import SerpAPISearchEngineimport os# Load environment variablesload_dotenv()+# Choose search tool: "serp" or "duckduckgo" (serp requires API key)+search_tool = "auto" # Change this variable to switch between search tools+# LLM Configuration@@ -36,7 +34,7 @@ ENABLE_FACT_CHECKING = False # comes with pros and cons. Maybe works better witQUALITY_CHECK_DDG_URLS = True # Keep True for better quality results.# Search Configuration (applies to both DDG and SerpAPI)-MAX_SEARCH_RESULTS = 40+MAX_SEARCH_RESULTS = 5SEARCH_REGION = "us"TIME_PERIOD = "y"SAFE_SEARCH = True@@ -46,9 +44,6 @@ SEARCH_LANGUAGE = "English"# Output ConfigurationOUTPUT_DIR = "research_outputs"-# Choose search tool: "serp" or "duckduckgo" (serp requires API key)-search_tool = "arxiv" # Change this variable to switch between search tools-def get_llm(model_name=DEFAULT_MODEL, temperature=DEFAULT_TEMPERATURE):"""Get LLM instance - easy to switch between models"""@@ -76,55 +71,14 @@ def get_llm(model_name=DEFAULT_MODEL, temperature=DEFAULT_TEMPERATURE):def get_search():- """Get search tool instance based on the chosen search_tool variable"""- llm_instance = get_llm()- if "serp" in search_tool.lower():- search_engine = SerpAPISearchEngine(- max_results=MAX_SEARCH_RESULTS,- region=SEARCH_REGION,- time_period=TIME_PERIOD,- safe_search=SAFE_SEARCH,- search_language=SEARCH_LANGUAGE- )- elif "wiki" in search_tool.lower():- wiki = WikipediaSearchEngine(max_results=3, include_content=SEARCH_SNIPPETS_ONLY)- return wiki- elif "arxiv" in search_tool.lower():- # Create and return an instance of ArXivSearchEngine- arxiv_engine = ArXivSearchEngine(- max_results=MAX_SEARCH_RESULTS,- sort_by="relevance", # Options: 'relevance', 'lastUpdatedDate', 'submittedDate'- sort_order="descending",- include_full_text=SEARCH_SNIPPETS_ONLY- )- return arxiv_engine- else:- search_engine = DuckDuckGoSearchEngine(- max_results=MAX_SEARCH_RESULTS,- region=SEARCH_REGION,- safe_search=SAFE_SEARCH,- )-- if SEARCH_SNIPPETS_ONLY:- return search_engine-- else :- if "serp_old" in search_tool.lower():- return FullSerpAPISearchResults(- llm=llm_instance,- serpapi_api_key=os.getenv("SERP_API_KEY"),- max_results=MAX_SEARCH_RESULTS,- language = SEARCH_LANGUAGE,- region=SEARCH_REGION,- time_period=TIME_PERIOD,- safesearch="active" if SAFE_SEARCH else "off"- )- else:- return FullSearchResults(- web_search=search_engine,- llm=llm_instance,- max_results=MAX_SEARCH_RESULTS,- region=SEARCH_REGION,- time=TIME_PERIOD,- safesearch="Moderate" if SAFE_SEARCH else "Off",- )\ No newline at end of file+ """Get search tool instance based on config settings"""+ return factory_get_search(+ search_tool=search_tool, # From config.py+ 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 filediff --git a/web_search_engines/full_serp_search_results_old.py b/web_search_engines/engines/full_serp_search_results_old.pysimilarity index 100%rename from web_search_engines/full_serp_search_results_old.pyrename to web_search_engines/engines/full_serp_search_results_old.pydiff --git a/web_search_engines/engines/meta_search_engine.py b/web_search_engines/engines/meta_search_engine.pynew file mode 100644index 0000000000..1f5cdc1e36--- /dev/null+++ b/web_search_engines/engines/meta_search_engine.py@@ -0,0 +1,207 @@+import logging+import os+from typing import Dict, List, Any, Optional++from web_search_engines.search_engine_base import BaseSearchEngine+from web_search_engines.search_engines_config import SEARCH_ENGINES+from web_search_engines.search_engine_factory import create_search_engine+from web_search_engines.engines.search_engine_wikipedia import WikipediaSearchEngine++# Setup logging+logging.basicConfig(level=logging.INFO)+logger = logging.getLogger(__name__)+++class MetaSearchEngine(BaseSearchEngine):+ """+ LLM-powered meta search engine that intelligently selects and uses+ the appropriate search engines based on query analysis+ """++ def __init__(self,+ llm,+ max_results: int = 10,+ use_api_key_services: bool = True,+ max_engines_to_try: int = 3):+ """+ Initialize the meta search engine.++ Args:+ llm: Language model instance for query classification+ max_results: Maximum number of search results to return+ use_api_key_services: Whether to include services that require API keys+ max_engines_to_try: Maximum number of engines to try before giving up+ """+ self.llm = llm+ self.max_results = max_results+ self.use_api_key_services = use_api_key_services+ self.max_engines_to_try = max_engines_to_try++ # Cache for engine instances+ self.engine_cache = {}++ # Get available engines (excluding 'meta' and 'auto')+ self.available_engines = self._get_available_engines()+ 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)++ 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 availability+ available = []+ for name, config in SEARCH_ENGINES.items():+ if name in ["auto", "auto"]:+ continue++ if config.get("requires_api_key", False) and not self.use_api_key_services:+ continue++ if config.get("requires_api_key", False):+ api_key_env = config.get("api_key_env")+ api_key = os.getenv(api_key_env) if api_key_env else None+ if not api_key:+ continue++ available.append(name)++ return available++ def analyze_query(self, query: str) -> List[str]:+ """+ Use the LLM to analyze the query and return a ranked list of+ recommended search engines to try+ """+ if not self.available_engines:+ logger.warning("No search engines available")+ return []++ # Create engine descriptions for the prompt+ engine_descriptions = "\n".join([+ f"- {name.upper()}: Good for {', '.join(SEARCH_ENGINES[name]['strengths'][:3])}. "+ f"Weaknesses: {', '.join(SEARCH_ENGINES[name]['weaknesses'][:2])}. "+ f"Reliability: {SEARCH_ENGINES[name]['reliability']*100:.0f}%"+ for name in self.available_engines+ ])++ prompt = f"""Analyze this search query and rank the available search engines in order of most to least appropriate for answering it.++Query: "{query}"++Available search engines:+{engine_descriptions}++Consider:+1. The nature of the query (factual, academic, product-related, news, etc.)+2. The strengths and weaknesses of each engine+3. The reliability of each engine++Return ONLY a comma-separated list of search engine names in your recommended order. Example: "wikipedia,arxiv,duckduckgo"+Do not include any engines that are not listed above. Only return the comma-separated list, nothing else."""++ # Get response from LLM+ try:+ response = self.llm.invoke(prompt)+ content = response.content.strip()++ # Parse the response into a list of engine names+ engine_names = [name.strip().lower() for name in content.split(',')]++ # Filter out any invalid engine names+ valid_engines = [name for name in engine_names if name in self.available_engines]++ # If no valid engines were returned, use default order based on reliability+ if not valid_engines:+ valid_engines = sorted(+ self.available_engines,+ key=lambda x: SEARCH_ENGINES[x]["reliability"],+ reverse=True+ )++ return valid_engines+ except Exception as e:+ logger.error(f"Error analyzing query with LLM: {str(e)}")+ # Fall back to reliability-based ordering+ return sorted(+ self.available_engines,+ key=lambda x: SEARCH_ENGINES[x]["reliability"],+ reverse=True+ )++ def run(self, query: str) -> List[Dict[str, Any]]:+ """Execute a search using the recommended engines in order"""+ # Get ranked list of engines for this query+ ranked_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)++ # Limit the number of engines to try+ engines_to_try = ranked_engines[:self.max_engines_to_try]++ logger.info(f"Search plan created. Will try these engines in order: {', '.join(engines_to_try)}")++ all_errors = []+ # Try each engine in order+ for engine_name in engines_to_try:+ logger.info(f"Trying search engine: {engine_name}")++ # Get or create the engine instance+ engine = self._get_engine_instance(engine_name)++ if not engine:+ logger.warning(f"Failed to initialize {engine_name}, skipping")+ all_errors.append(f"Failed to initialize {engine_name}")+ continue++ try:+ # Execute the search+ results = engine.run(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++ logger.info(f"{engine_name} returned no results")+ all_errors.append(f"{engine_name} returned no results")++ except Exception as e:+ error_msg = f"Error using {engine_name} search engine: {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)++ def _get_engine_instance(self, engine_name: str) -> Optional[BaseSearchEngine]:+ """Get or create an instance of the specified search engine"""+ # Return cached instance if available+ if engine_name in self.engine_cache:+ return self.engine_cache[engine_name]++ # Create a new instance+ engine = None+ try:+ engine = create_search_engine(+ engine_name,+ llm=self.llm,+ max_results=self.max_results+ )+ except Exception as e:+ logger.error(f"Error creating engine instance for {engine_name}: {str(e)}")+ return None++ if engine:+ # Cache the instance+ self.engine_cache[engine_name] = engine++ return engine++ def invoke(self, query: str) -> List[Dict[str, Any]]:+ """Compatibility method for LangChain tools"""+ return self.run(query)\ No newline at end of filediff --git a/web_search_engines/search_engine_arxiv.py b/web_search_engines/engines/search_engine_arxiv.pysimilarity index 100%rename from web_search_engines/search_engine_arxiv.pyrename to web_search_engines/engines/search_engine_arxiv.pydiff --git a/web_search_engines/search_engine_ddg.py b/web_search_engines/engines/search_engine_ddg.pysimilarity index 100%rename from web_search_engines/search_engine_ddg.pyrename to web_search_engines/engines/search_engine_ddg.pydiff --git a/web_search_engines/engines/search_engine_guardian.py b/web_search_engines/engines/search_engine_guardian.pynew file mode 100644index 0000000000..795ac056de--- /dev/null+++ b/web_search_engines/engines/search_engine_guardian.py@@ -0,0 +1,204 @@+import requests+from typing import Dict, List, Any, Optional+import os+from datetime import datetime, timedelta++from web_search_engines.search_engine_base import BaseSearchEngine+++class GuardianSearchEngine(BaseSearchEngine):+ """The Guardian API search engine implementation"""++ def __init__(self,+ max_results: int = 10,+ api_key: Optional[str] = None,+ from_date: Optional[str] = None,+ to_date: Optional[str] = None,+ section: Optional[str] = None,+ order_by: str = "relevance"):+ """+ Initialize The Guardian search engine.++ Args:+ max_results: Maximum number of search results+ api_key: The Guardian API key (can also be set in GUARDIAN_API_KEY env)+ from_date: Start date for search (YYYY-MM-DD format, default 1 month ago)+ 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")+ """+ self.max_results = max_results+ self.api_key = api_key or os.getenv("GUARDIAN_API_KEY")++ if not self.api_key:+ raise ValueError("Guardian API key not found. Please provide api_key or set the GUARDIAN_API_KEY environment variable.")++ # Set date ranges if not provided+ if not from_date:+ # Default to one month ago+ one_month_ago = datetime.now() - timedelta(days=30)+ self.from_date = one_month_ago.strftime("%Y-%m-%d")+ else:+ self.from_date = from_date++ if not to_date:+ # Default to today+ self.to_date = datetime.now().strftime("%Y-%m-%d")+ else:+ self.to_date = to_date++ self.section = section+ self.order_by = order_by++ # API base URL+ self.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---""")++ try:+ # Build query parameters+ params = {+ "q": query,+ "api-key": self.api_key,+ "from-date": self.from_date,+ "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-tags": "keyword"+ }++ # Add section filter if specified+ if self.section:+ params["section"] = self.section++ # Execute the API request+ response = requests.get(self.api_url, params=params)+ response.raise_for_status() # Raise an error for bad responses++ data = response.json()++ # Extract results from the response+ articles = data.get("response", {}).get("results", [])++ # Format results to match expected structure+ results = []+ for i, article in enumerate(articles):+ if i >= self.max_results:+ break++ fields = article.get("fields", {})++ result = {+ "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", "") # Match other engines' full content field+ }++ # Extract tags/keywords+ tags = article.get("tags", [])+ result["keywords"] = [tag.get("webTitle", "") for tag in tags if tag.get("type") == "keyword"]++ results.append(result)++ return results++ except Exception as e:+ print(f"Error during Guardian search: {e}")+ return []++ def get_article_by_id(self, article_id: str) -> Dict[str, Any]:+ """+ Get a specific article by its ID.++ Args:+ article_id: The Guardian article ID++ Returns:+ Dictionary with article information+ """+ try:+ # Guardian article API URL+ url = f"https://content.guardianapis.com/{article_id}"++ # Execute the API request+ response = requests.get(+ url,+ params={+ "api-key": self.api_key,+ "show-fields": "headline,trailText,body,byline,publication",+ "show-tags": "keyword"+ }+ )+ response.raise_for_status()++ data = response.json()+ article = data.get("response", {}).get("content", {})++ if not article:+ return {}++ fields = article.get("fields", {})++ # Format the article+ result = {+ "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", "")+ }++ # Extract tags/keywords+ tags = article.get("tags", [])+ result["keywords"] = [tag.get("webTitle", "") for tag in tags if tag.get("type") == "keyword"]++ return result++ except Exception as e:+ print(f"Error getting article details: {e}")+ return {}++ def search_by_section(self, section: str, max_results: Optional[int] = None) -> List[Dict[str, Any]]:+ """+ Search for articles in a specific section.++ Args:+ section: The Guardian section name (e.g., "politics", "technology")+ max_results: Maximum number of search results (defaults to self.max_results)++ Returns:+ List of articles in the section+ """+ self.section = section+ return self.run("") # Empty query to get all articles in the section++ def get_recent_articles(self, days: int = 7, max_results: Optional[int] = None) -> List[Dict[str, Any]]:+ """+ Get recent articles from The Guardian.++ Args:+ days: Number of days to look back+ max_results: Maximum number of results (defaults to self.max_results)++ 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"++ if max_results:+ self.max_results = max_results++ return self.run("") # Empty query to get all recent articles\ No newline at end of filediff --git a/web_search_engines/search_engine_serpapi.py b/web_search_engines/engines/search_engine_serpapi.pysimilarity index 100%rename from web_search_engines/search_engine_serpapi.pyrename to web_search_engines/engines/search_engine_serpapi.pydiff --git a/web_search_engines/search_engine_wikipedia.py b/web_search_engines/engines/search_engine_wikipedia.pysimilarity index 100%rename from web_search_engines/search_engine_wikipedia.pyrename to web_search_engines/engines/search_engine_wikipedia.pydiff --git a/web_search_engines/search_engine_factory.py b/web_search_engines/search_engine_factory.pynew file mode 100644index 0000000000..8b527bd97a--- /dev/null+++ b/web_search_engines/search_engine_factory.py@@ -0,0 +1,196 @@+import os+import importlib+import logging+from typing import Dict, List, Any, Optional++from web_search_engines.search_engine_base import BaseSearchEngine+from web_search_engines.search_engines_config import SEARCH_ENGINES, DEFAULT_SEARCH_ENGINE++# Setup logging+logging.basicConfig(level=logging.INFO)+logger = logging.getLogger(__name__)+++def create_search_engine(engine_name: str, llm=None, **kwargs) -> Optional[BaseSearchEngine]:+ """+ Create a search engine instance based on the engine name.++ Args:+ engine_name: Name of the search engine to create+ llm: Language model instance (required for some engines like meta)+ **kwargs: Additional parameters to override defaults++ Returns:+ Initialized search engine instance or None if creation failed+ """+ # If engine name not found, use default+ if engine_name not in SEARCH_ENGINES:+ logger.warning(f"Search engine '{engine_name}' not found, using default: {DEFAULT_SEARCH_ENGINE}")+ engine_name = DEFAULT_SEARCH_ENGINE++ # Get engine configuration+ engine_config = SEARCH_ENGINES[engine_name]++ # Check for API key requirements+ if engine_config.get("requires_api_key", False):+ api_key_env = engine_config.get("api_key_env")+ api_key = os.getenv(api_key_env) if api_key_env else None++ if not api_key:+ logger.warning(f"Required API key for {engine_name} not found in environment variable: {api_key_env}")+ return None++ # Check for LLM requirements+ if engine_config.get("requires_llm", False) and not llm:+ logger.error(f"Engine {engine_name} requires an LLM instance but none was provided")+ return None++ try:+ # Load the engine class+ module_path = engine_config["module_path"]+ class_name = engine_config["class_name"]++ module = importlib.import_module(module_path)+ engine_class = getattr(module, class_name)++ # Combine default parameters with provided ones+ params = {**engine_config.get("default_params", {}), **kwargs}++ # Add LLM if required+ if engine_config.get("requires_llm", False):+ 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:+ 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++ # Create the engine instance+ engine = engine_class(**params)++ # Check if we need to wrap with full search capabilities+ if kwargs.get("use_full_search", False) and engine_config.get("supports_full_search", False):+ return _create_full_search_wrapper(engine_name, engine, llm, kwargs)++ return engine++ except Exception as e:+ logger.error(f"Failed to create search engine '{engine_name}': {str(e)}")+ return None+++def _create_full_search_wrapper(engine_name: str, base_engine: BaseSearchEngine, llm, params: Dict[str, Any]) -> Optional[BaseSearchEngine]:+ """Create a full search wrapper for the base engine if supported"""+ try:+ engine_config = SEARCH_ENGINES[engine_name]++ # Get full search class details+ module_path = engine_config.get("full_search_module")+ class_name = engine_config.get("full_search_class")++ if not module_path or not class_name:+ logger.warning(f"Full search configuration missing for {engine_name}")+ return base_engine++ # Import the full search class+ module = importlib.import_module(module_path)+ full_search_class = getattr(module, class_name)++ # Extract relevant parameters for the full search wrapper+ wrapper_params = {}++ # 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]++ # Special case for SerpAPI which needs the API key directly+ if engine_name == "serpapi":+ wrapper_params["serpapi_api_key"] = os.getenv("SERP_API_KEY")++ # Map some parameter names to what the wrapper expects+ if "language" in params and "search_language" not in params:+ wrapper_params["language"] = params["language"]++ if "safesearch" not in wrapper_params and "safe_search" in 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+ )++ return full_search++ except Exception as e:+ logger.error(f"Failed to create full search wrapper for {engine_name}: {str(e)}")+ return base_engine+++def get_available_engines(include_api_key_services: bool = True):+ """Get a list of available engine names"""+ if include_api_key_services:+ return list(SEARCH_ENGINES.keys())+ else:+ return [name for name, config in SEARCH_ENGINES.items()+ if not config.get("requires_api_key", False)]+++def get_search(search_tool: str, llm_instance,+ max_results: int = 10,+ region: str = "us",+ time_period: str = "y",+ safe_search: bool = True,+ search_snippets_only: bool = False,+ search_language: str = "English"):+ """+ 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+ llm_instance: Language model instance+ max_results: Maximum number of search results+ region: Search region/locale+ time_period: Time period for search results+ safe_search: Whether to enable safe search+ search_snippets_only: Whether to return just snippets (vs. full content)+ search_language: Language for search results++ Returns:+ Initialized search engine instance+ """+ # Common parameters+ params = {+ "max_results": max_results,+ "llm": llm_instance, # Only used by engines that need it+ }++ # Add engine-specific parameters+ if search_tool in ["duckduckgo", "serpapi"]:+ params.update({+ "region": region,+ "time_period": time_period,+ "safe_search": safe_search,+ "use_full_search": not search_snippets_only+ })++ if search_tool == "serpapi":+ params["search_language"] = search_language++ # Create and return the search engine+ return create_search_engine(search_tool, **params)diff --git a/web_search_engines/search_engines_config.py b/web_search_engines/search_engines_config.pynew file mode 100644index 0000000000..c453745f6d--- /dev/null+++ b/web_search_engines/search_engines_config.py@@ -0,0 +1,110 @@+"""+Configuration file for search engines.+Add or modify search engines here without changing code elsewhere.+"""++# Registry of all available search engines+SEARCH_ENGINES = {+ # Wikipedia search engine+ "wikipedia": {+ "module_path": "web_search_engines.engines.search_engine_wikipedia",+ "class_name": "WikipediaSearchEngine",+ "requires_api_key": False,+ "reliability": 0.95,+ "strengths": ["factual information", "general knowledge", "definitions",+ "historical facts", "biographies", "overview information"],+ "weaknesses": ["recent events", "specialized academic topics", "product comparisons"],+ "default_params": {+ "include_content": True+ }+ },++ # arXiv search engine+ "arxiv": {+ "module_path": "web_search_engines.engines.search_engine_arxiv",+ "class_name": "ArXivSearchEngine",+ "requires_api_key": False,+ "reliability": 0.9,+ "strengths": ["scientific papers", "academic research", "physics", "computer science",+ "mathematics", "statistics", "machine learning", "preprints"],+ "weaknesses": ["non-academic topics", "consumer products", "news", "general information"],+ "default_params": {+ "sort_by": "relevance",+ "sort_order": "descending"+ }+ },+++ # DuckDuckGo search engine+ "duckduckgo": {+ "module_path": "web_search_engines.engines.search_engine_ddg",+ "class_name": "DuckDuckGoSearchEngine",+ "requires_api_key": False,+ "reliability": 0.4,+ "strengths": ["web search", "product information", "reviews", "recent information",+ "news", "general queries", "broad coverage"],+ "weaknesses": ["inconsistent due to rate limits", "not specialized for academic content"],+ "default_params": {+ "region": "us",+ "safe_search": True+ },+ "supports_full_search": True,+ "full_search_module": "web_search_engines.engines.full_search",+ "full_search_class": "FullSearchResults"+ },++ # SerpAPI search engine+ "serpapi": {+ "module_path": "web_search_engines.engines.search_engine_serpapi",+ "class_name": "SerpAPISearchEngine",+ "requires_api_key": True,+ "api_key_env": "SERP_API_KEY",+ "reliability": 0.6,+ "strengths": ["comprehensive web search", "product information", "reviews",+ "recent content", "news", "broad coverage"],+ "weaknesses": ["requires API key with usage limits", "not specialized for academic content"],+ "default_params": {+ "region": "us",+ "time_period": "y",+ "safe_search": True,+ "search_language": "English"+ },+ "supports_full_search": True,+ "full_search_module": "web_search_engines.engines.full_serp_search_results_old",+ "full_search_class": "FullSerpAPISearchResults"+ },+ # The Guardian search engine+ "guardian": {+ "module_path": "web_search_engines.engines.search_engine_guardian",+ "class_name": "GuardianSearchEngine",+ "requires_api_key": True,+ "api_key_env": "GUARDIAN_API_KEY",+ "reliability": 0.85,+ "strengths": ["news articles", "current events", "opinion pieces", "journalism",+ "UK and global news", "political analysis"],+ "weaknesses": ["primarily focused on news", "limited historical content pre-1999"],+ "default_params": {+ "order_by": "relevance"+ }+ },+ # Meta search engine (intelligent engine selection)+ "auto": {+ "module_path": "web_search_engines.engines.meta_search_engine",+ "class_name": "MetaSearchEngine",+ "requires_api_key": False,+ "reliability": 0.85,+ "strengths": ["intelligent engine selection", "adaptable to query type", "fallback capabilities"],+ "weaknesses": ["slightly slower due to LLM analysis"],+ "default_params": {+ "use_api_key_services": True,+ "max_engines_to_try": 3+ },+ "requires_llm": True+ }+}++# Add 'auto' as an alias for 'meta'+SEARCH_ENGINES["auto"] = SEARCH_ENGINES["auto"]++# Default search engine to use if none specified+DEFAULT_SEARCH_ENGINE = "wikipedia"