~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
add brave search as a search tool
Nikhil Dev Goyal72978a7befe3
diff --git a/config.py b/config.pyindex d883f6a753..37a0a81288 100644--- a/config.py+++ b/config.py@@ -43,7 +43,7 @@ import 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; for only local search "local-all"+search_tool = "brave" # Change this variable to switch between search tools; for only local search "local-all"# LLM Configurationdiff --git a/web_search_engines/engines/search_engine_brave.py b/web_search_engines/engines/search_engine_brave.pynew file mode 100644index 0000000000..122c87425d--- /dev/null+++ b/web_search_engines/engines/search_engine_brave.py@@ -0,0 +1,245 @@+from langchain_community.tools import BraveSearch+from typing import Dict, List, Any, Optional+import os+from langchain_core.language_models import BaseLLM++from web_search_engines.search_engine_base import BaseSearchEngine+import config+++class BraveSearchEngine(BaseSearchEngine):+ """Brave search engine implementation with two-phase approach"""++ 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,+ llm: Optional[BaseLLM] = None,+ include_full_content: bool = False,+ max_filtered_results: Optional[int] = None,+ **kwargs):+ """+ Initialize the Brave 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: Brave Search API key (can also be set in BRAVE_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 mapping+ 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",+ }++ # Get API key+ brave_api_key = api_key or os.getenv("BRAVE_API_KEY")+ if not brave_api_key:+ raise ValueError("BRAVE_API_KEY not found. Please provide api_key or set the BRAVE_API_KEY environment variable.")++ # Get language code+ language_code = language_code_mapping.get(search_language.lower(), "en")++ # Convert time period format to Brave's format+ brave_time_period = f"p{time_period}"++ # Convert safe search to Brave's format+ brave_safe_search = "moderate" if safe_search else "off"++ # Initialize Brave Search+ self.engine = BraveSearch.from_api_key(+ api_key=brave_api_key,+ search_kwargs={+ "count": min(20, max_results),+ "country": region.upper(),+ "search_lang": language_code,+ "safesearch": brave_safe_search,+ "freshness": brave_time_period,+ }+ )++ # Set user agent for Brave Search+ os.environ["USER_AGENT"] = "Local Deep Research/1.0"++ # If full content is requested, initialize FullSearchResults+ if include_full_content:+ # Import FullSearchResults only if needed+ try:+ from web_search_engines.engines.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=brave_safe_search+ )+ 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 Brave Search.++ Args:+ query: The search query++ Returns:+ List of preview dictionaries+ """+ print("Getting search results from Brave Search")++ try:+ # Get search results from Brave Search+ raw_results = self.engine.run(query[:400])++ # Parse results if they're in string format+ if isinstance(raw_results, str):+ try:+ import json+ raw_results = json.loads(raw_results)+ except json.JSONDecodeError:+ print("Error: Unable to parse BraveSearch response as JSON.")+ return []++ # Format results as previews+ previews = []+ for i, result in enumerate(raw_results):+ preview = {+ "id": i, # Use index as ID+ "title": result.get("title", ""),+ "link": result.get("link", ""),+ "snippet": result.get("snippet", ""),+ "displayed_link": result.get("link", ""),+ "position": i+ }++ # Store full Brave 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 Brave Search 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 Brave 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+ 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 Brave 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: str) -> List[Dict[str, Any]]:+ """+ Execute a search using Brave Search with the two-phase approach.++ Args:+ query: The search query++ Returns:+ List of search results+ """+ print("---Execute a search using Brave Search---")++ # 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 resultsdiff --git a/web_search_engines/search_engine_factory.py b/web_search_engines/search_engine_factory.pyindex 024fcaf5c5..eae9a264d5 100644--- a/web_search_engines/search_engine_factory.py+++ b/web_search_engines/search_engine_factory.py@@ -130,6 +130,19 @@ def _create_full_search_wrapper(engine_name: str, base_engine: BaseSearchEngine,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"+ # Special case for Brave which needs the API key directly+ if engine_name == "brave" and "api_key" in wrapper_init_params:+ brave_api_key = os.getenv("BRAVE_API_KEY")+ if brave_api_key:+ wrapper_params["api_key"] = brave_api_key++ # Map some parameter names to what the wrapper expects+ 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 and "safesearch" in wrapper_init_params:+ wrapper_params["safesearch"] = "moderate" if params["safe_search"] else "off"+# Always include llm if it's a parameterif "llm" in wrapper_init_params:wrapper_params["llm"] = llm@@ -150,6 +163,7 @@ def _create_full_search_wrapper(engine_name: str, base_engine: BaseSearchEngine,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:@@ -195,7 +209,7 @@ def get_search(search_tool: str, llm_instance,params["max_filtered_results"] = max_filtered_results# Add engine-specific parameters- if search_tool in ["duckduckgo", "serpapi"]:+ if search_tool in ["duckduckgo", "serpapi", "brave"]:params.update({"region": region,"time_period": time_period,@@ -203,8 +217,8 @@ def get_search(search_tool: str, llm_instance,"use_full_search": not search_snippets_only})- if search_tool == "serpapi":+ if search_tool in ["serpapi", "brave"]:params["search_language"] = search_language# Create and return the search engine- return create_search_engine(search_tool, **params)\ No newline at end of file+ return create_search_engine(search_tool, **params)diff --git a/web_search_engines/search_engines_config.py b/web_search_engines/search_engines_config.pyindex cea8b33e7a..22420af815 100644--- a/web_search_engines/search_engines_config.py+++ b/web_search_engines/search_engines_config.py@@ -90,6 +90,27 @@ SEARCH_ENGINES = {"full_search_module": "web_search_engines.engines.full_serp_search_results_old","full_search_class": "FullSerpAPISearchResults"},+ # Brave search engine+ "brave": {+ "module_path": "web_search_engines.engines.search_engine_brave",+ "class_name": "BraveSearchEngine",+ "requires_api_key": True,+ "api_key_env": "BRAVE_API_KEY",+ "reliability": 0.7,+ "strengths": ["privacy-focused web search", "product information", "reviews",+ "recent content", "news", "broad coverage"],+ "weaknesses": ["requires API key with usage limits", "smaller index than Google"],+ "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_search",+ "full_search_class": "FullSearchResults"+ },+# The Guardian search engine - search seem to often provide irrelevant results.#"guardian": {# "module_path": "web_search_engines.engines.search_engine_guardian",