~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
changed to more modular system for search engines
LearningCircuitcd5275b6fdab
diff --git a/config.py b/config.pyindex fe4731b703..b29060616f 100644--- a/config.py+++ b/config.py@@ -1,27 +1,20 @@-from langchain_community.tools import DuckDuckGoSearchResults+from langchain_anthropic import ChatAnthropicfrom langchain_openai import ChatOpenAIfrom langchain_ollama import ChatOllamafrom dotenv import load_dotenv-from full_duck_duck_go_search_results import FullDuckDuckGoSearchResults-from full_serp_search_results import FullSerpAPISearchResults # Added import for SerpAPI class-from langchain_community.utilities import SerpAPIWrapper++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_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()-#Define Google Language Codes-LANGUAGE_CODE_MAPPING = {- "english": "en",- "spanish": "es",- "chinese": "zh",- "hindi": "hi",- "french": "fr",- "arabic": "ar",- "bengali": "bn",- "portuguese": "pt",- "russian": "ru",-}# LLM ConfigurationDEFAULT_MODEL = "mistral" # try to use the largest model that fits into your GPU memory@@ -54,7 +47,7 @@ SEARCH_LANGUAGE = "English"OUTPUT_DIR = "research_outputs"# Choose search tool: "serp" or "duckduckgo" (serp requires API key)-search_tool = "duckduckgo" # Change this variable to switch between search tools+search_tool = "wiki" # Change this variable to switch between search toolsdef get_llm(model_name=DEFAULT_MODEL, temperature=DEFAULT_TEMPERATURE):@@ -85,30 +78,29 @@ 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+ else:+ search_engine = DuckDuckGoSearchEngine(+ max_results=MAX_SEARCH_RESULTS,+ region=SEARCH_REGION,+ safe_search=SAFE_SEARCH,+ )if SEARCH_SNIPPETS_ONLY:- if "serp" in search_tool.lower():- return SerpAPIWrapper(- serpapi_api_key=os.getenv("SERP_API_KEY"),- params={- "engine": "google",- "hl": LANGUAGE_CODE_MAPPING.get(SEARCH_LANGUAGE.lower()), # Language setting- "gl": SEARCH_REGION, # Country/Geolocation setting- "safe" : "active" if SAFE_SEARCH else "off",- "tbs": f"qdr:{TIME_PERIOD}", # Time filter- "num": MAX_SEARCH_RESULTS, # Number of results- }- )- else:- return DuckDuckGoSearchResults(- max_results=MAX_SEARCH_RESULTS,- region=SEARCH_REGION,- time=TIME_PERIOD,- safesearch=SAFE_SEARCH,- )+ return search_engine+else :- if "serp" in search_tool.lower():+ if "serp_old" in search_tool.lower():return FullSerpAPISearchResults(llm=llm_instance,serpapi_api_key=os.getenv("SERP_API_KEY"),@@ -119,7 +111,8 @@ def get_search():safesearch="active" if SAFE_SEARCH else "off")else:- return FullDuckDuckGoSearchResults(+ return FullSearchResults(+ web_search=search_engine,llm=llm_instance,max_results=MAX_SEARCH_RESULTS,region=SEARCH_REGION,diff --git a/web_search_engines/__init__.py b/web_search_engines/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/full_duck_duck_go_search_results.py b/web_search_engines/full_search.pysimilarity index 78%rename from full_duck_duck_go_search_results.pyrename to web_search_engines/full_search.pyindex d459dcd507..12bf2688f8 100644--- a/full_duck_duck_go_search_results.py+++ b/web_search_engines/full_search.py@@ -1,7 +1,6 @@import justext-from langchain_community.tools import DuckDuckGoSearchResults-from langchain.document_loaders import AsyncChromiumLoader-from langchain.document_transformers import BeautifulSoupTransformer+from langchain_community.document_loaders import AsyncChromiumLoader+from langchain_community.document_transformers import BeautifulSoupTransformerfrom langchain_core.language_models import BaseLLMfrom typing import List, Dictimport json, os@@ -9,16 +8,18 @@ from utilities import remove_think_tagsfrom datetime import datetimeimport config-class FullDuckDuckGoSearchResults:+class FullSearchResults:def __init__(self,llm: BaseLLM, # Add LLM parameter+ web_search: list,output_format: str = "list",language: str = "English",max_results: int = 10,region: str = "wt-wt",time: str = "y",- safesearch: str = "Moderate",+ safesearch: str = "Moderate"+):self.llm = llmself.output_format = output_format@@ -27,15 +28,10 @@ class FullDuckDuckGoSearchResults:self.region = regionself.time = timeself.safesearch = safesearch+ self.web_search =web_searchos.environ["USER_AGENT"] = "Local Deep Research/1.0"- self.ddg_search = DuckDuckGoSearchResults(- output_format=output_format,- max_results=self.max_results,- region=self.region,- time=self.time,- safesearch=self.safesearch,- )+self.bs_transformer = BeautifulSoupTransformer()self.tags_to_extract = ["p", "div", "span"]@@ -43,16 +39,6 @@ class FullDuckDuckGoSearchResults:if not results:return results- # Prepare the prompt for URL evaluation- urls_text = "\n".join(- [- f"URL: {r.get('link', '')}\n"- f"Title: {r.get('title', '')}\n"- f"Snippet: {r.get('snippet', '')}\n"- for r in results- ]- )- print(urls_text)now = 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:@@ -61,14 +47,8 @@ class FullDuckDuckGoSearchResults:3. Source reliability (prefer official company websites, established news outlets)4. Direct relevance to query: {query}- For each source, analyze:- - Publication date (if available)- - Author/organization credibility- - Whether claims are supported by other reliable sources- - Primary vs secondary source status-URLs to evaluate:- {urls_text}+ {results}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.@@ -96,7 +76,7 @@ class FullDuckDuckGoSearchResults:def run(self, query: str):nr_full_text = 0# Step 1: Get search results from DuckDuckGo- search_results = self.ddg_search.invoke(query)+ 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.")diff --git a/full_serp_search_results.py b/web_search_engines/full_serp_search_results_old.pysimilarity index 90%rename from full_serp_search_results.pyrename to web_search_engines/full_serp_search_results_old.pyindex 23d198b162..bdeac65bf8 100644--- a/full_serp_search_results.py+++ b/web_search_engines/full_serp_search_results_old.py@@ -2,14 +2,27 @@ import osimport jsonimport justextfrom langchain_community.utilities import SerpAPIWrapper-from langchain.document_loaders import AsyncChromiumLoader-from langchain.document_transformers import BeautifulSoupTransformer+from langchain_community.document_loaders import AsyncChromiumLoader+from langchain_community.document_transformers import BeautifulSoupTransformerfrom langchain_core.language_models import BaseLLMfrom typing import List, Dictfrom datetime import datetimefrom utilities import remove_think_tagsimport config+#Define Google Language Codes+LANGUAGE_CODE_MAPPING = {+ "english": "en",+ "spanish": "es",+ "chinese": "zh",+ "hindi": "hi",+ "french": "fr",+ "arabic": "ar",+ "bengali": "bn",+ "portuguese": "pt",+ "russian": "ru",+}+class FullSerpAPISearchResults:def __init__(@@ -35,7 +48,7 @@ class FullSerpAPISearchResults:serpapi_api_key=serpapi_api_key, # <-- Pass API Key here!params={"engine": "google",- "hl": config.LANGUAGE_CODE_MAPPING.get(self.language.lower()),+ "hl": LANGUAGE_CODE_MAPPING.get(self.language.lower()),"gl": self.region,"safe": self.safesearch.lower(),"tbs": f"qdr:{self.time_period}",diff --git a/web_search_engines/search_engine_base.py b/web_search_engines/search_engine_base.pynew file mode 100644index 0000000000..920c78df8c--- /dev/null+++ b/web_search_engines/search_engine_base.py@@ -0,0 +1,20 @@++from abc import ABC, abstractmethod+from typing import Dict, List, Any, Optional++++++class BaseSearchEngine(ABC):+ """Abstract base class for search engines"""++ @abstractmethod+ def run(self, query: str) -> List[Dict[str, Any]]:+ """Execute a search and return results"""+ pass++ def invoke(self, query: str) -> List[Dict[str, Any]]:+ """Compatibility method for LangChain tools"""+ return self.run(query)+diff --git a/web_search_engines/search_engine_ddg.py b/web_search_engines/search_engine_ddg.pynew file mode 100644index 0000000000..54f39b0cd2--- /dev/null+++ b/web_search_engines/search_engine_ddg.py@@ -0,0 +1,24 @@+from langchain_community.utilities import DuckDuckGoSearchAPIWrapper+from typing import Dict, List, Any, Optional++from web_search_engines.search_engine_base import BaseSearchEngine+++class DuckDuckGoSearchEngine(BaseSearchEngine):+ def __init__(self,+ max_results: int = 10,+ region: str = "us",+ safe_search: bool = True):+ self.max_results=max_results+ self.engine = DuckDuckGoSearchAPIWrapper(+ region=region,+ max_results=max_results,+ 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):+ return []+ return results\ No newline at end of filediff --git a/web_search_engines/search_engine_serpapi.py b/web_search_engines/search_engine_serpapi.pynew file mode 100644index 0000000000..db6f8f5768--- /dev/null+++ b/web_search_engines/search_engine_serpapi.py@@ -0,0 +1,53 @@+from langchain_community.utilities import SerpAPIWrapper+from typing import Dict, List, Any, Optional+import os+from web_search_engines.search_engine_base import BaseSearchEngine++++class SerpAPISearchEngine(BaseSearchEngine):++ def __init__(self,+ max_results: int = 10,+ region: str = "us",+ time_period: str = "y",+ safe_search: bool = True,+ search_language: str = "English",+ api_key: Optional[str] = None,+ language_code_mapping: Optional[Dict[str, str]] = None):++ if language_code_mapping is None:+ language_code_mapping = {+ "english": "en",+ "spanish": "es",+ "chinese": "zh",+ "hindi": "hi",+ "french": "fr",+ "arabic": "ar",+ "bengali": "bn",+ "portuguese": "pt",+ "russian": "ru",+ }++ serpapi_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.")++ language_code = language_code_mapping.get(search_language.lower(), "en")++ self.engine = SerpAPIWrapper(+ serpapi_api_key=serpapi_api_key,+ params={+ "engine": "google",+ "hl": language_code,+ "gl": region,+ "safe": "active" if safe_search else "off",+ "tbs": f"qdr:{time_period}",+ "num": max_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 filediff --git a/web_search_engines/search_engine_wikipedia.py b/web_search_engines/search_engine_wikipedia.pynew file mode 100644index 0000000000..ce72364507--- /dev/null+++ b/web_search_engines/search_engine_wikipedia.py@@ -0,0 +1,118 @@+import wikipedia+from typing import Dict, List, Any, Optional++from web_search_engines.search_engine_base import BaseSearchEngine+++class WikipediaSearchEngine(BaseSearchEngine):+ """Wikipedia search engine implementation"""++ def __init__(self,+ max_results: int = 10,+ language: str = "en",+ include_content: bool = True,+ sentences: int = 5):+ """+ Initialize the Wikipedia search engine.++ Args:+ max_results: Maximum number of search results+ language: 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)+ """+ self.max_results = max_results+ self.include_content = include_content+ self.sentences = sentences++ # Set the Wikipedia language+ wikipedia.set_lang(language)++ def run(self, query: str) -> List[Dict[str, Any]]:+ print("""Execute a search using Wikipedia""")+ try:+ # Get search results+ search_results = wikipedia.search(query, results=self.max_results)++ # Process results+ results = []+ for title in search_results:+ try:+ # Get page information+ page = wikipedia.page(title)++ result = {+ "title": page.title,+ "link": page.url,+ "snippet": wikipedia.summary(title, sentences=self.sentences)+ }++ # 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,+ wikipedia.exceptions.WikipediaException) as e:+ # Skip pages with errors+ continue++ return results++ except Exception as e:+ print(f"Error during Wikipedia search: {e}")+ return []++ def get_summary(self, title: str, sentences: Optional[int] = None) -> str:+ """+ Get a summary of a specific Wikipedia page.++ Args:+ title: Title of the Wikipedia page+ sentences: Number of sentences to include (defaults to self.sentences)++ Returns:+ Summary of the page+ """+ sentences = sentences or self.sentences+ return wikipedia.summary(title, sentences=sentences)++ def get_page(self, title: str) -> Dict[str, Any]:+ """+ Get detailed information about a specific Wikipedia page.++ Args:+ title: Title of the Wikipedia page++ Returns:+ Dictionary with page information+ """+ page = wikipedia.page(title)++ 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+ }++ def set_language(self, language: str) -> None:+ """+ Change the Wikipedia language.++ Args:+ language: Language code (e.g., 'en', 'fr', 'es')+ """+ wikipedia.set_lang(language)\ No newline at end of file