~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
feat: Add 5 new free search adapters (#1540)
LearningCircuitc48375e0d7aa
diff --git a/src/local_deep_research/defaults/settings_gutenberg.json b/src/local_deep_research/defaults/settings_gutenberg.jsonnew file mode 100644index 0000000000..4154e3a02c--- /dev/null+++ b/src/local_deep_research/defaults/settings_gutenberg.json@@ -0,0 +1,118 @@+{+ "search.engine.web.gutenberg": {+ "category": "gutenberg",+ "description": "Project Gutenberg search engine configuration",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "Project Gutenberg Search Engine",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "json",+ "value": {+ "module_path": ".engines.search_engine_gutenberg",+ "class_name": "GutenbergSearchEngine",+ "requires_api_key": false,+ "requires_llm": true,+ "description": "Search 70,000+ free public domain books with full text via Gutendex.",+ "reliability": 0.95+ },+ "visible": false+ },+ "search.engine.web.gutenberg.display_name": {+ "category": "gutenberg",+ "description": "Display name for Project Gutenberg search engine.",+ "editable": false,+ "name": "Display Name",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "Project Gutenberg",+ "visible": false+ },+ "search.engine.web.gutenberg.description": {+ "category": "gutenberg",+ "description": "Human-readable description of the search engine.",+ "editable": false,+ "name": "Description",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "Search 70,000+ free public domain books with full text via Gutendex.",+ "visible": false+ },+ "search.engine.web.gutenberg.module_path": {+ "category": "gutenberg",+ "description": "Python module path for Project Gutenberg search engine.",+ "editable": false,+ "name": "Module Path",+ "type": "SEARCH",+ "ui_element": "text",+ "value": ".engines.search_engine_gutenberg",+ "visible": false+ },+ "search.engine.web.gutenberg.class_name": {+ "category": "gutenberg",+ "description": "Python class implementing Project Gutenberg search.",+ "editable": false,+ "name": "Class Name",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "GutenbergSearchEngine",+ "visible": false+ },+ "search.engine.web.gutenberg.requires_api_key": {+ "category": "gutenberg",+ "description": "Project Gutenberg is free and does not require an API key.",+ "editable": false,+ "name": "Requires API Key",+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": false,+ "visible": false+ },+ "search.engine.web.gutenberg.reliability": {+ "category": "gutenberg",+ "description": "Reliability score for Project Gutenberg.",+ "editable": true,+ "name": "Reliability",+ "max_value": 1.0,+ "min_value": 0.0,+ "step": 0.05,+ "type": "SEARCH",+ "ui_element": "range",+ "value": 0.95,+ "visible": true+ },+ "search.engine.web.gutenberg.strengths": {+ "category": "gutenberg",+ "description": "Key strengths of Project Gutenberg.",+ "editable": true,+ "name": "Strengths",+ "type": "SEARCH",+ "ui_element": "json",+ "value": ["public domain", "full text", "classic literature", "free ebooks", "multiple formats"],+ "visible": true+ },+ "search.engine.web.gutenberg.weaknesses": {+ "category": "gutenberg",+ "description": "Limitations of Project Gutenberg.",+ "editable": true,+ "name": "Weaknesses",+ "type": "SEARCH",+ "ui_element": "json",+ "value": ["public domain only", "older works", "limited modern titles"],+ "visible": true+ },+ "search.engine.web.gutenberg.default_params.max_results": {+ "category": "gutenberg",+ "description": "Maximum number of results to retrieve from Project Gutenberg.",+ "editable": true,+ "max_value": 32,+ "min_value": 1,+ "name": "Max Results",+ "type": "SEARCH",+ "ui_element": "number",+ "value": 20,+ "visible": true+ }+}diff --git a/src/local_deep_research/defaults/settings_openlibrary.json b/src/local_deep_research/defaults/settings_openlibrary.jsonnew file mode 100644index 0000000000..f8a927d836--- /dev/null+++ b/src/local_deep_research/defaults/settings_openlibrary.json@@ -0,0 +1,118 @@+{+ "search.engine.web.openlibrary": {+ "category": "openlibrary",+ "description": "Open Library search engine configuration",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "Open Library Search Engine",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "json",+ "value": {+ "module_path": ".engines.search_engine_openlibrary",+ "class_name": "OpenLibrarySearchEngine",+ "requires_api_key": false,+ "requires_llm": true,+ "description": "Search 2M+ books with metadata, covers, and full text from Internet Archive.",+ "reliability": 0.9+ },+ "visible": false+ },+ "search.engine.web.openlibrary.display_name": {+ "category": "openlibrary",+ "description": "Display name for Open Library search engine.",+ "editable": false,+ "name": "Display Name",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "Open Library",+ "visible": false+ },+ "search.engine.web.openlibrary.description": {+ "category": "openlibrary",+ "description": "Human-readable description of the search engine.",+ "editable": false,+ "name": "Description",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "Search 2M+ books with metadata, covers, and full text from Internet Archive.",+ "visible": false+ },+ "search.engine.web.openlibrary.module_path": {+ "category": "openlibrary",+ "description": "Python module path for Open Library search engine.",+ "editable": false,+ "name": "Module Path",+ "type": "SEARCH",+ "ui_element": "text",+ "value": ".engines.search_engine_openlibrary",+ "visible": false+ },+ "search.engine.web.openlibrary.class_name": {+ "category": "openlibrary",+ "description": "Python class implementing Open Library search.",+ "editable": false,+ "name": "Class Name",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "OpenLibrarySearchEngine",+ "visible": false+ },+ "search.engine.web.openlibrary.requires_api_key": {+ "category": "openlibrary",+ "description": "Open Library is free and does not require an API key.",+ "editable": false,+ "name": "Requires API Key",+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": false,+ "visible": false+ },+ "search.engine.web.openlibrary.reliability": {+ "category": "openlibrary",+ "description": "Reliability score for Open Library.",+ "editable": true,+ "name": "Reliability",+ "max_value": 1.0,+ "min_value": 0.0,+ "step": 0.05,+ "type": "SEARCH",+ "ui_element": "range",+ "value": 0.9,+ "visible": true+ },+ "search.engine.web.openlibrary.strengths": {+ "category": "openlibrary",+ "description": "Key strengths of Open Library.",+ "editable": true,+ "name": "Strengths",+ "type": "SEARCH",+ "ui_element": "json",+ "value": ["books", "literature", "metadata", "covers", "full text", "Internet Archive"],+ "visible": true+ },+ "search.engine.web.openlibrary.weaknesses": {+ "category": "openlibrary",+ "description": "Limitations of Open Library.",+ "editable": true,+ "name": "Weaknesses",+ "type": "SEARCH",+ "ui_element": "json",+ "value": ["books only", "variable metadata quality", "English focus"],+ "visible": true+ },+ "search.engine.web.openlibrary.default_params.max_results": {+ "category": "openlibrary",+ "description": "Maximum number of results to retrieve from Open Library.",+ "editable": true,+ "max_value": 100,+ "min_value": 1,+ "name": "Max Results",+ "type": "SEARCH",+ "ui_element": "number",+ "value": 20,+ "visible": true+ }+}diff --git a/src/local_deep_research/defaults/settings_pubchem.json b/src/local_deep_research/defaults/settings_pubchem.jsonnew file mode 100644index 0000000000..ed0891adab--- /dev/null+++ b/src/local_deep_research/defaults/settings_pubchem.json@@ -0,0 +1,128 @@+{+ "search.engine.web.pubchem": {+ "category": "pubchem",+ "description": "PubChem search engine configuration",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "PubChem Search Engine",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "json",+ "value": {+ "module_path": ".engines.search_engine_pubchem",+ "class_name": "PubChemSearchEngine",+ "requires_api_key": false,+ "requires_llm": true,+ "description": "Search millions of chemical compounds with structures, properties, and bioactivity data.",+ "reliability": 0.95+ },+ "visible": false+ },+ "search.engine.web.pubchem.display_name": {+ "category": "pubchem",+ "description": "Display name for PubChem search engine.",+ "editable": false,+ "name": "Display Name",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "PubChem",+ "visible": false+ },+ "search.engine.web.pubchem.description": {+ "category": "pubchem",+ "description": "Human-readable description of the search engine.",+ "editable": false,+ "name": "Description",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "Search millions of chemical compounds with structures, properties, and bioactivity data.",+ "visible": false+ },+ "search.engine.web.pubchem.module_path": {+ "category": "pubchem",+ "description": "Python module path for PubChem search engine.",+ "editable": false,+ "name": "Module Path",+ "type": "SEARCH",+ "ui_element": "text",+ "value": ".engines.search_engine_pubchem",+ "visible": false+ },+ "search.engine.web.pubchem.class_name": {+ "category": "pubchem",+ "description": "Python class implementing PubChem search.",+ "editable": false,+ "name": "Class Name",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "PubChemSearchEngine",+ "visible": false+ },+ "search.engine.web.pubchem.requires_api_key": {+ "category": "pubchem",+ "description": "PubChem is free and does not require an API key.",+ "editable": false,+ "name": "Requires API Key",+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": false,+ "visible": false+ },+ "search.engine.web.pubchem.reliability": {+ "category": "pubchem",+ "description": "Reliability score for PubChem.",+ "editable": true,+ "name": "Reliability",+ "max_value": 1.0,+ "min_value": 0.0,+ "step": 0.05,+ "type": "SEARCH",+ "ui_element": "range",+ "value": 0.95,+ "visible": true+ },+ "search.engine.web.pubchem.strengths": {+ "category": "pubchem",+ "description": "Key strengths of PubChem.",+ "editable": true,+ "name": "Strengths",+ "type": "SEARCH",+ "ui_element": "json",+ "value": ["chemistry", "compounds", "drug information", "molecular properties", "bioactivity"],+ "visible": true+ },+ "search.engine.web.pubchem.weaknesses": {+ "category": "pubchem",+ "description": "Limitations of PubChem.",+ "editable": true,+ "name": "Weaknesses",+ "type": "SEARCH",+ "ui_element": "json",+ "value": ["chemistry only", "technical data", "requires chemical knowledge"],+ "visible": true+ },+ "search.engine.web.pubchem.default_params.max_results": {+ "category": "pubchem",+ "description": "Maximum number of results to retrieve from PubChem.",+ "editable": true,+ "max_value": 50,+ "min_value": 1,+ "name": "Max Results",+ "type": "SEARCH",+ "ui_element": "number",+ "value": 10,+ "visible": true+ },+ "search.engine.web.pubchem.default_params.include_synonyms": {+ "category": "pubchem",+ "description": "Include compound synonyms in full content results.",+ "editable": true,+ "name": "Include Synonyms",+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": true,+ "visible": true+ }+}diff --git a/src/local_deep_research/defaults/settings_stackexchange.json b/src/local_deep_research/defaults/settings_stackexchange.jsonnew file mode 100644index 0000000000..e4dc66f474--- /dev/null+++ b/src/local_deep_research/defaults/settings_stackexchange.json@@ -0,0 +1,129 @@+{+ "search.engine.web.stackexchange": {+ "category": "stackexchange",+ "description": "Stack Exchange search engine configuration",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "Stack Exchange Search Engine",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "json",+ "value": {+ "module_path": ".engines.search_engine_stackexchange",+ "class_name": "StackExchangeSearchEngine",+ "requires_api_key": false,+ "requires_llm": true,+ "description": "Search Stack Overflow and other Q&A sites for programming answers.",+ "reliability": 0.9+ },+ "visible": false+ },+ "search.engine.web.stackexchange.display_name": {+ "category": "stackexchange",+ "description": "Display name for Stack Exchange search engine.",+ "editable": false,+ "name": "Display Name",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "Stack Exchange",+ "visible": false+ },+ "search.engine.web.stackexchange.description": {+ "category": "stackexchange",+ "description": "Human-readable description of the search engine.",+ "editable": false,+ "name": "Description",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "Search Stack Overflow and other Q&A sites for programming answers.",+ "visible": false+ },+ "search.engine.web.stackexchange.module_path": {+ "category": "stackexchange",+ "description": "Python module path for Stack Exchange search engine.",+ "editable": false,+ "name": "Module Path",+ "type": "SEARCH",+ "ui_element": "text",+ "value": ".engines.search_engine_stackexchange",+ "visible": false+ },+ "search.engine.web.stackexchange.class_name": {+ "category": "stackexchange",+ "description": "Python class implementing Stack Exchange search.",+ "editable": false,+ "name": "Class Name",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "StackExchangeSearchEngine",+ "visible": false+ },+ "search.engine.web.stackexchange.requires_api_key": {+ "category": "stackexchange",+ "description": "Stack Exchange is free without an API key (300 requests/day).",+ "editable": false,+ "name": "Requires API Key",+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": false,+ "visible": false+ },+ "search.engine.web.stackexchange.reliability": {+ "category": "stackexchange",+ "description": "Reliability score for Stack Exchange.",+ "editable": true,+ "name": "Reliability",+ "max_value": 1.0,+ "min_value": 0.0,+ "step": 0.05,+ "type": "SEARCH",+ "ui_element": "range",+ "value": 0.9,+ "visible": true+ },+ "search.engine.web.stackexchange.strengths": {+ "category": "stackexchange",+ "description": "Key strengths of Stack Exchange.",+ "editable": true,+ "name": "Strengths",+ "type": "SEARCH",+ "ui_element": "json",+ "value": ["programming", "Q&A", "code examples", "community moderated", "multiple sites"],+ "visible": true+ },+ "search.engine.web.stackexchange.weaknesses": {+ "category": "stackexchange",+ "description": "Limitations of Stack Exchange.",+ "editable": true,+ "name": "Weaknesses",+ "type": "SEARCH",+ "ui_element": "json",+ "value": ["technical focus", "rate limited", "Q&A format only"],+ "visible": true+ },+ "search.engine.web.stackexchange.default_params.max_results": {+ "category": "stackexchange",+ "description": "Maximum number of results to retrieve from Stack Exchange.",+ "editable": true,+ "max_value": 100,+ "min_value": 1,+ "name": "Max Results",+ "type": "SEARCH",+ "ui_element": "number",+ "value": 20,+ "visible": true+ },+ "search.engine.web.stackexchange.default_params.site": {+ "category": "stackexchange",+ "description": "Stack Exchange site to search (stackoverflow, serverfault, superuser, etc.).",+ "editable": true,+ "name": "Site",+ "type": "SEARCH",+ "ui_element": "select",+ "value": "stackoverflow",+ "options": ["stackoverflow", "serverfault", "superuser", "askubuntu", "unix", "math", "physics", "stats", "security", "dba"],+ "visible": true+ }+}diff --git a/src/local_deep_research/defaults/settings_zenodo.json b/src/local_deep_research/defaults/settings_zenodo.jsonnew file mode 100644index 0000000000..70c0bcbd45--- /dev/null+++ b/src/local_deep_research/defaults/settings_zenodo.json@@ -0,0 +1,118 @@+{+ "search.engine.web.zenodo": {+ "category": "zenodo",+ "description": "Zenodo search engine configuration",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "Zenodo Search Engine",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "json",+ "value": {+ "module_path": ".engines.search_engine_zenodo",+ "class_name": "ZenodoSearchEngine",+ "requires_api_key": false,+ "requires_llm": true,+ "description": "Search millions of research datasets, software, and publications with DOIs.",+ "reliability": 0.95+ },+ "visible": false+ },+ "search.engine.web.zenodo.display_name": {+ "category": "zenodo",+ "description": "Display name for Zenodo search engine.",+ "editable": false,+ "name": "Display Name",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "Zenodo",+ "visible": false+ },+ "search.engine.web.zenodo.description": {+ "category": "zenodo",+ "description": "Human-readable description of the search engine.",+ "editable": false,+ "name": "Description",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "Search millions of research datasets, software, and publications with DOIs.",+ "visible": false+ },+ "search.engine.web.zenodo.module_path": {+ "category": "zenodo",+ "description": "Python module path for Zenodo search engine.",+ "editable": false,+ "name": "Module Path",+ "type": "SEARCH",+ "ui_element": "text",+ "value": ".engines.search_engine_zenodo",+ "visible": false+ },+ "search.engine.web.zenodo.class_name": {+ "category": "zenodo",+ "description": "Python class implementing Zenodo search.",+ "editable": false,+ "name": "Class Name",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "ZenodoSearchEngine",+ "visible": false+ },+ "search.engine.web.zenodo.requires_api_key": {+ "category": "zenodo",+ "description": "Zenodo is free and does not require an API key for search.",+ "editable": false,+ "name": "Requires API Key",+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": false,+ "visible": false+ },+ "search.engine.web.zenodo.reliability": {+ "category": "zenodo",+ "description": "Reliability score for Zenodo.",+ "editable": true,+ "name": "Reliability",+ "max_value": 1.0,+ "min_value": 0.0,+ "step": 0.05,+ "type": "SEARCH",+ "ui_element": "range",+ "value": 0.95,+ "visible": true+ },+ "search.engine.web.zenodo.strengths": {+ "category": "zenodo",+ "description": "Key strengths of Zenodo.",+ "editable": true,+ "name": "Strengths",+ "type": "SEARCH",+ "ui_element": "json",+ "value": ["research data", "datasets", "DOIs", "software", "open access", "CERN"],+ "visible": true+ },+ "search.engine.web.zenodo.weaknesses": {+ "category": "zenodo",+ "description": "Limitations of Zenodo.",+ "editable": true,+ "name": "Weaknesses",+ "type": "SEARCH",+ "ui_element": "json",+ "value": ["research focus", "variable quality", "metadata only"],+ "visible": true+ },+ "search.engine.web.zenodo.default_params.max_results": {+ "category": "zenodo",+ "description": "Maximum number of results to retrieve from Zenodo.",+ "editable": true,+ "max_value": 100,+ "min_value": 1,+ "name": "Max Results",+ "type": "SEARCH",+ "ui_element": "number",+ "value": 20,+ "visible": true+ }+}diff --git a/src/local_deep_research/security/module_whitelist.py b/src/local_deep_research/security/module_whitelist.pyindex 8a4f0258fc..3202379938 100644--- a/src/local_deep_research/security/module_whitelist.py+++ b/src/local_deep_research/security/module_whitelist.py@@ -53,9 +53,14 @@ ALLOWED_MODULE_PATHS: frozenset[str] = frozenset(".engines.search_engine_serper",".engines.search_engine_serpapi",".engines.search_engine_tavily",+ ".engines.search_engine_gutenberg",+ ".engines.search_engine_openlibrary",+ ".engines.search_engine_pubchem",+ ".engines.search_engine_stackexchange",".engines.search_engine_wayback",".engines.search_engine_wikipedia",".engines.search_engine_wikinews",+ ".engines.search_engine_zenodo",".search_engine_base",])@@ -75,6 +80,7 @@ ALLOWED_CLASS_NAMES: frozenset[str] = frozenset("CollectionSearchEngine","DuckDuckGoSearchEngine","ElasticsearchSearchEngine",+ "GutenbergSearchEngine","ExaSearchEngine","FullSearchResults","GitHubSearchEngine",@@ -85,8 +91,10 @@ ALLOWED_CLASS_NAMES: frozenset[str] = frozenset("MojeekSearchEngine","NasaAdsSearchEngine","OpenAlexSearchEngine",+ "OpenLibrarySearchEngine","PaperlessSearchEngine","ParallelSearchEngine",+ "PubChemSearchEngine","PubMedSearchEngine","RetrieverSearchEngine","ScaleSerpSearchEngine",@@ -94,10 +102,12 @@ ALLOWED_CLASS_NAMES: frozenset[str] = frozenset("SemanticScholarSearchEngine","SerpAPISearchEngine","SerperSearchEngine",+ "StackExchangeSearchEngine","TavilySearchEngine","WaybackSearchEngine","WikinewsSearchEngine","WikipediaSearchEngine",+ "ZenodoSearchEngine",])diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex 77aeae6d01..b97717a924 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -1583,8 +1583,14 @@ def _get_engine_icon_and_category(is_news = engine_data.get("is_news", False)is_code = engine_data.get("is_code", False)+ # Check books attribute+ if engine_class:+ is_books = getattr(engine_class, "is_books", False)+ else:+ is_books = engine_data.get("is_books", False)+# Return icon and category based on engine type- # Priority: local > scientific > news > code > generic > default+ # Priority: local > scientific > news > code > books > generic > defaultif is_local:return "📁", "Local RAG"elif is_scientific:@@ -1593,6 +1599,8 @@ def _get_engine_icon_and_category(return "📰", "News"elif is_code:return "💻", "Code"+ elif is_books:+ return "📚", "Books"elif is_generic:return "🌐", "Web Search"else:@@ -1656,9 +1664,17 @@ def api_get_available_search_engines():engine_data, engine_class)- # Build display name with icon and category+ # Check if engine requires an API key+ requires_api_key = engine_data.get(+ "requires_api_key", False+ )++ # Build display name with icon, category, and API key statusbase_name = engine_data.get("display_name", engine_id)- label = f"{icon} {base_name} ({category})"+ if requires_api_key:+ label = f"{icon} {base_name} ({category}, API key)"+ else:+ label = f"{icon} {base_name} ({category}, Free)"# Check if engine is a favoriteis_favorite = engine_id in favorites@@ -1669,6 +1685,7 @@ def api_get_available_search_engines():"strengths": engine_data.get("strengths", []),"icon": icon,"category": category,+ "requires_api_key": requires_api_key,"is_favorite": is_favorite,}@@ -1678,6 +1695,7 @@ def api_get_available_search_engines():"label": label,"icon": icon,"category": category,+ "requires_api_key": requires_api_key,"is_favorite": is_favorite,})diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_gutenberg.py b/src/local_deep_research/web_search_engines/engines/search_engine_gutenberg.pynew file mode 100644index 0000000000..8194f72457--- /dev/null+++ b/src/local_deep_research/web_search_engines/engines/search_engine_gutenberg.py@@ -0,0 +1,361 @@+"""Project Gutenberg search engine via Gutendex API."""++from typing import Any, Dict, List, Optional++import requests+from langchain_core.language_models import BaseLLM+from loguru import logger++from ...security.safe_requests import safe_get+from ..rate_limiting import RateLimitError+from ..search_engine_base import BaseSearchEngine+++class GutenbergSearchEngine(BaseSearchEngine):+ """+ Project Gutenberg search engine via Gutendex API.++ Provides access to 70,000+ free public domain books with full text.+ No authentication required.+ """++ is_public = True+ is_generic = False+ is_scientific = False+ is_books = True++ def __init__(+ self,+ max_results: int = 10,+ languages: Optional[str] = None,+ topic: Optional[str] = None,+ author_year_start: Optional[int] = None,+ author_year_end: Optional[int] = None,+ copyright_filter: Optional[bool] = None,+ sort: str = "popular",+ llm: Optional[BaseLLM] = None,+ max_filtered_results: Optional[int] = None,+ settings_snapshot: Optional[Dict[str, Any]] = None,+ **kwargs,+ ):+ """+ Initialize the Project Gutenberg search engine.++ Args:+ max_results: Maximum number of search results+ languages: Filter by language codes (e.g., 'en', 'fr,de')+ topic: Filter by subject/bookshelf topic+ author_year_start: Filter authors born after this year+ author_year_end: Filter authors born before this year+ copyright_filter: Filter by copyright status (True/False/None)+ sort: Sort order ('popular', 'ascending', 'descending')+ llm: Language model for relevance filtering+ max_filtered_results: Maximum results after filtering+ settings_snapshot: Settings snapshot for thread context+ """+ super().__init__(+ llm=llm,+ max_filtered_results=max_filtered_results,+ max_results=max_results,+ settings_snapshot=settings_snapshot,+ **kwargs,+ )++ self.languages = languages+ self.topic = topic+ self.author_year_start = author_year_start+ self.author_year_end = author_year_end+ self.copyright_filter = copyright_filter+ self.sort = sort++ self.base_url = "https://gutendex.com"+ self.search_url = f"{self.base_url}/books/"++ # User-Agent header for API requests+ self.headers = {+ "User-Agent": "LocalDeepResearch/1.0 (https://github.com/LearningCircuit/local-deep-research)"+ }++ def _build_query_params(self, query: str) -> Dict[str, Any]:+ """Build query parameters for the API request."""+ params = {}+ if query:+ params["search"] = query++ if self.languages:+ params["languages"] = self.languages++ if self.topic:+ params["topic"] = self.topic++ if self.author_year_start is not None:+ params["author_year_start"] = self.author_year_start++ if self.author_year_end is not None:+ params["author_year_end"] = self.author_year_end++ if self.copyright_filter is not None:+ params["copyright"] = str(self.copyright_filter).lower()++ if self.sort and self.sort != "popular":+ params["sort"] = self.sort++ return params++ def _get_best_format_url(self, formats: Dict[str, str]) -> Optional[str]:+ """Get the best available format URL for reading."""+ # Priority order for reading formats+ priority = [+ "text/html",+ "text/html; charset=utf-8",+ "text/plain; charset=utf-8",+ "text/plain",+ "application/epub+zip",+ "application/x-mobipocket-ebook",+ "application/pdf",+ ]++ for mime_type in priority:+ if mime_type in formats:+ return formats[mime_type]++ # Return first available if no priority match+ if formats:+ return next(iter(formats.values()))+ return None++ def _parse_authors(self, authors: List[Dict]) -> List[str]:+ """Parse author information."""+ result = []+ for author in authors[:5]:+ name = author.get("name", "")+ if name:+ # Format: "Last, First" -> "First Last"+ if ", " in name:+ parts = name.split(", ", 1)+ name = f"{parts[1]} {parts[0]}"+ result.append(name)+ return result++ def _get_previews(self, query: str) -> List[Dict[str, Any]]:+ """+ Get preview information for Project Gutenberg books.++ Args:+ query: The search query++ Returns:+ List of preview dictionaries+ """+ logger.info(f"Getting Gutenberg previews for query: {query}")++ # Apply rate limiting+ self._last_wait_time = self.rate_tracker.apply_rate_limit(+ self.engine_type+ )++ try:+ params = self._build_query_params(query)+ response = safe_get(+ self.search_url,+ params=params,+ headers=self.headers,+ timeout=30,+ )++ self._raise_if_rate_limit(response.status_code)++ response.raise_for_status()+ data = response.json()++ results = data.get("results", [])+ total = data.get("count", 0)+ logger.info(+ f"Found {total} Gutenberg results, returning {len(results)}"+ )++ previews = []+ for book in results[: self.max_results]:+ try:+ book_id = book.get("id")+ title = book.get("title", "Untitled")++ # Get authors+ authors = self._parse_authors(book.get("authors", []))++ # Get subjects and bookshelves+ subjects = book.get("subjects", [])[:5]+ bookshelves = book.get("bookshelves", [])[:3]++ # Get languages+ languages = book.get("languages", [])++ # Get formats+ formats = book.get("formats", {})+ read_url = self._get_best_format_url(formats)++ # Build Gutenberg URL+ gutenberg_url = (+ f"https://www.gutenberg.org/ebooks/{book_id}"+ )++ # Get summaries if available+ summaries = book.get("summaries", [])+ summary_text = ""+ if summaries and isinstance(summaries, list):+ # Use the first summary, strip whitespace+ first_summary = summaries[0] if summaries else ""+ if isinstance(first_summary, str):+ summary_text = first_summary.strip()[:300]++ # Build snippet with summary for richer content+ snippet_parts = []+ if summary_text:+ snippet_parts.append(summary_text)+ if authors:+ snippet_parts.append(f"By {', '.join(authors[:2])}")+ if subjects and not summary_text:+ snippet_parts.append(+ f"Subjects: {', '.join(subjects[:3])}"+ )+ if bookshelves and not summary_text:+ snippet_parts.append(+ f"Bookshelves: {', '.join(bookshelves[:2])}"+ )+ snippet = ". ".join(snippet_parts)++ # Check for cover image+ cover_url = formats.get("image/jpeg")++ preview = {+ "id": str(book_id),+ "title": title,+ "link": gutenberg_url,+ "snippet": snippet,+ "authors": authors,+ "subjects": subjects,+ "bookshelves": bookshelves,+ "languages": languages,+ "download_count": book.get("download_count", 0),+ "read_url": read_url,+ "cover_url": cover_url,+ "formats": list(formats.keys()),+ "copyright": book.get("copyright", False),+ "source": "Project Gutenberg",+ "_raw": book,+ }++ previews.append(preview)++ except Exception:+ logger.exception("Error parsing Gutenberg book")+ continue++ return previews++ except (requests.RequestException, ValueError) as e:+ logger.exception("Gutendex API request failed")+ self._raise_if_rate_limit(e)+ return []++ def _get_full_content(+ self, relevant_items: List[Dict[str, Any]]+ ) -> List[Dict[str, Any]]:+ """+ Get full content for the relevant Gutenberg books.++ Args:+ relevant_items: List of relevant preview dictionaries++ Returns:+ List of result dictionaries with full content+ """+ logger.info(+ f"Getting full content for {len(relevant_items)} Gutenberg books"+ )++ results = []+ for item in relevant_items:+ result = item.copy()++ raw = item.get("_raw", {})+ if raw:+ # Get all subjects+ result["subjects"] = raw.get("subjects", [])++ # Get all bookshelves+ result["bookshelves"] = raw.get("bookshelves", [])++ # Get translators+ translators = raw.get("translators", [])+ result["translators"] = self._parse_authors(translators)++ # Build content summary+ content_parts = []+ if result.get("authors"):+ content_parts.append(+ f"Authors: {', '.join(result['authors'])}"+ )+ if result.get("subjects"):+ content_parts.append(+ f"Subjects: {', '.join(result['subjects'][:5])}"+ )+ if result.get("bookshelves"):+ content_parts.append(+ f"Bookshelves: {', '.join(result['bookshelves'])}"+ )+ if result.get("download_count"):+ content_parts.append(+ f"Downloads: {result['download_count']}"+ )+ if result.get("read_url"):+ content_parts.append(f"Read online: {result['read_url']}")++ result["content"] = "\n".join(content_parts)++ # Clean up internal fields+ if "_raw" in result:+ del result["_raw"]++ results.append(result)++ return results++ def get_book(self, book_id: int) -> Optional[Dict[str, Any]]:+ """+ Get a specific book by Gutenberg ID.++ Args:+ book_id: The Project Gutenberg book ID++ Returns:+ Book dictionary or None+ """+ try:+ url = f"{self.base_url}/books/{book_id}"+ response = safe_get(url, headers=self.headers, timeout=30)+ self._raise_if_rate_limit(response.status_code)+ response.raise_for_status()+ return response.json()+ except RateLimitError:+ raise+ except Exception:+ logger.exception(f"Error fetching Gutenberg book {book_id}")+ return None++ def search_by_topic(self, topic: str) -> List[Dict[str, Any]]:+ """+ Search books by topic/subject.++ Args:+ topic: The topic to search for++ Returns:+ List of matching books+ """+ original_topic = self.topic+ try:+ self.topic = topic+ return self.run("")+ finally:+ self.topic = original_topicdiff --git a/src/local_deep_research/web_search_engines/engines/search_engine_openlibrary.py b/src/local_deep_research/web_search_engines/engines/search_engine_openlibrary.pynew file mode 100644index 0000000000..54c992759a--- /dev/null+++ b/src/local_deep_research/web_search_engines/engines/search_engine_openlibrary.py@@ -0,0 +1,372 @@+"""Open Library search engine for books and literature."""++import html+from typing import Any, Dict, List, Optional++import requests+from langchain_core.language_models import BaseLLM+from loguru import logger++from ...security.safe_requests import safe_get+from ..rate_limiting import RateLimitError+from ..search_engine_base import BaseSearchEngine+++class OpenLibrarySearchEngine(BaseSearchEngine):+ """+ Open Library search engine for books and literature.++ Provides access to 2M+ books with metadata, covers, and reading lists.+ No authentication required. Part of the Internet Archive.+ """++ is_public = True+ is_generic = False+ is_scientific = False+ is_books = True # New category for book search++ def __init__(+ self,+ max_results: int = 10,+ sort: str = "relevance",+ language: Optional[str] = None,+ search_field: Optional[str] = None,+ llm: Optional[BaseLLM] = None,+ max_filtered_results: Optional[int] = None,+ settings_snapshot: Optional[Dict[str, Any]] = None,+ **kwargs,+ ):+ """+ Initialize the Open Library search engine.++ Args:+ max_results: Maximum number of search results+ sort: Sort order ('relevance', 'new', 'old', 'random')+ language: Filter by language code (e.g., 'eng', 'fre', 'ger')+ search_field: Search in specific field ('title', 'author', 'subject')+ llm: Language model for relevance filtering+ max_filtered_results: Maximum results after filtering+ settings_snapshot: Settings snapshot for thread context+ """+ super().__init__(+ llm=llm,+ max_filtered_results=max_filtered_results,+ max_results=max_results,+ settings_snapshot=settings_snapshot,+ **kwargs,+ )++ self.sort = sort+ self.language = language+ self.search_field = search_field++ self.base_url = "https://openlibrary.org"+ self.search_url = f"{self.base_url}/search.json"++ # User-Agent header is important for Open Library API+ # They may block requests without a proper User-Agent+ self.headers = {+ "User-Agent": "LocalDeepResearch/1.0 (https://github.com/LearningCircuit/local-deep-research)"+ }++ def _build_query_params(self, query: str) -> Dict[str, Any]:+ """Build query parameters for the API request."""+ params = {+ "limit": min(self.max_results, 100),+ "fields": "key,title,author_name,author_key,first_publish_year,"+ "publisher,language,subject,isbn,cover_i,edition_count,"+ "ebook_access,has_fulltext,ia,description",+ }++ # Build query based on search field+ if self.search_field == "title":+ params["title"] = query+ elif self.search_field == "author":+ params["author"] = query+ elif self.search_field == "subject":+ params["subject"] = query+ else:+ params["q"] = query++ # Add sort if not relevance (default)+ if self.sort and self.sort != "relevance":+ params["sort"] = self.sort++ # Add language filter+ if self.language:+ params["language"] = self.language++ return params++ def _get_cover_url(+ self, cover_id: Optional[int], size: str = "M"+ ) -> Optional[str]:+ """Get cover image URL for a book."""+ if not cover_id:+ return None+ return f"https://covers.openlibrary.org/b/id/{cover_id}-{size}.jpg"++ def _get_previews(self, query: str) -> List[Dict[str, Any]]:+ """+ Get preview information for Open Library books.++ Args:+ query: The search query++ Returns:+ List of preview dictionaries+ """+ logger.info(f"Getting Open Library previews for query: {query}")++ # Apply rate limiting+ self._last_wait_time = self.rate_tracker.apply_rate_limit(+ self.engine_type+ )++ try:+ params = self._build_query_params(query)+ response = safe_get(+ self.search_url,+ params=params,+ headers=self.headers,+ timeout=30,+ )++ self._raise_if_rate_limit(response.status_code)++ response.raise_for_status()+ data = response.json()++ docs = data.get("docs", [])+ total_found = data.get("num_found", 0)+ logger.info(+ f"Found {total_found} Open Library results, returning {len(docs)}"+ )++ previews = []+ for doc in docs:+ try:+ # Get work key and build URL+ work_key = doc.get("key", "")+ link = f"{self.base_url}{work_key}" if work_key else ""++ # Get title (decode HTML entities)+ title = html.unescape(doc.get("title", "Untitled"))++ # Get authors+ authors = doc.get("author_name", [])+ if isinstance(authors, str):+ authors = [authors]+ authors = authors[:5] # Limit to 5 authors++ # Get first publish year+ first_publish_year = doc.get("first_publish_year")++ # Get publishers+ publishers = doc.get("publisher", [])+ if isinstance(publishers, str):+ publishers = [publishers]+ publisher = publishers[0] if publishers else ""++ # Get subjects+ subjects = doc.get("subject", [])+ if isinstance(subjects, str):+ subjects = [subjects]+ subjects = subjects[:5] # Limit to 5 subjects++ # Get ISBNs+ isbns = doc.get("isbn", [])+ if isinstance(isbns, str):+ isbns = [isbns]+ isbn = isbns[0] if isbns else None++ # Get cover+ cover_id = doc.get("cover_i")+ cover_url = self._get_cover_url(cover_id)++ # Get description if available+ description = doc.get("description", "")+ # Description can be a string or a dict with "value" key+ if isinstance(description, dict):+ description = description.get("value", "")+ elif isinstance(description, list):+ description = (+ " ".join(str(d) for d in description)+ if description+ else ""+ )++ # Build snippet with description for richer content+ snippet_parts = []+ if description:+ snippet_parts.append(description[:300])+ if authors:+ snippet_parts.append(f"By {', '.join(authors[:3])}")+ if first_publish_year:+ snippet_parts.append(+ f"First published: {first_publish_year}"+ )+ if subjects and not description:+ snippet_parts.append(+ f"Subjects: {', '.join(subjects[:3])}"+ )+ snippet = ". ".join(snippet_parts)++ # Check availability+ has_fulltext = doc.get("has_fulltext", False)+ ebook_access = doc.get("ebook_access", "no_ebook")+ ia_ids = doc.get("ia", [])+ if isinstance(ia_ids, str):+ ia_ids = [ia_ids]++ preview = {+ "id": work_key,+ "title": title,+ "link": link,+ "snippet": snippet,+ "authors": authors,+ "first_publish_year": first_publish_year,+ "publisher": publisher,+ "subjects": subjects,+ "isbn": isbn,+ "cover_url": cover_url,+ "edition_count": doc.get("edition_count", 0),+ "has_fulltext": has_fulltext,+ "ebook_access": ebook_access,+ "internet_archive_ids": ia_ids[:3] if ia_ids else [],+ "source": "Open Library",+ "_raw": doc,+ }++ previews.append(preview)++ except Exception:+ logger.exception("Error parsing Open Library item")+ continue++ return previews++ except (requests.RequestException, ValueError) as e:+ logger.exception("Open Library API request failed")+ self._raise_if_rate_limit(e)+ return []++ def _get_full_content(+ self, relevant_items: List[Dict[str, Any]]+ ) -> List[Dict[str, Any]]:+ """+ Get full content for the relevant Open Library books.++ Args:+ relevant_items: List of relevant preview dictionaries++ Returns:+ List of result dictionaries with full content+ """+ logger.info(+ f"Getting full content for {len(relevant_items)} Open Library books"+ )++ results = []+ for item in relevant_items:+ result = item.copy()++ raw = item.get("_raw", {})+ if raw:+ # Get all languages+ languages = raw.get("language", [])+ if isinstance(languages, str):+ languages = [languages]+ result["languages"] = languages++ # Get all subjects+ result["subjects"] = raw.get("subject", [])+ if isinstance(result["subjects"], str):+ result["subjects"] = [result["subjects"]]++ # Get all publishers+ result["publishers"] = raw.get("publisher", [])+ if isinstance(result["publishers"], str):+ result["publishers"] = [result["publishers"]]++ # Build content summary+ content_parts = []+ if result.get("authors"):+ content_parts.append(+ f"Authors: {', '.join(result['authors'])}"+ )+ if result.get("first_publish_year"):+ content_parts.append(+ f"First published: {result['first_publish_year']}"+ )+ if result.get("edition_count"):+ content_parts.append(f"Editions: {result['edition_count']}")+ if result.get("subjects"):+ subjects = result["subjects"]+ if isinstance(subjects, list):+ content_parts.append(+ f"Subjects: {', '.join(subjects[:10])}"+ )+ if result.get("has_fulltext"):+ content_parts.append(+ "Full text available on Internet Archive"+ )++ result["content"] = "\n".join(content_parts)++ # Clean up internal fields+ if "_raw" in result:+ del result["_raw"]++ results.append(result)++ return results++ def get_book_by_isbn(self, isbn: str) -> Optional[Dict[str, Any]]:+ """+ Get a specific book by ISBN.++ Args:+ isbn: The book ISBN (10 or 13 digit)++ Returns:+ Book dictionary or None+ """+ try:+ url = f"{self.base_url}/isbn/{isbn}.json"+ response = safe_get(url, headers=self.headers, timeout=30)+ self._raise_if_rate_limit(response.status_code)+ response.raise_for_status()+ return response.json()+ except RateLimitError:+ raise+ except Exception:+ logger.exception(f"Error fetching book by ISBN {isbn}")+ return None++ def get_author(self, author_key: str) -> Optional[Dict[str, Any]]:+ """+ Get author information.++ Args:+ author_key: The author key (e.g., '/authors/OL23919A')++ Returns:+ Author dictionary or None+ """+ try:+ if not author_key or not author_key.startswith("/authors/"):+ logger.warning(+ "Invalid author_key format: expected '/authors/...' prefix"+ )+ return None+ url = f"{self.base_url}{author_key}.json"+ response = safe_get(url, headers=self.headers, timeout=30)+ self._raise_if_rate_limit(response.status_code)+ response.raise_for_status()+ return response.json()+ except RateLimitError:+ raise+ except Exception:+ logger.exception(f"Error fetching author {author_key}")+ return Nonediff --git a/src/local_deep_research/web_search_engines/engines/search_engine_pubchem.py b/src/local_deep_research/web_search_engines/engines/search_engine_pubchem.pynew file mode 100644index 0000000000..f20eab09e3--- /dev/null+++ b/src/local_deep_research/web_search_engines/engines/search_engine_pubchem.py@@ -0,0 +1,493 @@+"""PubChem search engine for chemical compound information."""++from typing import Any, Dict, List, Optional+from urllib.parse import quote++from langchain_core.language_models import BaseLLM+from loguru import logger++from ...security.safe_requests import safe_get+from ..rate_limiting import RateLimitError+from ..search_engine_base import BaseSearchEngine+++class PubChemSearchEngine(BaseSearchEngine):+ """+ PubChem search engine for chemical compound information.++ Provides access to chemical structures, properties, and bioactivity data.+ No authentication required.+ """++ is_public = True+ is_generic = False+ is_scientific = True+ is_code = False++ def __init__(+ self,+ max_results: int = 10,+ include_synonyms: bool = True,+ llm: Optional[BaseLLM] = None,+ max_filtered_results: Optional[int] = None,+ settings_snapshot: Optional[Dict[str, Any]] = None,+ **kwargs,+ ):+ """+ Initialize the PubChem search engine.++ Args:+ max_results: Maximum number of search results+ include_synonyms: Whether to include compound synonyms+ llm: Language model for relevance filtering+ max_filtered_results: Maximum results after filtering+ settings_snapshot: Settings snapshot for thread context+ """+ super().__init__(+ llm=llm,+ max_filtered_results=max_filtered_results,+ max_results=max_results,+ settings_snapshot=settings_snapshot,+ **kwargs,+ )++ self.include_synonyms = include_synonyms+ self.base_url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug"+ self.autocomplete_url = (+ "https://pubchem.ncbi.nlm.nih.gov/rest/autocomplete"+ )++ # User-Agent header for API requests+ self.headers = {+ "User-Agent": "LocalDeepResearch/1.0 (https://github.com/LearningCircuit/local-deep-research)"+ }++ def _search_compounds(self, query: str) -> List[str]:+ """Search for compound names matching the query."""+ try:+ url = (+ f"{self.autocomplete_url}/compound/{quote(query, safe='')}/json"+ )+ params = {"limit": self.max_results * 2} # Get extra for filtering++ response = safe_get(+ url, params=params, headers=self.headers, timeout=30+ )+ self._raise_if_rate_limit(response.status_code)+ response.raise_for_status()+ data = response.json()++ terms = data.get("dictionary_terms", {}).get("compound", [])+ return terms++ except RateLimitError:+ raise+ except Exception:+ logger.exception("PubChem autocomplete search failed")+ return []++ def _get_compound_by_name(self, name: str) -> Optional[Dict[str, Any]]:+ """Get compound information by name."""+ try:+ self.rate_tracker.apply_rate_limit(self.engine_type)+ # Get CID first+ url = f"{self.base_url}/compound/name/{quote(name, safe='')}/cids/JSON"+ response = safe_get(url, headers=self.headers, timeout=30)++ if response.status_code == 404:+ return None+ self._raise_if_rate_limit(response.status_code)++ response.raise_for_status()+ data = response.json()+ cids = data.get("IdentifierList", {}).get("CID", [])++ if not cids:+ return None++ cid = cids[0]++ # Get compound properties+ properties = self._get_compound_properties(cid)++ # Get compound description+ description = self._get_compound_description(cid)++ return {+ "cid": cid,+ "name": name,+ "properties": properties,+ "description": description,+ }++ except RateLimitError:+ raise+ except Exception:+ logger.exception(f"Error fetching PubChem compound: {name}")+ return None++ def _get_compound_properties(self, cid: int) -> Dict[str, Any]:+ """Get properties for a compound by CID."""+ try:+ self.rate_tracker.apply_rate_limit(self.engine_type)+ properties_list = [+ "MolecularFormula",+ "MolecularWeight",+ "IUPACName",+ "CanonicalSMILES",+ "IsomericSMILES",+ "InChI",+ "InChIKey",+ "XLogP",+ "TPSA",+ "Complexity",+ "Charge",+ "HBondDonorCount",+ "HBondAcceptorCount",+ "RotatableBondCount",+ "HeavyAtomCount",+ ]++ url = f"{self.base_url}/compound/cid/{cid}/property/{','.join(properties_list)}/JSON"+ response = safe_get(url, headers=self.headers, timeout=30)+ self._raise_if_rate_limit(response.status_code)+ response.raise_for_status()+ data = response.json()++ props = data.get("PropertyTable", {}).get("Properties", [])+ return props[0] if props else {}++ except RateLimitError:+ raise+ except Exception:+ logger.exception(f"Error fetching PubChem properties for CID {cid}")+ return {}++ def _get_compound_description(self, cid: int) -> str:+ """Get description for a compound by CID."""+ try:+ self.rate_tracker.apply_rate_limit(self.engine_type)+ url = f"{self.base_url}/compound/cid/{cid}/description/JSON"+ response = safe_get(url, headers=self.headers, timeout=30)++ if response.status_code == 404:+ return ""+ self._raise_if_rate_limit(response.status_code)++ response.raise_for_status()+ data = response.json()++ descriptions = data.get("InformationList", {}).get(+ "Information", []+ )+ for desc in descriptions:+ if desc.get("Description"):+ return desc.get("Description", "")++ return ""++ except RateLimitError:+ raise+ except Exception:+ logger.exception(+ f"Error fetching PubChem description for CID {cid}"+ )+ return ""++ def _get_compound_synonyms(self, cid: int, limit: int = 10) -> List[str]:+ """Get synonyms for a compound by CID."""+ try:+ self.rate_tracker.apply_rate_limit(self.engine_type)+ url = f"{self.base_url}/compound/cid/{cid}/synonyms/JSON"+ response = safe_get(url, headers=self.headers, timeout=30)++ if response.status_code == 404:+ return []+ self._raise_if_rate_limit(response.status_code)++ response.raise_for_status()+ data = response.json()++ info = data.get("InformationList", {}).get("Information", [])+ if info:+ synonyms = info[0].get("Synonym", [])+ return synonyms[:limit]+ return []++ except RateLimitError:+ raise+ except Exception:+ logger.exception(f"Error fetching PubChem synonyms for CID {cid}")+ return []++ def _get_previews(self, query: str) -> List[Dict[str, Any]]:+ """+ Get preview information for PubChem compounds.++ Args:+ query: The search query (compound name)++ Returns:+ List of preview dictionaries+ """+ logger.info(f"Getting PubChem previews for query: {query}")++ # Apply rate limiting+ self._last_wait_time = self.rate_tracker.apply_rate_limit(+ self.engine_type+ )++ # Search for matching compound names+ compound_names = self._search_compounds(query)++ if not compound_names:+ # Try direct lookup+ compound = self._get_compound_by_name(query)+ if compound:+ compound_names = [query]+ else:+ logger.info("No PubChem compounds found")+ return []++ logger.info(f"Found {len(compound_names)} potential compounds")++ previews = []+ seen_cids = set()+ for name in compound_names:+ if len(previews) >= self.max_results:+ break++ try:+ compound = self._get_compound_by_name(name)+ if not compound:+ continue++ cid = compound["cid"]++ # Deduplicate by CID (autocomplete may return+ # case variants like "Caffeine" and "caffeine")+ if cid in seen_cids:+ continue+ seen_cids.add(cid)+ properties = compound.get("properties", {})+ description = compound.get("description", "")++ # Build compound URL+ compound_url = (+ f"https://pubchem.ncbi.nlm.nih.gov/compound/{cid}"+ )++ # Get key properties+ molecular_formula = properties.get("MolecularFormula", "")+ molecular_weight = properties.get("MolecularWeight", "")+ iupac_name = properties.get("IUPACName", "")+ smiles = (+ properties.get("CanonicalSMILES", "")+ or properties.get("SMILES", "")+ or properties.get("IsomericSMILES", "")+ or properties.get("ConnectivitySMILES", "")+ )++ # Get drug-relevant properties+ xlogp = properties.get("XLogP")+ hbond_donors = properties.get("HBondDonorCount")+ hbond_acceptors = properties.get("HBondAcceptorCount")++ # Build snippet+ snippet_parts = []+ if molecular_formula:+ snippet_parts.append(f"Formula: {molecular_formula}")+ if molecular_weight:+ snippet_parts.append(f"MW: {molecular_weight}")+ if xlogp is not None:+ snippet_parts.append(f"XLogP: {xlogp}")+ if hbond_donors is not None or hbond_acceptors is not None:+ hbond_info = []+ if hbond_donors is not None:+ hbond_info.append(f"H-Donors: {hbond_donors}")+ if hbond_acceptors is not None:+ hbond_info.append(f"H-Acceptors: {hbond_acceptors}")+ snippet_parts.append(", ".join(hbond_info))+ if iupac_name:+ snippet_parts.append(f"IUPAC: {iupac_name}")+ if description:+ snippet_parts.append(description[:200])+ snippet = ". ".join(snippet_parts)++ preview = {+ "id": str(cid),+ "cid": cid,+ "title": name,+ "link": compound_url,+ "snippet": snippet,+ "molecular_formula": molecular_formula,+ "molecular_weight": molecular_weight,+ "iupac_name": iupac_name,+ "smiles": smiles,+ "inchi_key": properties.get("InChIKey", ""),+ "description": description,+ "source": "PubChem",+ "_raw": {+ "properties": properties,+ "description": description,+ },+ }++ previews.append(preview)++ except RateLimitError:+ raise+ except Exception:+ logger.exception(f"Error processing PubChem compound: {name}")+ continue++ return previews++ def _get_full_content(+ self, relevant_items: List[Dict[str, Any]]+ ) -> List[Dict[str, Any]]:+ """+ Get full content for the relevant PubChem compounds.++ Args:+ relevant_items: List of relevant preview dictionaries++ Returns:+ List of result dictionaries with full content+ """+ logger.info(+ f"Getting full content for {len(relevant_items)} PubChem compounds"+ )++ results = []+ for item in relevant_items:+ result = item.copy()++ cid = item.get("cid")+ if cid and self.include_synonyms:+ # Get synonyms+ synonyms = self._get_compound_synonyms(cid)+ result["synonyms"] = synonyms++ raw = item.get("_raw", {})+ if raw:+ properties = raw.get("properties", {})+ description = raw.get("description", "")++ # Build content summary+ content_parts = []+ content_parts.append(+ f"Compound: {result.get('title', 'Unknown')}"+ )+ if cid is not None:+ content_parts.append(f"CID: {cid}")++ if result.get("molecular_formula"):+ content_parts.append(+ f"Molecular Formula: {result['molecular_formula']}"+ )+ if result.get("molecular_weight"):+ content_parts.append(+ f"Molecular Weight: {result['molecular_weight']} g/mol"+ )+ if result.get("iupac_name"):+ content_parts.append(f"IUPAC Name: {result['iupac_name']}")+ if result.get("smiles"):+ content_parts.append(f"SMILES: {result['smiles']}")+ if result.get("inchi_key"):+ content_parts.append(f"InChIKey: {result['inchi_key']}")++ # Additional properties+ if properties.get("XLogP") is not None:+ content_parts.append(f"XLogP: {properties['XLogP']}")+ if properties.get("TPSA") is not None:+ content_parts.append(f"TPSA: {properties['TPSA']} Ų")+ if properties.get("HBondDonorCount") is not None:+ content_parts.append(+ f"H-Bond Donors: {properties['HBondDonorCount']}"+ )+ if properties.get("HBondAcceptorCount") is not None:+ content_parts.append(+ f"H-Bond Acceptors: {properties['HBondAcceptorCount']}"+ )++ if result.get("synonyms"):+ content_parts.append(+ f"\nSynonyms: {', '.join(result['synonyms'][:5])}"+ )++ if description:+ content_parts.append(f"\nDescription: {description}")++ result["content"] = "\n".join(content_parts)++ # Clean up internal fields+ if "_raw" in result:+ del result["_raw"]++ results.append(result)++ return results++ def get_compound(self, cid: int) -> Optional[Dict[str, Any]]:+ """+ Get a specific compound by CID.++ Args:+ cid: The PubChem compound ID++ Returns:+ Compound dictionary or None+ """+ try:+ properties = self._get_compound_properties(cid)+ description = self._get_compound_description(cid)+ synonyms = self._get_compound_synonyms(cid)++ return {+ "cid": cid,+ "properties": properties,+ "description": description,+ "synonyms": synonyms,+ }+ except RateLimitError:+ raise+ except Exception:+ logger.exception(f"Error fetching PubChem compound {cid}")+ return None++ def search_by_formula(self, formula: str) -> List[Dict[str, Any]]:+ """+ Search compounds by molecular formula.++ Args:+ formula: Molecular formula (e.g., "C6H12O6")++ Returns:+ List of matching compounds+ """+ try:+ url = f"{self.base_url}/compound/fastformula/{quote(formula, safe='')}/cids/JSON"+ response = safe_get(url, headers=self.headers, timeout=30)++ if response.status_code == 404:+ return []+ self._raise_if_rate_limit(response.status_code)++ response.raise_for_status()+ data = response.json()+ cids = data.get("IdentifierList", {}).get("CID", [])++ results = []+ for cid in cids[: self.max_results]:+ compound = self.get_compound(cid)+ if compound:+ results.append(compound)++ return results++ except RateLimitError:+ raise+ except Exception:+ logger.exception(f"Error searching by formula: {formula}")+ return []diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_stackexchange.py b/src/local_deep_research/web_search_engines/engines/search_engine_stackexchange.pynew file mode 100644index 0000000000..0ffae05242--- /dev/null+++ b/src/local_deep_research/web_search_engines/engines/search_engine_stackexchange.py@@ -0,0 +1,471 @@+"""Stack Exchange search engine for Q&A content."""++import html+import re+import time+from typing import Any, Dict, List, Optional++import requests+from langchain_core.language_models import BaseLLM+from loguru import logger++from ...security.safe_requests import safe_get+from ..rate_limiting import RateLimitError+from ..search_engine_base import BaseSearchEngine+++class StackExchangeSearchEngine(BaseSearchEngine):+ """+ Stack Exchange search engine for Q&A content.++ Provides access to Stack Overflow and other Stack Exchange sites.+ No authentication required (300 requests/day without key).+ """++ is_public = True+ is_generic = False+ is_scientific = False+ is_code = True++ # Common Stack Exchange sites+ SITES = {+ "stackoverflow": "Stack Overflow",+ "serverfault": "Server Fault",+ "superuser": "Super User",+ "askubuntu": "Ask Ubuntu",+ "unix": "Unix & Linux",+ "math": "Mathematics",+ "physics": "Physics",+ "stats": "Cross Validated",+ "security": "Information Security",+ "dba": "Database Administrators",+ }++ # Sites with their own .com domains (not *.stackexchange.com)+ SITE_DOMAINS = {+ "stackoverflow": "stackoverflow.com",+ "serverfault": "serverfault.com",+ "superuser": "superuser.com",+ "askubuntu": "askubuntu.com",+ }++ def __init__(+ self,+ max_results: int = 10,+ site: str = "stackoverflow",+ sort: str = "relevance",+ accepted_only: bool = False,+ has_answers: bool = False,+ min_score: Optional[int] = None,+ tagged: Optional[str] = None,+ llm: Optional[BaseLLM] = None,+ max_filtered_results: Optional[int] = None,+ settings_snapshot: Optional[Dict[str, Any]] = None,+ **kwargs,+ ):+ """+ Initialize the Stack Exchange search engine.++ Args:+ max_results: Maximum number of search results+ site: Stack Exchange site to search (stackoverflow, serverfault, etc.)+ sort: Sort order (relevance, votes, creation, activity)+ accepted_only: Only return questions with accepted answers+ has_answers: Only return questions that have answers+ min_score: Minimum score for questions+ tagged: Filter by tags (semicolon separated)+ llm: Language model for relevance filtering+ max_filtered_results: Maximum results after filtering+ settings_snapshot: Settings snapshot for thread context+ """+ super().__init__(+ llm=llm,+ max_filtered_results=max_filtered_results,+ max_results=max_results,+ settings_snapshot=settings_snapshot,+ **kwargs,+ )++ # Validate site parameter+ if site not in self.SITES:+ valid_sites = ", ".join(self.SITES.keys())+ raise ValueError(+ f"Invalid site: '{site}'. Must be one of: {valid_sites}"+ )++ # Validate sort parameter+ valid_sorts = ("relevance", "votes", "creation", "activity")+ if sort not in valid_sorts:+ raise ValueError(+ f"Invalid sort: '{sort}'. Must be one of: {', '.join(valid_sorts)}"+ )++ # Validate sort/min_score combination: the StackExchange API's "min"+ # parameter works with any sort except "relevance".+ if min_score is not None and sort == "relevance":+ raise ValueError(+ "min_score requires a numeric sort order (votes, creation, or activity). "+ "sort='relevance' does not support the 'min' parameter."+ )++ self.site = site+ self.sort = sort+ self.accepted_only = accepted_only+ self.has_answers = has_answers+ self.min_score = min_score+ self.tagged = tagged++ self.base_url = "https://api.stackexchange.com/2.3"+ self.search_url = f"{self.base_url}/search/advanced"++ # User-Agent and required headers for API requests+ self.headers = {+ "User-Agent": "LocalDeepResearch/1.0 (https://github.com/LearningCircuit/local-deep-research)",+ "Accept-Encoding": "gzip, deflate",+ }++ # Track backoff requirement from API responses+ self._backoff_until: float = 0++ def _apply_backoff(self) -> None:+ """Apply backoff if required by previous API response."""+ if self._backoff_until > 0:+ wait_time = self._backoff_until - time.time()+ if wait_time > 0:+ logger.info(+ f"Stack Exchange backoff: waiting {wait_time:.1f} seconds"+ )+ time.sleep(wait_time)+ self._backoff_until = 0++ def _handle_backoff(self, data: Dict[str, Any]) -> None:+ """Handle backoff field in API response."""+ backoff = data.get("backoff")+ if backoff:+ self._backoff_until = time.time() + min(int(backoff), 300)+ logger.warning(+ f"Stack Exchange API requested backoff of {backoff} seconds"+ )++ def _build_query_params(self, query: str) -> Dict[str, Any]:+ """Build query parameters for the API request."""+ params = {+ "q": query,+ "site": self.site,+ "order": "desc",+ "sort": self.sort,+ "pagesize": min(self.max_results, 100),+ "filter": "withbody", # Include question body+ }++ if self.accepted_only:+ params["accepted"] = "True"++ if self.has_answers:+ params["answers"] = "1"++ if self.min_score is not None:+ params["min"] = self.min_score++ if self.tagged:+ params["tagged"] = self.tagged++ return params++ def _decode_html(self, text: str) -> str:+ """Decode HTML entities in text."""+ return html.unescape(text)++ def _get_site_name(self) -> str:+ """Get human-readable site name."""+ return self.SITES.get(self.site, self.site.title())++ def _get_previews(self, query: str) -> List[Dict[str, Any]]:+ """+ Get preview information for Stack Exchange questions.++ Args:+ query: The search query++ Returns:+ List of preview dictionaries+ """+ logger.info(+ f"Getting Stack Exchange previews for query: {query} on {self.site}"+ )++ # Apply rate limiting+ self._last_wait_time = self.rate_tracker.apply_rate_limit(+ self.engine_type+ )++ # Apply backoff if required by previous API response+ self._apply_backoff()++ try:+ params = self._build_query_params(query)++ response = safe_get(+ self.search_url,+ params=params,+ headers=self.headers,+ timeout=30,+ )++ self._raise_if_rate_limit(response.status_code)++ response.raise_for_status()+ data = response.json()++ # Handle backoff if present in response+ self._handle_backoff(data)++ # Check for API errors+ if "error_id" in data:+ error_msg = data.get("error_message", "Unknown error")+ logger.error(f"Stack Exchange API error: {error_msg}")+ return []++ results = data.get("items", [])+ quota_remaining = data.get("quota_remaining", 0)+ logger.info(+ f"Found {len(results)} Stack Exchange results, quota remaining: {quota_remaining}"+ )++ if quota_remaining < 10:+ logger.warning(f"Stack Exchange quota low: {quota_remaining}")++ previews = []+ for question in results[: self.max_results]:+ try:+ question_id = question.get("question_id")+ title = self._decode_html(question.get("title", "Untitled"))++ # Get owner info+ owner = question.get("owner", {})+ author = self._decode_html(+ owner.get("display_name", "Unknown")+ )+ author_link = owner.get("link", "")+ author_reputation = owner.get("reputation", 0)++ # Get question stats+ score = question.get("score", 0)+ view_count = question.get("view_count", 0)+ answer_count = question.get("answer_count", 0)+ is_answered = question.get("is_answered", False)+ accepted_answer_id = question.get("accepted_answer_id")++ # Get tags+ tags = question.get("tags", [])++ # Build answer status prefix+ status_parts = []+ if is_answered:+ status = f"Answered ({answer_count} answer{'s' if answer_count != 1 else ''}"+ if accepted_answer_id:+ status += ", accepted"+ status += ")"+ status_parts.append(status)+ elif answer_count > 0:+ status_parts.append(+ f"{answer_count} answer{'s' if answer_count != 1 else ''}"+ )+ if tags:+ status_parts.append(f"Tags: {', '.join(tags[:4])}")+ prefix = " | ".join(status_parts)++ # Get body (snippet)+ body = question.get("body", "")+ # Strip HTML for snippet+ body_text = html.unescape(re.sub(r"<[^>]+>", " ", body))[+ :500+ ]+ snippet = f"{prefix} | {body_text}" if prefix else body_text++ # Get dates+ creation_date = question.get("creation_date", 0)+ last_activity = question.get("last_activity_date", 0)++ # Build link+ fallback_domain = self.SITE_DOMAINS.get(+ self.site, f"{self.site}.stackexchange.com"+ )+ link = question.get(+ "link",+ f"https://{fallback_domain}/questions/{question_id}",+ )++ preview = {+ "id": str(question_id),+ "title": title,+ "link": link,+ "snippet": snippet,+ "author": author,+ "author_link": author_link,+ "author_reputation": author_reputation,+ "score": score,+ "view_count": view_count,+ "answer_count": answer_count,+ "is_answered": is_answered,+ "has_accepted_answer": accepted_answer_id is not None,+ "tags": tags,+ "creation_date": creation_date,+ "last_activity_date": last_activity,+ "site": self.site,+ "source": self._get_site_name(),+ "_raw": question,+ }++ previews.append(preview)++ except Exception:+ logger.exception("Error parsing Stack Exchange question")+ continue++ return previews++ except (requests.RequestException, ValueError) as e:+ logger.exception("Stack Exchange API request failed")+ self._raise_if_rate_limit(e)+ return []++ def _get_full_content(+ self, relevant_items: List[Dict[str, Any]]+ ) -> List[Dict[str, Any]]:+ """+ Get full content for the relevant Stack Exchange questions.++ Args:+ relevant_items: List of relevant preview dictionaries++ Returns:+ List of result dictionaries with full content+ """+ logger.info(+ f"Getting full content for {len(relevant_items)} Stack Exchange questions"+ )++ results = []+ for item in relevant_items:+ result = item.copy()++ raw = item.get("_raw", {})+ if raw:+ # Get full body+ body = raw.get("body", "")+ # Clean HTML for content+ clean_body = html.unescape(re.sub(r"<[^>]+>", " ", body))+ clean_body = " ".join(+ clean_body.split()+ ) # Normalize whitespace++ # Build content summary+ content_parts = []+ content_parts.append(+ f"Question: {result.get('title', 'Untitled')}"+ )+ content_parts.append(+ f"Author: {result.get('author', 'Unknown')}"+ )+ content_parts.append(f"Score: {result.get('score', 0)}")+ content_parts.append(+ f"Answers: {result.get('answer_count', 0)}"+ )+ if result.get("has_accepted_answer"):+ content_parts.append("Has accepted answer: Yes")+ if result.get("tags"):+ content_parts.append(f"Tags: {', '.join(result['tags'])}")+ content_parts.append(f"\nContent:\n{clean_body[:2000]}")++ result["content"] = "\n".join(content_parts)++ # Clean up internal fields+ if "_raw" in result:+ del result["_raw"]++ results.append(result)++ return results++ def get_question(self, question_id: int) -> Optional[Dict[str, Any]]:+ """+ Get a specific question by ID.++ Args:+ question_id: The Stack Exchange question ID++ Returns:+ Question dictionary or None+ """+ try:+ url = f"{self.base_url}/questions/{question_id}"+ params = {"site": self.site, "filter": "withbody"}+ response = safe_get(+ url, params=params, headers=self.headers, timeout=30+ )+ self._raise_if_rate_limit(response.status_code)+ response.raise_for_status()+ data = response.json()+ self._handle_backoff(data)+ items = data.get("items", [])+ return items[0] if items else None+ except RateLimitError:+ raise+ except Exception:+ logger.exception(+ f"Error fetching Stack Exchange question {question_id}"+ )+ return None++ def get_answers(self, question_id: int) -> List[Dict[str, Any]]:+ """+ Get answers for a specific question.++ Args:+ question_id: The Stack Exchange question ID++ Returns:+ List of answer dictionaries+ """+ try:+ url = f"{self.base_url}/questions/{question_id}/answers"+ params = {+ "site": self.site,+ "order": "desc",+ "sort": "votes",+ "filter": "withbody",+ }+ response = safe_get(+ url, params=params, headers=self.headers, timeout=30+ )+ self._raise_if_rate_limit(response.status_code)+ response.raise_for_status()+ data = response.json()+ self._handle_backoff(data)+ return data.get("items", [])+ except RateLimitError:+ raise+ except Exception:+ logger.exception(+ f"Error fetching answers for question {question_id}"+ )+ return []++ def search_by_tag(self, tag: str, query: str = "") -> List[Dict[str, Any]]:+ """+ Search questions by tag.++ Args:+ tag: The tag to filter by+ query: Optional search query++ Returns:+ List of matching questions+ """+ original_tagged = self.tagged+ try:+ self.tagged = tag+ return self.run(query)+ finally:+ self.tagged = original_taggeddiff --git a/src/local_deep_research/web_search_engines/engines/search_engine_zenodo.py b/src/local_deep_research/web_search_engines/engines/search_engine_zenodo.pynew file mode 100644index 0000000000..eadabd934e--- /dev/null+++ b/src/local_deep_research/web_search_engines/engines/search_engine_zenodo.py@@ -0,0 +1,395 @@+"""Zenodo search engine for open research data and publications."""++import html+import re+from typing import Any, Dict, List, Optional++import requests+from langchain_core.language_models import BaseLLM+from loguru import logger++from ...security.safe_requests import safe_get+from ..rate_limiting import RateLimitError+from ..search_engine_base import BaseSearchEngine+++class ZenodoSearchEngine(BaseSearchEngine):+ """+ Zenodo search engine for open research data and publications.++ Provides access to millions of research outputs including datasets,+ software, publications, and more. No authentication required for search.+ """++ is_public = True+ is_generic = False+ is_scientific = True+ is_code = False++ def __init__(+ self,+ max_results: int = 10,+ resource_type: Optional[str] = None,+ access_right: Optional[str] = None,+ communities: Optional[str] = None,+ sort: str = "bestmatch",+ llm: Optional[BaseLLM] = None,+ max_filtered_results: Optional[int] = None,+ settings_snapshot: Optional[Dict[str, Any]] = None,+ **kwargs,+ ):+ """+ Initialize the Zenodo search engine.++ Args:+ max_results: Maximum number of search results+ resource_type: Filter by type (dataset, software, publication, etc.)+ access_right: Filter by access (open, closed, embargoed, restricted)+ communities: Filter by Zenodo community+ sort: Sort order (bestmatch, mostrecent, -mostrecent)+ llm: Language model for relevance filtering+ max_filtered_results: Maximum results after filtering+ settings_snapshot: Settings snapshot for thread context+ """+ super().__init__(+ llm=llm,+ max_filtered_results=max_filtered_results,+ max_results=max_results,+ settings_snapshot=settings_snapshot,+ **kwargs,+ )++ self.resource_type = resource_type+ self.access_right = access_right+ self.communities = communities+ self.sort = sort++ self.base_url = "https://zenodo.org"+ self.search_url = f"{self.base_url}/api/records"++ # User-Agent header for API requests+ self.headers = {+ "User-Agent": "LocalDeepResearch/1.0 (https://github.com/LearningCircuit/local-deep-research)"+ }++ def _build_query_params(self, query: str) -> Dict[str, Any]:+ """Build query parameters for the API request."""+ params = {+ "q": query,+ "size": self.max_results,+ "sort": self.sort,+ }++ if self.resource_type:+ params["type"] = self.resource_type++ if self.access_right:+ params["access_right"] = self.access_right++ if self.communities:+ params["communities"] = self.communities++ return params++ def _parse_creators(self, creators: List[Dict]) -> List[str]:+ """Parse creator/author information."""+ result = []+ for creator in creators[:5]:+ name = creator.get("name", "")+ if name:+ result.append(name)+ return result++ def _get_resource_type_label(self, resource_type: Dict) -> str:+ """Get human-readable resource type label."""+ if not resource_type:+ return "Unknown"+ return (+ resource_type.get("title") or resource_type.get("type") or "Unknown"+ )++ def _get_previews(self, query: str) -> List[Dict[str, Any]]:+ """+ Get preview information for Zenodo records.++ Args:+ query: The search query++ Returns:+ List of preview dictionaries+ """+ logger.info(f"Getting Zenodo previews for query: {query}")++ # Apply rate limiting+ self._last_wait_time = self.rate_tracker.apply_rate_limit(+ self.engine_type+ )++ try:+ params = self._build_query_params(query)+ response = safe_get(+ self.search_url,+ params=params,+ headers=self.headers,+ timeout=30,+ )++ self._raise_if_rate_limit(response.status_code)++ response.raise_for_status()+ data = response.json()++ hits = data.get("hits", {})+ results = hits.get("hits", [])+ total = hits.get("total", 0)+ logger.info(+ f"Found {total} Zenodo results, returning {len(results)}"+ )++ previews = []+ for record in results[: self.max_results]:+ try:+ record_id = record.get("id")+ metadata = record.get("metadata", {})++ title = metadata.get("title", "Untitled")++ # Get creators+ creators = self._parse_creators(+ metadata.get("creators", [])+ )++ # Get description/abstract+ description = metadata.get("description", "")+ # Strip HTML tags and decode entities for snippet+ if description:+ description = html.unescape(+ re.sub(r"<[^>]+>", "", description)+ )+ description = description[:500]++ # Get DOI+ doi = metadata.get("doi", "")++ # Get publication date+ pub_date = metadata.get("publication_date", "")++ # Get resource type+ resource_type = metadata.get("resource_type", {})+ type_label = self._get_resource_type_label(resource_type)++ # Get access right+ access = metadata.get("access_right", "open")++ # Get keywords+ keywords = metadata.get("keywords", [])[:10]++ # Get license+ license_info = metadata.get("license", {})+ license_id = (+ license_info.get("id", "") if license_info else ""+ )++ # Get links+ links = record.get("links", {})+ record_url = links.get(+ "self_html", f"{self.base_url}/records/{record_id}"+ )+ doi_url = links.get("doi", "")++ # Build snippet+ snippet_parts = []+ if creators:+ snippet_parts.append(f"By {', '.join(creators[:2])}")+ if type_label:+ type_str = f"Type: {type_label}"+ # Add access status and license inline+ access_license = []+ if access:+ access_license.append(+ access.replace("_", " ").title()+ )+ if license_id:+ access_license.append(license_id.upper())+ if access_license:+ type_str += f" ({', '.join(access_license)})"+ snippet_parts.append(type_str)+ if pub_date:+ snippet_parts.append(f"Published: {pub_date}")+ if description:+ snippet_parts.append(description[:200])+ snippet = ". ".join(snippet_parts)++ preview = {+ "id": str(record_id),+ "title": title,+ "link": record_url,+ "snippet": snippet,+ "authors": creators,+ "doi": doi,+ "doi_url": doi_url,+ "publication_date": pub_date,+ "resource_type": type_label,+ "access_right": access,+ "keywords": keywords,+ "license": license_id,+ "description": description,+ "source": "Zenodo",+ "_raw": record,+ }++ previews.append(preview)++ except Exception:+ logger.exception("Error parsing Zenodo record")+ continue++ return previews++ except (requests.RequestException, ValueError) as e:+ logger.exception("Zenodo API request failed")+ self._raise_if_rate_limit(e)+ return []++ def _get_full_content(+ self, relevant_items: List[Dict[str, Any]]+ ) -> List[Dict[str, Any]]:+ """+ Get full content for the relevant Zenodo records.++ Args:+ relevant_items: List of relevant preview dictionaries++ Returns:+ List of result dictionaries with full content+ """+ logger.info(+ f"Getting full content for {len(relevant_items)} Zenodo records"+ )++ results = []+ for item in relevant_items:+ result = item.copy()++ raw = item.get("_raw", {})+ if raw:+ metadata = raw.get("metadata", {})++ # Get full description (strip HTML tags and decode entities)+ desc = metadata.get("description", "")+ if desc:+ desc = html.unescape(re.sub(r"<[^>]+>", "", desc))+ result["description"] = desc++ # Get all keywords+ result["keywords"] = metadata.get("keywords", [])++ # Get related identifiers+ result["related_identifiers"] = metadata.get(+ "related_identifiers", []+ )++ # Get files info+ files = raw.get("files") or []+ result["files"] = [+ {+ "filename": f.get("key", ""),+ "size": f.get("size", 0),+ "checksum": f.get("checksum", ""),+ }+ for f in files[:10]+ ]++ # Get references+ result["references"] = metadata.get("references", [])++ # Build content summary+ content_parts = []+ if result.get("authors"):+ content_parts.append(+ f"Authors: {', '.join(result['authors'])}"+ )+ if result.get("resource_type"):+ content_parts.append(f"Type: {result['resource_type']}")+ if result.get("publication_date"):+ content_parts.append(+ f"Published: {result['publication_date']}"+ )+ if result.get("doi"):+ content_parts.append(f"DOI: {result['doi']}")+ if result.get("keywords"):+ content_parts.append(+ f"Keywords: {', '.join(str(k) for k in result['keywords'][:5])}"+ )+ if result.get("license"):+ content_parts.append(f"License: {result['license']}")+ if result.get("description"):+ content_parts.append(+ f"\nDescription: {result['description'][:1000]}"+ )++ result["content"] = "\n".join(content_parts)++ # Clean up internal fields+ if "_raw" in result:+ del result["_raw"]++ results.append(result)++ return results++ def get_record(self, record_id: int) -> Optional[Dict[str, Any]]:+ """+ Get a specific record by Zenodo ID.++ Args:+ record_id: The Zenodo record ID++ Returns:+ Record dictionary or None+ """+ try:+ url = f"{self.search_url}/{record_id}"+ response = safe_get(url, headers=self.headers, timeout=30)+ self._raise_if_rate_limit(response.status_code)+ response.raise_for_status()+ return response.json()+ except RateLimitError:+ raise+ except Exception:+ logger.exception(f"Error fetching Zenodo record {record_id}")+ return None++ def search_datasets(self, query: str) -> List[Dict[str, Any]]:+ """+ Search specifically for datasets.++ Args:+ query: The search query++ Returns:+ List of matching datasets+ """+ original_type = self.resource_type+ try:+ self.resource_type = "dataset"+ return self.run(query)+ finally:+ self.resource_type = original_type++ def search_software(self, query: str) -> List[Dict[str, Any]]:+ """+ Search specifically for software.++ Args:+ query: The search query++ Returns:+ List of matching software records+ """+ original_type = self.resource_type+ try:+ self.resource_type = "software"+ return self.run(query)+ finally:+ self.resource_type = original_typediff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.pyindex a8c0a0bfcd..8871fe3678 100644--- a/src/local_deep_research/web_search_engines/search_engine_base.py+++ b/src/local_deep_research/web_search_engines/search_engine_base.py@@ -65,6 +65,10 @@ class BaseSearchEngine(ABC):# Code engines specialize in searching code repositoriesis_code = False+ # Class attribute to indicate if this is a book/literature search engine+ # Book engines search libraries and literary archives+ is_books = False+# Class attribute for rate limit detection patterns# Subclasses can override to add engine-specific patternsrate_limit_patterns: Set[str] = {diff --git a/tests/search_engines/test_new_adapters_integration.py b/tests/search_engines/test_new_adapters_integration.pynew file mode 100644index 0000000000..333718a689--- /dev/null+++ b/tests/search_engines/test_new_adapters_integration.py@@ -0,0 +1,504 @@+"""+Integration tests for new search adapters with real API calls.++These tests verify that the adapters work correctly against live APIs.+They are marked with @pytest.mark.integration and make real network requests.++The TestFactoryIntegration class verifies that engines can be created through+the production factory path (create_search_engine → get_safe_module_class),+which requires correct entries in the security whitelist.+"""++import pytest++from local_deep_research.web_search_engines.search_engine_base import (+ BaseSearchEngine,+)+from local_deep_research.web_search_engines.search_engine_factory import (+ create_search_engine,+)+++class TestOpenLibraryIntegration:+ """Integration tests for Open Library with real API calls."""++ def test_create_engine(self):+ """Test that Open Library engine can be instantiated."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ engine = OpenLibrarySearchEngine(max_results=5)+ assert engine is not None+ assert engine.max_results == 5++ def test_search_and_get_results(self):+ """Test full search flow with real API."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ engine = OpenLibrarySearchEngine(max_results=5)+ results = engine.run("lord of the rings")++ assert len(results) > 0, "Should return search results"++ for r in results:+ assert "title" in r, "Each result should have a title"+ assert "link" in r, "Each result should have a link"+ assert r.get("source") == "Open Library"++ titles = [r["title"].lower() for r in results]+ assert any("lord" in t or "ring" in t for t in titles), (+ f"Should find Lord of the Rings, got: {titles}"+ )++ def test_search_returns_authors(self):+ """Test that search returns author information."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ engine = OpenLibrarySearchEngine(max_results=3)+ results = engine.run("1984 orwell")++ assert len(results) > 0+ has_authors = any(r.get("authors") for r in results)+ assert has_authors, "At least one result should have authors"+++class TestGutenbergIntegration:+ """Integration tests for Gutenberg with real API calls."""++ def test_create_engine(self):+ """Test that Gutenberg engine can be instantiated."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine(max_results=5)+ assert engine is not None+ assert engine.max_results == 5++ def test_search_and_get_results(self):+ """Test full search flow with real API."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine(max_results=5)+ results = engine.run("sherlock holmes")++ assert len(results) > 0, "Should return search results"++ for r in results:+ assert "title" in r, "Each result should have a title"+ assert "link" in r, "Each result should have a link"+ assert r.get("source") == "Project Gutenberg"+ assert "gutenberg.org" in r["link"]++ titles = [r["title"].lower() for r in results]+ assert any("sherlock" in t or "holmes" in t for t in titles), (+ f"Should find Sherlock Holmes, got: {titles}"+ )++ def test_search_returns_authors(self):+ """Test that search returns author information."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine(max_results=3)+ results = engine.run("pride and prejudice")++ assert len(results) > 0+ found_austen = False+ for r in results:+ for author in r.get("authors", []):+ if "austen" in author.lower():+ found_austen = True+ break+ assert found_austen, (+ f"Should find Austen, got: {[r.get('authors') for r in results]}"+ )+++class TestZenodoIntegration:+ """Integration tests for Zenodo with real API calls.++ Note: These tests depend on external Zenodo API availability.+ They handle empty results gracefully since API may be rate-limited in CI.+ """++ def test_create_engine(self):+ """Test that Zenodo engine can be instantiated."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine(max_results=5)+ assert engine is not None+ assert engine.max_results == 5++ def test_search_and_get_results(self):+ """Test full search flow with real API."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine(max_results=5)+ results = engine.run("climate data")++ # API may be rate-limited; verify structure if results returned+ if len(results) > 0:+ for r in results:+ assert "title" in r, "Each result should have a title"+ assert "link" in r, "Each result should have a link"+ assert r.get("source") == "Zenodo"+ assert "zenodo.org" in r["link"]++ def test_search_returns_doi(self):+ """Test that search returns DOI information."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine(max_results=5)+ results = engine.run("neural network dataset")++ # API may be rate-limited; verify DOI if results returned+ if len(results) > 0:+ has_doi = any(r.get("doi") for r in results)+ assert has_doi, "At least one result should have a DOI"+++class TestStackExchangeIntegration:+ """Integration tests for Stack Exchange with real API calls."""++ def test_create_engine(self):+ """Test that Stack Exchange engine can be instantiated."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine(max_results=5)+ assert engine is not None+ assert engine.max_results == 5++ def test_search_and_get_results(self):+ """Test full search flow with real API."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine(max_results=5)+ results = engine.run("python list comprehension")++ assert len(results) > 0, "Should return search results"++ for r in results:+ assert "title" in r, "Each result should have a title"+ assert "link" in r, "Each result should have a link"+ assert r.get("source") == "Stack Overflow"+ assert "stackoverflow.com" in r["link"]++ def test_search_returns_scores(self):+ """Test that search returns score information."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine(max_results=5)+ results = engine.run("javascript async await")++ assert len(results) > 0+ for r in results:+ assert "score" in r, "Each result should have a score"+ assert isinstance(r["score"], int), "Score should be integer"++ def test_search_returns_tags(self):+ """Test that search returns tag information."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine(max_results=5)+ results = engine.run("react hooks useState")++ assert len(results) > 0+ has_tags = any(r.get("tags") for r in results)+ assert has_tags, "At least one result should have tags"+++class TestPubChemIntegration:+ """Integration tests for PubChem with real API calls.++ Note: These tests depend on external PubChem API availability.+ They handle empty results gracefully since API may be rate-limited in CI.+ """++ def test_create_engine(self):+ """Test that PubChem engine can be instantiated."""+ from local_deep_research.web_search_engines.engines.search_engine_pubchem import (+ PubChemSearchEngine,+ )++ engine = PubChemSearchEngine(max_results=5)+ assert engine is not None+ assert engine.max_results == 5++ def test_search_and_get_results(self):+ """Test full search flow with real API."""+ from local_deep_research.web_search_engines.engines.search_engine_pubchem import (+ PubChemSearchEngine,+ )++ engine = PubChemSearchEngine(max_results=3)+ results = engine.run("caffeine")++ # API may be rate-limited; verify structure if results returned+ if len(results) > 0:+ first = results[0]+ assert "title" in first, "Should have title"+ assert "link" in first, "Should have link"+ assert first.get("source") == "PubChem"+ assert "pubchem.ncbi.nlm.nih.gov" in first["link"]++ def test_search_returns_molecular_properties(self):+ """Test that search returns molecular properties."""+ from local_deep_research.web_search_engines.engines.search_engine_pubchem import (+ PubChemSearchEngine,+ )++ engine = PubChemSearchEngine(max_results=1)+ results = engine.run("ibuprofen")++ # API may be rate-limited; verify properties if results returned+ if len(results) > 0:+ first = results[0]+ assert first.get("molecular_formula"), (+ "Should have molecular formula"+ )+ assert first.get("molecular_weight"), "Should have molecular weight"+ assert first.get("cid"), "Should have PubChem CID"++ def test_search_returns_smiles(self):+ """Test that search returns SMILES notation."""+ from local_deep_research.web_search_engines.engines.search_engine_pubchem import (+ PubChemSearchEngine,+ )++ engine = PubChemSearchEngine(max_results=1)+ results = engine.run("glucose")++ # API may be rate-limited; verify SMILES if results returned+ if len(results) > 0:+ first = results[0]+ assert first.get("smiles"), "Should have SMILES notation"+++class TestAllAdaptersRoundTrip:+ """Test all adapters in a single parametrized test.++ Note: These tests depend on external API availability.+ They handle empty results gracefully since APIs may be rate-limited in CI.+ """++ @pytest.mark.parametrize(+ "engine_class_path,engine_class_name,query,expected_source",+ [+ (+ "local_deep_research.web_search_engines.engines.search_engine_openlibrary",+ "OpenLibrarySearchEngine",+ "frankenstein shelley",+ "Open Library",+ ),+ (+ "local_deep_research.web_search_engines.engines.search_engine_gutenberg",+ "GutenbergSearchEngine",+ "moby dick",+ "Project Gutenberg",+ ),+ (+ "local_deep_research.web_search_engines.engines.search_engine_zenodo",+ "ZenodoSearchEngine",+ "astronomy dataset",+ "Zenodo",+ ),+ (+ "local_deep_research.web_search_engines.engines.search_engine_stackexchange",+ "StackExchangeSearchEngine",+ "docker container",+ "Stack Overflow",+ ),+ (+ "local_deep_research.web_search_engines.engines.search_engine_pubchem",+ "PubChemSearchEngine",+ "ethanol",+ "PubChem",+ ),+ ],+ )+ def test_adapter_full_flow(+ self, engine_class_path, engine_class_name, query, expected_source+ ):+ """Test each adapter's full flow."""+ import importlib++ module = importlib.import_module(engine_class_path)+ engine_class = getattr(module, engine_class_name)+ engine = engine_class(max_results=3)++ assert engine is not None, f"Failed to create {engine_class_name}"++ results = engine.run(query)++ # API may be rate-limited; verify structure if results returned+ if len(results) > 0:+ for r in results:+ assert r.get("source") == expected_source, (+ f"Source should be {expected_source}, got {r.get('source')}"+ )+ assert "title" in r, (+ f"{engine_class_name} results should have title"+ )+ assert "link" in r, (+ f"{engine_class_name} results should have link"+ )++ @pytest.mark.parametrize(+ "engine_class_path,engine_class_name,query",+ [+ (+ "local_deep_research.web_search_engines.engines.search_engine_openlibrary",+ "OpenLibrarySearchEngine",+ "frankenstein shelley",+ ),+ (+ "local_deep_research.web_search_engines.engines.search_engine_gutenberg",+ "GutenbergSearchEngine",+ "moby dick",+ ),+ (+ "local_deep_research.web_search_engines.engines.search_engine_zenodo",+ "ZenodoSearchEngine",+ "astronomy dataset",+ ),+ (+ "local_deep_research.web_search_engines.engines.search_engine_stackexchange",+ "StackExchangeSearchEngine",+ "docker container",+ ),+ (+ "local_deep_research.web_search_engines.engines.search_engine_pubchem",+ "PubChemSearchEngine",+ "ethanol",+ ),+ ],+ )+ def test_adapter_full_content(+ self, engine_class_path, engine_class_name, query+ ):+ """Test each adapter's _get_full_content() path (search_snippets_only=False)."""+ import importlib++ module = importlib.import_module(engine_class_path)+ engine_class = getattr(module, engine_class_name)+ engine = engine_class(max_results=2, search_snippets_only=False)++ results = engine.run(query)++ # API may be rate-limited; verify content field if results returned+ if len(results) > 0:+ for r in results:+ assert "content" in r, (+ f"{engine_class_name} full content results should have 'content' field"+ )+ assert "_raw" not in r, (+ f"{engine_class_name} should clean up _raw in full content"+ )+++def _make_snapshot(engine_key: str, module_path: str, class_name: str) -> dict:+ """Build a minimal flat settings snapshot for a single engine.++ Uses ``ui_element: "checkbox"`` for boolean fields so that+ ``get_typed_setting_value`` preserves the boolean type.+ """+ return {+ f"search.engine.web.{engine_key}.module_path": {+ "value": module_path,+ },+ f"search.engine.web.{engine_key}.class_name": {+ "value": class_name,+ },+ f"search.engine.web.{engine_key}.requires_api_key": {+ "value": False,+ "ui_element": "checkbox",+ },+ }+++class TestFactoryIntegration:+ """Verify that create_search_engine() can instantiate each new engine.++ These tests exercise the full production path: settings snapshot →+ search_config() → get_safe_module_class() (security whitelist) →+ engine class instantiation. No mocking of the whitelist or factory.+ """++ @pytest.mark.parametrize(+ "engine_key,module_path,class_name",+ [+ (+ "openlibrary",+ ".engines.search_engine_openlibrary",+ "OpenLibrarySearchEngine",+ ),+ (+ "gutenberg",+ ".engines.search_engine_gutenberg",+ "GutenbergSearchEngine",+ ),+ (+ "zenodo",+ ".engines.search_engine_zenodo",+ "ZenodoSearchEngine",+ ),+ (+ "stackexchange",+ ".engines.search_engine_stackexchange",+ "StackExchangeSearchEngine",+ ),+ (+ "pubchem",+ ".engines.search_engine_pubchem",+ "PubChemSearchEngine",+ ),+ ],+ )+ def test_factory_creates_engine(self, engine_key, module_path, class_name):+ """Engine is created via the factory without SecurityError.++ If this fails with ``engine is None``, the most likely cause is a+ missing entry in ``module_whitelist.py`` (ALLOWED_MODULE_PATHS or+ ALLOWED_CLASS_NAMES).+ """+ snapshot = _make_snapshot(engine_key, module_path, class_name)+ engine = create_search_engine(+ engine_key,+ settings_snapshot=snapshot,+ programmatic_mode=True,+ )+ assert engine is not None, (+ f"create_search_engine returned None for '{engine_key}'. "+ f"Check that {module_path} and {class_name} are in "+ f"security/module_whitelist.py"+ )+ assert isinstance(engine, BaseSearchEngine)diff --git a/tests/search_engines/test_search_engine_gutenberg.py b/tests/search_engines/test_search_engine_gutenberg.pynew file mode 100644index 0000000000..08eafb4ed7--- /dev/null+++ b/tests/search_engines/test_search_engine_gutenberg.py@@ -0,0 +1,590 @@+"""+Tests for the Project Gutenberg search engine via Gutendex API.+Tests initialization, search functionality, and error handling.+"""++import pytest+from unittest.mock import Mock+++class TestGutenbergSearchEngineInit:+ """Tests for Gutenberg search engine initialization."""++ def test_init_default_parameters(self):+ """Test initialization with default parameters."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine()++ assert engine.max_results == 10+ assert engine.languages is None+ assert engine.topic is None+ assert engine.sort == "popular"+ assert engine.is_public is True+ assert engine.is_books is True++ def test_init_custom_parameters(self):+ """Test initialization with custom parameters."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine(+ max_results=20,+ languages="en,fr",+ topic="science fiction",+ sort="ascending",+ )++ assert engine.max_results == 20+ assert engine.languages == "en,fr"+ assert engine.topic == "science fiction"+ assert engine.sort == "ascending"++ def test_base_url_set(self):+ """Test that API base URL is correctly set."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine()+ assert engine.base_url == "https://gutendex.com"+ assert engine.search_url == "https://gutendex.com/books/"++ def test_user_agent_header_set(self):+ """Test that User-Agent header is set."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine()+ assert "User-Agent" in engine.headers+ assert "LocalDeepResearch" in engine.headers["User-Agent"]+++class TestGutenbergQueryBuilding:+ """Tests for Gutenberg query parameter building."""++ def test_build_query_params_basic(self):+ """Test basic query params building."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine()+ params = engine._build_query_params("sherlock holmes")++ assert params["search"] == "sherlock holmes"++ def test_build_query_params_with_languages(self):+ """Test query params with language filter."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine(languages="en")+ params = engine._build_query_params("test")++ assert params["languages"] == "en"++ def test_build_query_params_with_topic(self):+ """Test query params with topic filter."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine(topic="science fiction")+ params = engine._build_query_params("test")++ assert params["topic"] == "science fiction"+++class TestGutenbergAuthorParsing:+ """Tests for Gutenberg author parsing."""++ def test_parse_authors_standard_format(self):+ """Test parsing authors in 'Last, First' format."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine()+ authors = [{"name": "Doyle, Arthur Conan"}]++ result = engine._parse_authors(authors)+ assert result == ["Arthur Conan Doyle"]++ def test_parse_authors_simple_name(self):+ """Test parsing authors with simple name."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine()+ authors = [{"name": "Anonymous"}]++ result = engine._parse_authors(authors)+ assert result == ["Anonymous"]++ def test_parse_authors_limits_to_five(self):+ """Test that author parsing limits to 5."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine()+ authors = [{"name": f"Author{i}"} for i in range(10)]++ result = engine._parse_authors(authors)+ assert len(result) == 5+++class TestGutenbergFormatSelection:+ """Tests for Gutenberg format URL selection."""++ def test_get_best_format_prefers_html(self):+ """Test that HTML is preferred format."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine()+ formats = {+ "text/plain": "http://example.com/book.txt",+ "text/html": "http://example.com/book.html",+ "application/pdf": "http://example.com/book.pdf",+ }++ result = engine._get_best_format_url(formats)+ assert result == "http://example.com/book.html"++ def test_get_best_format_fallback(self):+ """Test fallback when no priority format available."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine()+ formats = {"application/rdf+xml": "http://example.com/book.rdf"}++ result = engine._get_best_format_url(formats)+ assert result == "http://example.com/book.rdf"++ def test_get_best_format_empty(self):+ """Test with empty formats."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine()+ result = engine._get_best_format_url({})+ assert result is None+++class TestGutenbergSearchExecution:+ """Tests for Gutenberg search execution."""++ @pytest.fixture+ def engine(self):+ """Create a Gutenberg engine."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ return GutenbergSearchEngine(max_results=10)++ def test_get_previews_success(self, engine, monkeypatch):+ """Test successful preview retrieval."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "count": 100,+ "results": [+ {+ "id": 1661,+ "title": "The Adventures of Sherlock Holmes",+ "authors": [{"name": "Doyle, Arthur Conan"}],+ "subjects": ["Detective stories", "Mystery"],+ "bookshelves": ["Detective Fiction"],+ "languages": ["en"],+ "download_count": 50000,+ "formats": {+ "text/html": "http://example.com/book.html",+ "image/jpeg": "http://example.com/cover.jpg",+ },+ "copyright": False,+ }+ ],+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_gutenberg.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("sherlock holmes")++ assert len(previews) == 1+ assert previews[0]["title"] == "The Adventures of Sherlock Holmes"+ assert "Arthur Conan Doyle" in previews[0]["authors"]+ assert previews[0]["source"] == "Project Gutenberg"+ assert "gutenberg.org" in previews[0]["link"]++ def test_get_previews_rate_limit_error(self, engine, monkeypatch):+ """Test that 429 errors raise RateLimitError."""+ from local_deep_research.web_search_engines.rate_limiting import (+ RateLimitError,+ )++ mock_response = Mock()+ mock_response.status_code = 429++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_gutenberg.safe_get",+ Mock(return_value=mock_response),+ )++ with pytest.raises(RateLimitError):+ engine._get_previews("test")++ def test_get_previews_handles_exception(self, engine, monkeypatch):+ """Test that exceptions are handled gracefully."""+ import requests++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_gutenberg.safe_get",+ Mock(side_effect=requests.RequestException("Network error")),+ )++ previews = engine._get_previews("test")+ assert previews == []+++class TestGutenbergEdgeCases:+ """Tests for Gutenberg edge cases and error handling."""++ @pytest.fixture+ def engine(self):+ """Create a Gutenberg engine."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ return GutenbergSearchEngine(max_results=10)++ def test_get_previews_empty_results(self, engine, monkeypatch):+ """Test handling of empty search results."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "count": 0,+ "results": [],+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_gutenberg.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("xyznonexistentquery12345")+ assert previews == []++ def test_get_previews_unicode_in_title(self, engine, monkeypatch):+ """Test handling of Unicode characters in book title."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "count": 1,+ "results": [+ {+ "id": 12345,+ "title": "Les Misérables",+ "authors": [{"name": "Hugo, Victor"}],+ "subjects": ["French literature"],+ "languages": ["fr"],+ "download_count": 10000,+ "formats": {},+ }+ ],+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_gutenberg.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("les miserables")+ assert len(previews) == 1+ assert "Misérables" in previews[0]["title"]++ def test_get_previews_missing_optional_fields(self, engine, monkeypatch):+ """Test handling of missing optional fields."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "count": 1,+ "results": [+ {+ "id": 12345,+ "title": "Minimal Book",+ # Missing: authors, subjects, bookshelves, formats+ }+ ],+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_gutenberg.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("test")+ assert len(previews) == 1+ assert previews[0]["title"] == "Minimal Book"+ assert previews[0]["authors"] == []++ def test_get_previews_multiple_authors(self, engine, monkeypatch):+ """Test parsing of multiple authors."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "count": 1,+ "results": [+ {+ "id": 12345,+ "title": "Collaborative Work",+ "authors": [+ {"name": "Smith, John"},+ {"name": "Doe, Jane"},+ {"name": "Brown, Bob"},+ ],+ "formats": {},+ }+ ],+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_gutenberg.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("test")+ assert len(previews) == 1+ assert len(previews[0]["authors"]) == 3+ assert "John Smith" in previews[0]["authors"]++ def test_all_sort_options(self):+ """Test that all sort options can be used."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ sort_options = ["popular", "ascending", "descending"]+ for sort in sort_options:+ engine = GutenbergSearchEngine(sort=sort)+ assert engine.sort == sort++ def test_format_priority_html_over_epub(self):+ """Test that HTML format is preferred over EPUB."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine()+ formats = {+ "application/epub+zip": "http://example.com/book.epub",+ "text/html": "http://example.com/book.html",+ }++ result = engine._get_best_format_url(formats)+ # HTML should be preferred over EPUB for reading+ assert "html" in result++ def test_format_priority_epub_over_pdf(self):+ """Test that EPUB format is preferred over PDF."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine()+ formats = {+ "application/pdf": "http://example.com/book.pdf",+ "application/epub+zip": "http://example.com/book.epub",+ }++ result = engine._get_best_format_url(formats)+ # EPUB should be preferred over PDF+ assert "epub" in result+++class TestGutenbergFullContent:+ """Tests for Gutenberg full content retrieval."""++ def test_get_full_content_builds_content(self):+ """Test that full content builds proper content string."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine()++ items = [+ {+ "title": "Test Book",+ "authors": ["Author One"],+ "subjects": ["Fiction", "Adventure"],+ "bookshelves": ["Adventure"],+ "download_count": 1000,+ "read_url": "http://example.com/read",+ "_raw": {+ "subjects": ["Fiction", "Adventure", "Classic"],+ "bookshelves": ["Adventure", "Best Books"],+ "translators": [],+ },+ }+ ]++ results = engine._get_full_content(items)++ assert len(results) == 1+ assert "Authors: Author One" in results[0]["content"]+ assert "Downloads: 1000" in results[0]["content"]+ assert "_raw" not in results[0]+++class TestGutenbergIntegration:+ """Integration tests making real API calls to Gutendex."""++ def test_real_search_sherlock_holmes(self):+ """Test real search for Sherlock Holmes."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine(max_results=5)+ results = engine._get_previews("sherlock holmes")++ # Verify we got results+ assert len(results) > 0, "Should find Sherlock Holmes books"++ # Verify result structure+ for r in results:+ assert "title" in r, "Each result should have a title"+ assert "link" in r, "Each result should have a link"+ assert r["source"] == "Project Gutenberg"+ assert "gutenberg.org" in r["link"], "Link should be Gutenberg URL"++ # Verify at least one is actually Sherlock Holmes+ titles = [r["title"].lower() for r in results]+ assert any("sherlock" in t or "holmes" in t for t in titles), (+ f"Should find Sherlock Holmes, got: {titles}"+ )++ def test_real_search_finds_doyle(self):+ """Test that Sherlock Holmes search finds Arthur Conan Doyle."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine(max_results=5)+ results = engine._get_previews("sherlock holmes doyle")++ assert len(results) > 0, "Should find results"++ # At least one should have Doyle as author+ found_doyle = False+ for r in results:+ for author in r.get("authors", []):+ if "doyle" in author.lower():+ found_doyle = True+ break+ assert found_doyle, (+ f"Should find Doyle as author, got: {[r.get('authors') for r in results]}"+ )++ def test_real_search_pride_and_prejudice(self):+ """Test real search for Pride and Prejudice."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine(max_results=5)+ results = engine._get_previews("pride and prejudice austen")++ assert len(results) > 0, "Should find Pride and Prejudice"++ # Check for Jane Austen+ found_austen = False+ for r in results:+ for author in r.get("authors", []):+ if "austen" in author.lower():+ found_austen = True+ break+ assert found_austen, (+ f"Should find Austen, got: {[r.get('authors') for r in results]}"+ )++ def test_real_search_returns_download_count(self):+ """Test that real search returns download counts."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine(max_results=3)+ results = engine._get_previews("moby dick")++ assert len(results) > 0, "Should find Moby Dick"++ # Popular books should have download counts+ first = results[0]+ assert "download_count" in first, "Should have download_count"+ assert first["download_count"] > 0, "Popular book should have downloads"++ def test_real_search_with_language_filter(self):+ """Test real search with English language filter."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine(max_results=5, languages="en")+ results = engine._get_previews("adventure")++ assert len(results) > 0, "Should find English adventure books"++ # All results should have English+ for r in results:+ assert "en" in r.get("languages", []), (+ f"Should be English, got languages: {r.get('languages')}"+ )++ def test_real_search_has_read_url(self):+ """Test that results include read URLs."""+ from local_deep_research.web_search_engines.engines.search_engine_gutenberg import (+ GutenbergSearchEngine,+ )++ engine = GutenbergSearchEngine(max_results=3)+ results = engine._get_previews("frankenstein")++ assert len(results) > 0, "Should find Frankenstein"++ # At least one should have a read URL+ has_read_url = any(r.get("read_url") for r in results)+ assert has_read_url, "At least one result should have read_url"diff --git a/tests/search_engines/test_search_engine_openlibrary.py b/tests/search_engines/test_search_engine_openlibrary.pynew file mode 100644index 0000000000..25ba31865f--- /dev/null+++ b/tests/search_engines/test_search_engine_openlibrary.py@@ -0,0 +1,671 @@+"""+Tests for the Open Library search engine.+Tests initialization, search functionality, and error handling.+"""++import pytest+from unittest.mock import Mock+++class TestOpenLibrarySearchEngineInit:+ """Tests for Open Library search engine initialization."""++ def test_init_default_parameters(self):+ """Test initialization with default parameters."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ engine = OpenLibrarySearchEngine()++ assert engine.max_results == 10+ assert engine.sort == "relevance"+ assert engine.language is None+ assert engine.search_field is None+ assert engine.is_public is True+ assert engine.is_books is True+ assert engine.is_generic is False++ def test_init_custom_parameters(self):+ """Test initialization with custom parameters."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ engine = OpenLibrarySearchEngine(+ max_results=50,+ sort="new",+ language="eng",+ search_field="title",+ )++ assert engine.max_results == 50+ assert engine.sort == "new"+ assert engine.language == "eng"+ assert engine.search_field == "title"++ def test_base_url_set(self):+ """Test that API base URL is correctly set."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ engine = OpenLibrarySearchEngine()+ assert engine.base_url == "https://openlibrary.org"+ assert engine.search_url == "https://openlibrary.org/search.json"++ def test_user_agent_header_set(self):+ """Test that User-Agent header is set."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ engine = OpenLibrarySearchEngine()+ assert "User-Agent" in engine.headers+ assert "LocalDeepResearch" in engine.headers["User-Agent"]+++class TestOpenLibraryQueryBuilding:+ """Tests for Open Library query parameter building."""++ def test_build_query_params_basic(self):+ """Test basic query params building."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ engine = OpenLibrarySearchEngine(max_results=20)+ params = engine._build_query_params("lord of the rings")++ assert params["q"] == "lord of the rings"+ assert params["limit"] == 20+ assert "fields" in params++ def test_build_query_params_title_search(self):+ """Test query params with title search field."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ engine = OpenLibrarySearchEngine(search_field="title")+ params = engine._build_query_params("1984")++ assert params["title"] == "1984"+ assert "q" not in params++ def test_build_query_params_author_search(self):+ """Test query params with author search field."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ engine = OpenLibrarySearchEngine(search_field="author")+ params = engine._build_query_params("Tolkien")++ assert params["author"] == "Tolkien"+ assert "q" not in params++ def test_build_query_params_with_language(self):+ """Test query params with language filter."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ engine = OpenLibrarySearchEngine(language="eng")+ params = engine._build_query_params("test")++ assert params["language"] == "eng"++ def test_build_query_params_with_sort(self):+ """Test query params with sort option."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ engine = OpenLibrarySearchEngine(sort="new")+ params = engine._build_query_params("test")++ assert params["sort"] == "new"+++class TestOpenLibraryCoverUrl:+ """Tests for Open Library cover URL generation."""++ def test_get_cover_url_with_id(self):+ """Test cover URL generation with valid ID."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ engine = OpenLibrarySearchEngine()+ url = engine._get_cover_url(12345)++ assert url == "https://covers.openlibrary.org/b/id/12345-M.jpg"++ def test_get_cover_url_with_size(self):+ """Test cover URL generation with custom size."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ engine = OpenLibrarySearchEngine()+ url = engine._get_cover_url(12345, size="L")++ assert url == "https://covers.openlibrary.org/b/id/12345-L.jpg"++ def test_get_cover_url_without_id(self):+ """Test cover URL generation without ID returns None."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ engine = OpenLibrarySearchEngine()+ url = engine._get_cover_url(None)++ assert url is None+++class TestOpenLibrarySearchExecution:+ """Tests for Open Library search execution."""++ @pytest.fixture+ def engine(self):+ """Create an Open Library engine."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ return OpenLibrarySearchEngine(max_results=10)++ def test_get_previews_success(self, engine, monkeypatch):+ """Test successful preview retrieval."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "num_found": 100,+ "docs": [+ {+ "key": "/works/OL27448W",+ "title": "The Lord of the Rings",+ "author_name": ["J.R.R. Tolkien"],+ "author_key": ["OL26320A"],+ "first_publish_year": 1954,+ "publisher": ["HarperCollins"],+ "subject": ["Fantasy", "Middle Earth", "Hobbits"],+ "isbn": ["9780261103252"],+ "cover_i": 8743908,+ "edition_count": 500,+ "has_fulltext": True,+ "ebook_access": "borrowable",+ }+ ],+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_openlibrary.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("lord of the rings")++ assert len(previews) == 1+ assert previews[0]["title"] == "The Lord of the Rings"+ assert "J.R.R. Tolkien" in previews[0]["authors"]+ assert previews[0]["first_publish_year"] == 1954+ assert previews[0]["source"] == "Open Library"+ assert previews[0]["cover_url"] is not None++ def test_get_previews_empty_results(self, engine, monkeypatch):+ """Test preview retrieval with no results."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(return_value={"num_found": 0, "docs": []})+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_openlibrary.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("xyznonexistentbook123")+ assert previews == []++ def test_get_previews_rate_limit_error(self, engine, monkeypatch):+ """Test that 429 errors raise RateLimitError."""+ from local_deep_research.web_search_engines.rate_limiting import (+ RateLimitError,+ )++ mock_response = Mock()+ mock_response.status_code = 429++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_openlibrary.safe_get",+ Mock(return_value=mock_response),+ )++ with pytest.raises(RateLimitError):+ engine._get_previews("test query")++ def test_get_previews_handles_exception(self, engine, monkeypatch):+ """Test that exceptions are handled gracefully."""+ import requests++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_openlibrary.safe_get",+ Mock(side_effect=requests.RequestException("Network error")),+ )++ previews = engine._get_previews("test query")+ assert previews == []++ def test_get_previews_passes_user_agent_header(self, engine, monkeypatch):+ """Test that User-Agent header is passed to API requests."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(return_value={"num_found": 0, "docs": []})+ mock_response.raise_for_status = Mock()++ mock_safe_get = Mock(return_value=mock_response)+ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_openlibrary.safe_get",+ mock_safe_get,+ )++ engine._get_previews("test")++ # Verify headers were passed+ call_kwargs = mock_safe_get.call_args[1]+ assert "headers" in call_kwargs+ assert "User-Agent" in call_kwargs["headers"]+++class TestOpenLibraryFullContent:+ """Tests for Open Library full content retrieval."""++ def test_get_full_content_builds_content(self):+ """Test that full content builds proper content string."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ engine = OpenLibrarySearchEngine()++ items = [+ {+ "title": "Test Book",+ "authors": ["Author One", "Author Two"],+ "first_publish_year": 2020,+ "edition_count": 5,+ "subjects": ["Fiction", "Adventure"],+ "has_fulltext": True,+ "_raw": {+ "language": ["eng", "fre"],+ "subject": ["Fiction", "Adventure", "Fantasy"],+ "publisher": ["Publisher One", "Publisher Two"],+ },+ }+ ]++ results = engine._get_full_content(items)++ assert len(results) == 1+ assert "Authors: Author One, Author Two" in results[0]["content"]+ assert "First published: 2020" in results[0]["content"]+ assert "Editions: 5" in results[0]["content"]+ assert "Full text available" in results[0]["content"]+ assert "_raw" not in results[0]+++class TestOpenLibraryEdgeCases:+ """Tests for Open Library edge cases and error handling."""++ @pytest.fixture+ def engine(self):+ """Create an Open Library engine."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ return OpenLibrarySearchEngine(max_results=10)++ def test_get_previews_unicode_in_title(self, engine, monkeypatch):+ """Test handling of Unicode characters in book title."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "num_found": 1,+ "docs": [+ {+ "key": "/works/OL123W",+ "title": "Les Misérables",+ "author_name": ["Victor Hugo"],+ }+ ],+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_openlibrary.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("les miserables")+ assert len(previews) == 1+ assert "Misérables" in previews[0]["title"]++ def test_get_previews_html_entities_in_title(self, engine, monkeypatch):+ """Test that HTML entities in title are decoded."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "num_found": 1,+ "docs": [+ {+ "key": "/works/OL123W",+ "title": "Harry Potter & the Philosopher's Stone",+ "author_name": ["J.K. Rowling"],+ }+ ],+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_openlibrary.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("harry potter")+ assert len(previews) == 1+ # HTML entities should be decoded+ assert "&" not in previews[0]["title"]+ assert "&" in previews[0]["title"]++ def test_get_previews_missing_optional_fields(self, engine, monkeypatch):+ """Test handling of missing optional fields."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "num_found": 1,+ "docs": [+ {+ "key": "/works/OL123W",+ "title": "Minimal Book",+ # Missing: author_name, first_publish_year, publisher, etc.+ }+ ],+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_openlibrary.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("test")+ assert len(previews) == 1+ assert previews[0]["title"] == "Minimal Book"+ assert previews[0]["authors"] == []+ assert previews[0]["cover_url"] is None++ def test_get_previews_string_author_converted_to_list(+ self, engine, monkeypatch+ ):+ """Test that string author is converted to list."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "num_found": 1,+ "docs": [+ {+ "key": "/works/OL123W",+ "title": "Test Book",+ "author_name": "Single Author", # String instead of list+ }+ ],+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_openlibrary.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("test")+ assert len(previews) == 1+ assert isinstance(previews[0]["authors"], list)+ assert "Single Author" in previews[0]["authors"]++ def test_get_previews_limits_authors_to_five(self, engine, monkeypatch):+ """Test that authors are limited to 5."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "num_found": 1,+ "docs": [+ {+ "key": "/works/OL123W",+ "title": "Multi-Author Book",+ "author_name": [f"Author {i}" for i in range(10)],+ }+ ],+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_openlibrary.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("test")+ assert len(previews) == 1+ assert len(previews[0]["authors"]) == 5++ def test_get_full_content_without_raw(self, engine):+ """Test full content handling when _raw is missing."""+ items = [+ {+ "title": "Test Book",+ "authors": ["Test Author"],+ }+ ]++ results = engine._get_full_content(items)+ assert len(results) == 1+ # Should not crash++ def test_all_sort_options(self):+ """Test that various sort options can be used."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ sort_options = ["relevance", "new", "old", "random"]+ for sort in sort_options:+ engine = OpenLibrarySearchEngine(sort=sort)+ assert engine.sort == sort++ def test_all_search_fields(self):+ """Test that all search field options work."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ fields = [None, "title", "author", "subject"]+ for field in fields:+ engine = OpenLibrarySearchEngine(search_field=field)+ assert engine.search_field == field+++class TestOpenLibraryHelperMethods:+ """Tests for Open Library helper methods."""++ def test_get_book_by_isbn_success(self, monkeypatch):+ """Test successful book retrieval by ISBN."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ engine = OpenLibrarySearchEngine()++ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "title": "Test Book",+ "authors": [{"key": "/authors/OL123A"}],+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_openlibrary.safe_get",+ Mock(return_value=mock_response),+ )++ book = engine.get_book_by_isbn("9780261103252")++ assert book is not None+ assert book["title"] == "Test Book"++ def test_get_book_by_isbn_handles_error(self, monkeypatch):+ """Test that errors are handled in ISBN lookup."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )+ import requests++ engine = OpenLibrarySearchEngine()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_openlibrary.safe_get",+ Mock(side_effect=requests.RequestException("Not found")),+ )++ book = engine.get_book_by_isbn("invalid")+ assert book is None+++class TestOpenLibraryIntegration:+ """Integration tests making real API calls to Open Library."""++ def test_real_search_harry_potter(self):+ """Test real search for Harry Potter books."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ engine = OpenLibrarySearchEngine(max_results=5)+ results = engine._get_previews("harry potter")++ # Verify we got results+ assert len(results) > 0, "Should find Harry Potter books"++ # Verify result structure+ for r in results:+ assert "title" in r, "Each result should have a title"+ assert "link" in r, "Each result should have a link"+ assert r["source"] == "Open Library", (+ "Source should be Open Library"+ )+ assert r["link"].startswith("https://openlibrary.org"), (+ "Link should be valid"+ )++ # Verify at least one result mentions Harry Potter+ titles = [r["title"].lower() for r in results]+ assert any("harry potter" in t or "potter" in t for t in titles), (+ f"At least one result should contain 'Harry Potter', got: {titles}"+ )++ def test_real_author_search_stephen_king(self):+ """Test real author search for Stephen King."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ engine = OpenLibrarySearchEngine(max_results=5, search_field="author")+ results = engine._get_previews("Stephen King")++ # Verify we got results+ assert len(results) > 0, "Should find Stephen King books"++ # Verify at least one result has Stephen King as author+ found_king = False+ for r in results:+ authors = r.get("authors", [])+ for author in authors:+ if "king" in author.lower():+ found_king = True+ break+ assert found_king, (+ f"At least one result should have King as author, got: {[r.get('authors') for r in results]}"+ )++ def test_real_title_search_1984(self):+ """Test real title search for 1984."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ engine = OpenLibrarySearchEngine(max_results=5, search_field="title")+ results = engine._get_previews("1984")++ # Verify we got results+ assert len(results) > 0, "Should find books with 1984 in title"++ # Verify result has expected fields+ first = results[0]+ assert "title" in first+ assert "authors" in first+ assert "link" in first++ def test_real_search_returns_metadata(self):+ """Test that real search returns proper metadata."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ engine = OpenLibrarySearchEngine(max_results=3)+ results = engine._get_previews("lord of the rings tolkien")++ assert len(results) > 0, "Should find Lord of the Rings"++ # Check first result has expected metadata+ first = results[0]+ assert first.get("title"), "Should have title"+ assert first.get("authors"), "Should have authors"+ assert first.get("link"), "Should have link"+ assert first.get("id"), "Should have id"++ # Verify it's actually Tolkien+ authors = first.get("authors", [])+ assert any("tolkien" in a.lower() for a in authors), (+ f"Should find Tolkien as author, got: {authors}"+ )++ def test_real_search_with_language_filter(self):+ """Test real search with language filter."""+ from local_deep_research.web_search_engines.engines.search_engine_openlibrary import (+ OpenLibrarySearchEngine,+ )++ engine = OpenLibrarySearchEngine(max_results=5, language="eng")+ results = engine._get_previews("science fiction")++ assert len(results) > 0, "Should find science fiction books in English"+ assert all(r["source"] == "Open Library" for r in results)diff --git a/tests/search_engines/test_search_engine_pubchem.py b/tests/search_engines/test_search_engine_pubchem.pynew file mode 100644index 0000000000..afaa4b0f1b--- /dev/null+++ b/tests/search_engines/test_search_engine_pubchem.py@@ -0,0 +1,456 @@+"""+Tests for the PubChem search engine.+Tests initialization, search functionality, and error handling.+"""++import pytest+from unittest.mock import Mock+++class TestPubChemSearchEngineInit:+ """Tests for PubChem search engine initialization."""++ def test_init_default_parameters(self):+ """Test initialization with default parameters."""+ from local_deep_research.web_search_engines.engines.search_engine_pubchem import (+ PubChemSearchEngine,+ )++ engine = PubChemSearchEngine()++ assert engine.max_results == 10+ assert engine.include_synonyms is True+ assert engine.is_public is True+ assert engine.is_scientific is True++ def test_init_custom_parameters(self):+ """Test initialization with custom parameters."""+ from local_deep_research.web_search_engines.engines.search_engine_pubchem import (+ PubChemSearchEngine,+ )++ engine = PubChemSearchEngine(+ max_results=20,+ include_synonyms=False,+ )++ assert engine.max_results == 20+ assert engine.include_synonyms is False++ def test_base_url_set(self):+ """Test that API base URL is correctly set."""+ from local_deep_research.web_search_engines.engines.search_engine_pubchem import (+ PubChemSearchEngine,+ )++ engine = PubChemSearchEngine()+ assert engine.base_url == "https://pubchem.ncbi.nlm.nih.gov/rest/pug"+ assert (+ engine.autocomplete_url+ == "https://pubchem.ncbi.nlm.nih.gov/rest/autocomplete"+ )++ def test_user_agent_header_set(self):+ """Test that User-Agent header is set."""+ from local_deep_research.web_search_engines.engines.search_engine_pubchem import (+ PubChemSearchEngine,+ )++ engine = PubChemSearchEngine()+ assert "User-Agent" in engine.headers+ assert "LocalDeepResearch" in engine.headers["User-Agent"]+++class TestPubChemSearchExecution:+ """Tests for PubChem search execution."""++ @pytest.fixture+ def engine(self):+ """Create a PubChem engine."""+ from local_deep_research.web_search_engines.engines.search_engine_pubchem import (+ PubChemSearchEngine,+ )++ return PubChemSearchEngine(max_results=5)++ def test_get_previews_handles_exception(self, engine, monkeypatch):+ """Test that exceptions are handled gracefully."""+ import requests++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_pubchem.safe_get",+ Mock(side_effect=requests.RequestException("Network error")),+ )++ previews = engine._get_previews("aspirin")+ assert previews == []+++class TestPubChemErrorHandling:+ """Tests for PubChem error handling scenarios."""++ @pytest.fixture+ def engine(self):+ """Create a PubChem engine."""+ from local_deep_research.web_search_engines.engines.search_engine_pubchem import (+ PubChemSearchEngine,+ )++ return PubChemSearchEngine(max_results=5)++ def test_get_previews_handles_autocomplete_failure(+ self, engine, monkeypatch+ ):+ """Test that autocomplete returns results but direct lookup fails."""+ # Autocomplete returns a compound name, but the CID lookup fails+ mock_autocomplete = Mock()+ mock_autocomplete.status_code = 200+ mock_autocomplete.json = Mock(+ return_value={"dictionary_terms": {"compound": ["test compound"]}}+ )+ mock_autocomplete.raise_for_status = Mock()++ # CID lookup returns 404 (compound not found)+ mock_not_found = Mock()+ mock_not_found.status_code = 404++ def mock_safe_get(*args, **kwargs):+ if "autocomplete" in args[0]:+ return mock_autocomplete+ return mock_not_found++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_pubchem.safe_get",+ mock_safe_get,+ )++ # Should return empty list since compound lookup fails+ previews = engine._get_previews("test compound")+ assert previews == []++ def test_get_previews_handles_not_found_compound(self, engine, monkeypatch):+ """Test handling of 404 status code when compound is not found."""++ # First call for autocomplete returns empty (to trigger direct lookup path)+ mock_autocomplete = Mock()+ mock_autocomplete.status_code = 200+ mock_autocomplete.json = Mock(+ return_value={"dictionary_terms": {"compound": []}}+ )+ mock_autocomplete.raise_for_status = Mock()++ # Second call for direct lookup returns 404 (compound not found)+ mock_not_found = Mock()+ mock_not_found.status_code = 404++ call_count = [0]++ def mock_safe_get(*args, **kwargs):+ call_count[0] += 1+ if call_count[0] == 1:+ return mock_autocomplete+ else:+ return mock_not_found++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_pubchem.safe_get",+ mock_safe_get,+ )++ # Should return empty list since no compound found+ previews = engine._get_previews("nonexistent")+ assert previews == []++ def test_get_previews_raises_rate_limit_on_429(self, engine, monkeypatch):+ """Test that 429 status code raises RateLimitError."""+ from local_deep_research.web_search_engines.rate_limiting import (+ RateLimitError,+ )++ mock_response = Mock()+ mock_response.status_code = 429++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_pubchem.safe_get",+ Mock(return_value=mock_response),+ )++ with pytest.raises(RateLimitError):+ engine._get_previews("aspirin")++ def test_get_previews_empty_autocomplete_results(self, engine, monkeypatch):+ """Test handling when autocomplete returns no results."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={"dictionary_terms": {"compound": []}}+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_pubchem.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("xyznonexistent12345")+ assert previews == []++ def test_get_previews_http_500_error(self, engine, monkeypatch):+ """Test handling of HTTP 500 server error."""+ import requests++ mock_response = Mock()+ mock_response.status_code = 500+ mock_response.raise_for_status = Mock(+ side_effect=requests.HTTPError("500 Server Error")+ )++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_pubchem.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("test")+ assert previews == []++ def test_get_previews_malformed_json(self, engine, monkeypatch):+ """Test handling of malformed JSON response."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(side_effect=ValueError("Invalid JSON"))++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_pubchem.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("test")+ assert previews == []++ def test_compound_with_missing_properties(self, engine, monkeypatch):+ """Test handling of compound with missing properties."""+ # Mock for autocomplete+ mock_autocomplete = Mock()+ mock_autocomplete.status_code = 200+ mock_autocomplete.json = Mock(+ return_value={"dictionary_terms": {"compound": ["test compound"]}}+ )+ mock_autocomplete.raise_for_status = Mock()++ # Mock for compound CID lookup+ mock_compound = Mock()+ mock_compound.status_code = 200+ mock_compound.json = Mock(+ return_value={"IdentifierList": {"CID": [12345]}}+ )+ mock_compound.raise_for_status = Mock()++ # Mock for properties - empty+ mock_properties = Mock()+ mock_properties.status_code = 200+ mock_properties.json = Mock(+ return_value={"PropertyTable": {"Properties": [{}]}}+ )+ mock_properties.raise_for_status = Mock()++ # Mock for description - empty+ mock_description = Mock()+ mock_description.status_code = 200+ mock_description.json = Mock(+ return_value={"InformationList": {"Information": []}}+ )+ mock_description.raise_for_status = Mock()++ def mock_safe_get(*args, **kwargs):+ url = args[0]+ if "autocomplete" in url:+ return mock_autocomplete+ elif "property" in url:+ return mock_properties+ elif "description" in url:+ return mock_description+ else:+ return mock_compound++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_pubchem.safe_get",+ mock_safe_get,+ )++ previews = engine._get_previews("test compound")+ # Should not crash, should return result with empty fields+ assert isinstance(previews, list)+ assert len(previews) == 1+ assert previews[0]["cid"] == 12345+++class TestPubChemFullContent:+ """Tests for PubChem full content retrieval."""++ def test_get_full_content_builds_content(self):+ """Test that full content builds proper content string."""+ from local_deep_research.web_search_engines.engines.search_engine_pubchem import (+ PubChemSearchEngine,+ )++ engine = PubChemSearchEngine(include_synonyms=False)++ items = [+ {+ "id": "2244",+ "cid": 2244,+ "title": "Aspirin",+ "molecular_formula": "C9H8O4",+ "molecular_weight": "180.16",+ "iupac_name": "2-acetyloxybenzoic acid",+ "smiles": "CC(=O)OC1=CC=CC=C1C(=O)O",+ "inchi_key": "BSYNRYMUTXBXSQ-UHFFFAOYSA-N",+ "description": "Aspirin is an anti-inflammatory drug.",+ "_raw": {+ "properties": {+ "XLogP": 1.2,+ "TPSA": 63.6,+ "HBondDonorCount": 1,+ "HBondAcceptorCount": 4,+ },+ "description": "Aspirin is an anti-inflammatory drug.",+ },+ }+ ]++ results = engine._get_full_content(items)++ assert len(results) == 1+ assert "Compound: Aspirin" in results[0]["content"]+ assert "CID: 2244" in results[0]["content"]+ assert "Molecular Formula: C9H8O4" in results[0]["content"]+ assert "Molecular Weight: 180.16 g/mol" in results[0]["content"]+ assert "_raw" not in results[0]+++class TestPubChemIntegration:+ """Integration tests making real API calls to PubChem."""++ def test_real_search_aspirin(self):+ """Test real search for aspirin."""+ from local_deep_research.web_search_engines.engines.search_engine_pubchem import (+ PubChemSearchEngine,+ )++ engine = PubChemSearchEngine(max_results=3)+ results = engine._get_previews("aspirin")++ # Verify we got results+ assert len(results) > 0, "Should find aspirin"++ # Verify first result+ first = results[0]+ assert "title" in first, "Should have title"+ assert "link" in first, "Should have link"+ assert first["source"] == "PubChem", "Source should be PubChem"+ assert "pubchem.ncbi.nlm.nih.gov" in first["link"], (+ "Link should be PubChem URL"+ )++ def test_real_search_returns_molecular_formula(self):+ """Test that real search returns molecular formula."""+ from local_deep_research.web_search_engines.engines.search_engine_pubchem import (+ PubChemSearchEngine,+ )++ engine = PubChemSearchEngine(max_results=1)+ results = engine._get_previews("caffeine")++ assert len(results) > 0, "Should find caffeine"++ first = results[0]+ assert first.get("molecular_formula"), "Should have molecular_formula"+ # Caffeine is C8H10N4O2+ assert "C" in first["molecular_formula"], "Formula should contain C"++ def test_real_search_returns_molecular_weight(self):+ """Test that real search returns molecular weight."""+ from local_deep_research.web_search_engines.engines.search_engine_pubchem import (+ PubChemSearchEngine,+ )++ engine = PubChemSearchEngine(max_results=1)+ results = engine._get_previews("glucose")++ assert len(results) > 0, "Should find glucose"++ first = results[0]+ assert first.get("molecular_weight"), "Should have molecular_weight"+ # Just verify molecular weight is a positive number+ # (PubChem may return different glucose compounds like derivatives)+ weight = float(first["molecular_weight"])+ assert weight > 0, f"Molecular weight should be positive, got {weight}"++ def test_real_search_returns_smiles(self):+ """Test that real search returns SMILES notation."""+ from local_deep_research.web_search_engines.engines.search_engine_pubchem import (+ PubChemSearchEngine,+ )++ engine = PubChemSearchEngine(max_results=1)+ results = engine._get_previews("ethanol")++ assert len(results) > 0, "Should find ethanol"++ first = results[0]+ assert first.get("smiles"), "Should have SMILES"+ # Ethanol SMILES should contain C and O+ assert "C" in first["smiles"] and "O" in first["smiles"], (+ f"Ethanol SMILES should contain C and O, got: {first['smiles']}"+ )++ def test_real_search_returns_cid(self):+ """Test that real search returns compound ID."""+ from local_deep_research.web_search_engines.engines.search_engine_pubchem import (+ PubChemSearchEngine,+ )++ engine = PubChemSearchEngine(max_results=1)+ results = engine._get_previews("water")++ assert len(results) > 0, "Should find water"++ first = results[0]+ assert first.get("cid"), "Should have CID"+ assert isinstance(first["cid"], int), "CID should be integer"++ def test_real_search_ibuprofen(self):+ """Test real search for ibuprofen."""+ from local_deep_research.web_search_engines.engines.search_engine_pubchem import (+ PubChemSearchEngine,+ )++ engine = PubChemSearchEngine(max_results=1)+ results = engine._get_previews("ibuprofen")++ assert len(results) > 0, "Should find ibuprofen"++ first = results[0]+ # Ibuprofen CID is 3672+ assert first.get("cid"), "Should have CID"+ assert first.get("iupac_name"), "Should have IUPAC name"++ def test_real_search_partial_name(self):+ """Test real search with partial compound name."""+ from local_deep_research.web_search_engines.engines.search_engine_pubchem import (+ PubChemSearchEngine,+ )++ engine = PubChemSearchEngine(max_results=5)+ results = engine._get_previews("acet")++ # Should find compounds starting with "acet" like acetone, acetamide, etc.+ assert len(results) > 0, "Should find compounds starting with 'acet'"++ # At least one should have a title starting with "acet"+ titles = [r["title"].lower() for r in results]+ has_acet = any("acet" in t for t in titles)+ assert has_acet, (+ f"Should find compound starting with 'acet', got: {titles}"+ )diff --git a/tests/search_engines/test_search_engine_stackexchange.py b/tests/search_engines/test_search_engine_stackexchange.pynew file mode 100644index 0000000000..d446a73d8c--- /dev/null+++ b/tests/search_engines/test_search_engine_stackexchange.py@@ -0,0 +1,772 @@+"""+Tests for the Stack Exchange search engine.+Tests initialization, search functionality, and error handling.+"""++import pytest+from unittest.mock import Mock+++class TestStackExchangeSearchEngineInit:+ """Tests for Stack Exchange search engine initialization."""++ def test_init_default_parameters(self):+ """Test initialization with default parameters."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine()++ assert engine.max_results == 10+ assert engine.site == "stackoverflow"+ assert engine.sort == "relevance"+ assert engine.accepted_only is False+ assert engine.has_answers is False+ assert engine.min_score is None+ assert engine.tagged is None+ assert engine.is_public is True+ assert engine.is_code is True++ def test_init_custom_parameters(self):+ """Test initialization with custom parameters."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine(+ max_results=50,+ site="serverfault",+ sort="votes",+ accepted_only=True,+ has_answers=True,+ min_score=5,+ tagged="python;django",+ )++ assert engine.max_results == 50+ assert engine.site == "serverfault"+ assert engine.sort == "votes"+ assert engine.accepted_only is True+ assert engine.has_answers is True+ assert engine.min_score == 5+ assert engine.tagged == "python;django"++ def test_init_rejects_min_score_with_relevance_sort(self):+ """Test that min_score + sort='relevance' raises ValueError."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ with pytest.raises(+ ValueError, match="min_score requires a numeric sort"+ ):+ StackExchangeSearchEngine(min_score=10, sort="relevance")++ def test_init_allows_min_score_with_non_relevance_sort(self):+ """Test that min_score works with votes, creation, and activity sorts."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ for sort in ("votes", "creation", "activity"):+ engine = StackExchangeSearchEngine(min_score=5, sort=sort)+ assert engine.min_score == 5+ assert engine.sort == sort++ def test_base_url_set(self):+ """Test that API base URL is correctly set."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine()+ assert engine.base_url == "https://api.stackexchange.com/2.3"+ assert (+ engine.search_url+ == "https://api.stackexchange.com/2.3/search/advanced"+ )+++class TestStackExchangeQueryBuilding:+ """Tests for Stack Exchange query parameter building."""++ def test_build_query_params_basic(self):+ """Test basic query params building."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine(max_results=20)+ params = engine._build_query_params("python list comprehension")++ assert params["q"] == "python list comprehension"+ assert params["site"] == "stackoverflow"+ assert params["pagesize"] == 20+ assert params["sort"] == "relevance"++ def test_build_query_params_with_site(self):+ """Test query params with different site."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine(site="unix")+ params = engine._build_query_params("bash script")++ assert params["site"] == "unix"++ def test_build_query_params_with_accepted_only(self):+ """Test query params with accepted only filter."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine(accepted_only=True)+ params = engine._build_query_params("test")++ assert params["accepted"] == "True"++ def test_build_query_params_with_min_score(self):+ """Test query params with minimum score filter."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine(min_score=10, sort="votes")+ params = engine._build_query_params("test")++ assert params["min"] == 10+ assert params["sort"] == "votes"++ def test_build_query_params_with_tags(self):+ """Test query params with tag filter."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine(tagged="python;django")+ params = engine._build_query_params("test")++ assert params["tagged"] == "python;django"+++class TestStackExchangeHtmlDecoding:+ """Tests for Stack Exchange HTML decoding."""++ def test_decode_html_entities(self):+ """Test HTML entity decoding."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine()+ result = engine._decode_html("What does "yield" do?")+ assert result == 'What does "yield" do?'++ def test_decode_html_ampersand(self):+ """Test ampersand decoding."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine()+ result = engine._decode_html("A & B")+ assert result == "A & B"+++class TestStackExchangeSiteName:+ """Tests for Stack Exchange site name resolution."""++ def test_get_site_name_stackoverflow(self):+ """Test site name for Stack Overflow."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine(site="stackoverflow")+ assert engine._get_site_name() == "Stack Overflow"++ def test_get_site_name_unix(self):+ """Test site name for Unix & Linux."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine(site="unix")+ assert engine._get_site_name() == "Unix & Linux"++ def test_invalid_site_raises_error(self):+ """Test that invalid site raises ValueError."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ with pytest.raises(ValueError) as excinfo:+ StackExchangeSearchEngine(site="customsite")+ assert "Invalid site" in str(excinfo.value)+ assert "customsite" in str(excinfo.value)++ def test_invalid_sort_raises_error(self):+ """Test that invalid sort raises ValueError."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ with pytest.raises(ValueError) as excinfo:+ StackExchangeSearchEngine(sort="invalid_sort")+ assert "Invalid sort" in str(excinfo.value)+++class TestStackExchangeBackoffHandling:+ """Tests for Stack Exchange API backoff handling."""++ def test_backoff_until_initialized_to_zero(self):+ """Test that backoff is initialized to zero."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine()+ assert engine._backoff_until == 0++ def test_handle_backoff_sets_future_time(self):+ """Test that handle_backoff sets a future time when backoff is present."""+ import time++ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine()+ before_time = time.time()++ engine._handle_backoff({"backoff": 10})++ assert engine._backoff_until > before_time+ assert engine._backoff_until <= before_time + 11 # Allow some tolerance++ def test_handle_backoff_ignores_missing_field(self):+ """Test that handle_backoff does nothing when backoff field is missing."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine()+ engine._backoff_until = 0++ engine._handle_backoff({"items": [], "quota_remaining": 100})++ assert engine._backoff_until == 0++ def test_apply_backoff_resets_after_waiting(self, monkeypatch):+ """Test that apply_backoff resets backoff_until after waiting."""+ import time++ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine()+ # Set backoff to a past time so we don't actually wait+ engine._backoff_until = time.time() - 1++ engine._apply_backoff()++ assert engine._backoff_until == 0++ def test_get_previews_handles_backoff_in_response(self, monkeypatch):+ """Test that backoff in response is properly handled."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine(max_results=5)++ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "items": [+ {+ "question_id": 12345,+ "title": "Test Question",+ "body": "<p>Test</p>",+ "link": "https://stackoverflow.com/questions/12345",+ "owner": {"display_name": "Test User"},+ "score": 10,+ "tags": ["python"],+ }+ ],+ "quota_remaining": 299,+ "backoff": 5, # API requests backoff of 5 seconds+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_stackexchange.safe_get",+ Mock(return_value=mock_response),+ )++ # Should still return results even with backoff+ previews = engine._get_previews("test")+ assert len(previews) == 1++ # Backoff should be set for next request+ assert engine._backoff_until > 0+++class TestStackExchangeSearchExecution:+ """Tests for Stack Exchange search execution."""++ @pytest.fixture+ def engine(self):+ """Create a Stack Exchange engine."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ return StackExchangeSearchEngine(max_results=10)++ def test_get_previews_success(self, engine, monkeypatch):+ """Test successful preview retrieval."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "items": [+ {+ "question_id": 231767,+ "title": "What does the "yield" keyword do?",+ "body": "<p>Test question body</p>",+ "link": "https://stackoverflow.com/questions/231767",+ "owner": {+ "display_name": "John Doe",+ "link": "https://stackoverflow.com/users/123",+ "reputation": 5000,+ },+ "score": 100,+ "view_count": 50000,+ "answer_count": 10,+ "is_answered": True,+ "accepted_answer_id": 231855,+ "tags": ["python", "yield", "generator"],+ "creation_date": 1224800471,+ "last_activity_date": 1711253482,+ }+ ],+ "has_more": True,+ "quota_max": 300,+ "quota_remaining": 299,+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_stackexchange.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("python yield")++ assert len(previews) == 1+ assert previews[0]["title"] == 'What does the "yield" keyword do?'+ assert previews[0]["author"] == "John Doe"+ assert previews[0]["score"] == 100+ assert previews[0]["answer_count"] == 10+ assert previews[0]["has_accepted_answer"] is True+ assert "python" in previews[0]["tags"]+ assert previews[0]["source"] == "Stack Overflow"++ def test_get_previews_rate_limit_error(self, engine, monkeypatch):+ """Test that 429 errors raise RateLimitError."""+ from local_deep_research.web_search_engines.rate_limiting import (+ RateLimitError,+ )++ mock_response = Mock()+ mock_response.status_code = 429++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_stackexchange.safe_get",+ Mock(return_value=mock_response),+ )++ with pytest.raises(RateLimitError):+ engine._get_previews("test")++ def test_get_previews_handles_exception(self, engine, monkeypatch):+ """Test that exceptions are handled gracefully."""+ import requests++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_stackexchange.safe_get",+ Mock(side_effect=requests.RequestException("Network error")),+ )++ previews = engine._get_previews("test")+ assert previews == []++ def test_get_previews_handles_api_error(self, engine, monkeypatch):+ """Test that API errors are handled gracefully."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "error_id": 502,+ "error_message": "Throttle violation",+ "error_name": "throttle_violation",+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_stackexchange.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("test")+ assert previews == []+++class TestStackExchangeFullContent:+ """Tests for Stack Exchange full content retrieval."""++ def test_get_full_content_builds_content(self):+ """Test that full content builds proper content string."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine()++ items = [+ {+ "title": "How to use Python generators?",+ "author": "Author One",+ "score": 50,+ "answer_count": 5,+ "has_accepted_answer": True,+ "tags": ["python", "generators"],+ "_raw": {+ "body": "<p>This is the question body with <code>code</code>.</p>",+ },+ }+ ]++ results = engine._get_full_content(items)++ assert len(results) == 1+ assert (+ "Question: How to use Python generators?" in results[0]["content"]+ )+ assert "Author: Author One" in results[0]["content"]+ assert "Score: 50" in results[0]["content"]+ assert "Has accepted answer: Yes" in results[0]["content"]+ assert "_raw" not in results[0]+++class TestStackExchangeEdgeCases:+ """Tests for Stack Exchange edge cases and error handling."""++ @pytest.fixture+ def engine(self):+ """Create a Stack Exchange engine."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ return StackExchangeSearchEngine(max_results=10)++ def test_all_valid_sites_can_be_instantiated(self):+ """Test that all sites in SITES dict can be used."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ valid_sites = [+ "stackoverflow",+ "serverfault",+ "superuser",+ "askubuntu",+ "unix",+ "math",+ "physics",+ "stats",+ "security",+ "dba",+ ]++ for site in valid_sites:+ engine = StackExchangeSearchEngine(site=site)+ assert engine.site == site++ def test_all_valid_sorts_can_be_used(self):+ """Test that all valid sort orders can be used."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ valid_sorts = ["relevance", "votes", "creation", "activity"]++ for sort in valid_sorts:+ engine = StackExchangeSearchEngine(sort=sort)+ assert engine.sort == sort++ def test_get_previews_empty_results(self, engine, monkeypatch):+ """Test handling of empty search results."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "items": [],+ "has_more": False,+ "quota_remaining": 299,+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_stackexchange.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("xyznonexistentquery123")+ assert previews == []++ def test_get_previews_low_quota_returns_empty(self, engine, monkeypatch):+ """Test that low quota still returns results (warning is logged via loguru)."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "items": [],+ "has_more": False,+ "quota_remaining": 5, # Low quota+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_stackexchange.safe_get",+ Mock(return_value=mock_response),+ )++ # Should still work even with low quota+ previews = engine._get_previews("test")+ assert previews == [] # Empty because no items in response++ def test_get_previews_unicode_query(self, engine, monkeypatch):+ """Test handling of Unicode characters in query."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "items": [+ {+ "question_id": 12345,+ "title": "How to print 日本語 in Python?",+ "body": "<p>Unicode test</p>",+ "link": "https://stackoverflow.com/questions/12345",+ "owner": {"display_name": "用户"},+ "score": 10,+ "tags": ["python", "unicode"],+ }+ ],+ "quota_remaining": 299,+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_stackexchange.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("日本語 Python")+ assert len(previews) == 1+ assert "日本語" in previews[0]["title"]++ def test_get_previews_missing_optional_fields(self, engine, monkeypatch):+ """Test handling of missing optional fields in API response."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "items": [+ {+ "question_id": 12345,+ "title": "Minimal question",+ # Missing: body, owner, tags, score, etc.+ }+ ],+ "quota_remaining": 299,+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_stackexchange.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("test")+ assert len(previews) == 1+ assert previews[0]["title"] == "Minimal question"+ assert previews[0]["author"] == "Unknown"+ assert previews[0]["score"] == 0++ def test_get_full_content_without_raw(self, engine):+ """Test full content handling when _raw is missing."""+ items = [+ {+ "title": "Test Question",+ "author": "Test Author",+ "score": 10,+ }+ ]++ results = engine._get_full_content(items)+ assert len(results) == 1+ # Should not crash, content might be minimal++ def test_decode_html_complex_entities(self, engine):+ """Test decoding of various HTML entities."""+ test_cases = [+ ("<code>", "<code>"),+ ("'test'", "'test'"),+ (" space ", "\xa0space\xa0"),+ ("&amp;", "&"),+ ]++ for input_text, expected in test_cases:+ result = engine._decode_html(input_text)+ assert result == expected, f"Failed for {input_text}"+++class TestStackExchangeIntegration:+ """Integration tests making real API calls to Stack Exchange."""++ def test_real_search_python(self):+ """Test real search for Python questions."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine(max_results=5)+ results = engine._get_previews("python list comprehension")++ # Verify we got results+ assert len(results) > 0, "Should find Python questions"++ # Verify result structure+ for r in results:+ assert "title" in r, "Each result should have a title"+ assert "link" in r, "Each result should have a link"+ assert r["source"] == "Stack Overflow", (+ "Source should be Stack Overflow"+ )+ assert "stackoverflow.com" in r["link"], "Link should be SO URL"++ def test_real_search_returns_scores(self):+ """Test that real search returns scores."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine(max_results=5)+ results = engine._get_previews("javascript async await")++ assert len(results) > 0, "Should find JavaScript questions"++ # All should have score+ for r in results:+ assert "score" in r, "Should have score"+ assert isinstance(r["score"], int), "Score should be int"++ def test_real_search_returns_tags(self):+ """Test that real search returns tags."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine(max_results=5)+ results = engine._get_previews("react hooks")++ assert len(results) > 0, "Should find React questions"++ # At least some should have tags+ has_tags = any(r.get("tags") for r in results)+ assert has_tags, (+ f"At least one should have tags, got: {[r.get('tags') for r in results]}"+ )++ def test_real_search_different_site(self):+ """Test real search on different Stack Exchange site."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine(max_results=5, site="unix")+ results = engine._get_previews("bash script loop")++ assert len(results) > 0, "Should find Unix questions"++ # Source should reflect the site+ assert results[0]["source"] == "Unix & Linux", (+ f"Source should be Unix & Linux, got: {results[0]['source']}"+ )+ assert results[0]["site"] == "unix"++ def test_real_search_with_high_score(self):+ """Test real search with minimum score filter."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine(+ max_results=5, min_score=100, sort="votes"+ )+ results = engine._get_previews("python")++ assert len(results) > 0, "Should find high-score Python questions"++ # All should have score >= 100+ for r in results:+ assert r["score"] >= 100, (+ f"Score should be >= 100, got: {r['score']}"+ )++ def test_real_search_returns_answer_count(self):+ """Test that real search returns answer counts."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine(max_results=5, has_answers=True)+ results = engine._get_previews("docker container")++ assert len(results) > 0, "Should find Docker questions with answers"++ # All should have at least one answer+ for r in results:+ assert r["answer_count"] >= 1, (+ f"Should have answers, got: {r['answer_count']}"+ )++ def test_real_search_returns_author_info(self):+ """Test that real search returns author information."""+ from local_deep_research.web_search_engines.engines.search_engine_stackexchange import (+ StackExchangeSearchEngine,+ )++ engine = StackExchangeSearchEngine(max_results=5)+ results = engine._get_previews("git merge conflict")++ assert len(results) > 0, "Should find Git questions"++ # At least some should have author+ has_author = any(r.get("author") for r in results)+ assert has_author, "At least one should have author"diff --git a/tests/search_engines/test_search_engine_zenodo.py b/tests/search_engines/test_search_engine_zenodo.pynew file mode 100644index 0000000000..15b69d8b2e--- /dev/null+++ b/tests/search_engines/test_search_engine_zenodo.py@@ -0,0 +1,683 @@+"""+Tests for the Zenodo search engine.+Tests initialization, search functionality, and error handling.+"""++import pytest+from unittest.mock import Mock+++class TestZenodoSearchEngineInit:+ """Tests for Zenodo search engine initialization."""++ def test_init_default_parameters(self):+ """Test initialization with default parameters."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine()++ assert engine.max_results == 10+ assert engine.resource_type is None+ assert engine.access_right is None+ assert engine.communities is None+ assert engine.sort == "bestmatch"+ assert engine.is_public is True+ assert engine.is_scientific is True++ def test_init_custom_parameters(self):+ """Test initialization with custom parameters."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine(+ max_results=50,+ resource_type="dataset",+ access_right="open",+ communities="zenodo",+ sort="mostrecent",+ )++ assert engine.max_results == 50+ assert engine.resource_type == "dataset"+ assert engine.access_right == "open"+ assert engine.communities == "zenodo"+ assert engine.sort == "mostrecent"++ def test_base_url_set(self):+ """Test that API base URL is correctly set."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine()+ assert engine.base_url == "https://zenodo.org"+ assert engine.search_url == "https://zenodo.org/api/records"++ def test_user_agent_header_set(self):+ """Test that User-Agent header is set."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine()+ assert "User-Agent" in engine.headers+ assert "LocalDeepResearch" in engine.headers["User-Agent"]+++class TestZenodoQueryBuilding:+ """Tests for Zenodo query parameter building."""++ def test_build_query_params_basic(self):+ """Test basic query params building."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine(max_results=20)+ params = engine._build_query_params("machine learning")++ assert params["q"] == "machine learning"+ assert params["size"] == 20+ assert params["sort"] == "bestmatch"++ def test_build_query_params_with_type(self):+ """Test query params with resource type filter."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine(resource_type="dataset")+ params = engine._build_query_params("climate data")++ assert params["type"] == "dataset"++ def test_build_query_params_with_access(self):+ """Test query params with access right filter."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine(access_right="open")+ params = engine._build_query_params("test")++ assert params["access_right"] == "open"++ def test_build_query_params_with_communities(self):+ """Test query params with communities filter."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine(communities="astronomy")+ params = engine._build_query_params("test")++ assert params["communities"] == "astronomy"+++class TestZenodoCreatorParsing:+ """Tests for Zenodo creator parsing."""++ def test_parse_creators_basic(self):+ """Test parsing creators."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine()+ creators = [+ {"name": "John Smith"},+ {"name": "Jane Doe"},+ ]++ result = engine._parse_creators(creators)+ assert result == ["John Smith", "Jane Doe"]++ def test_parse_creators_limits_to_five(self):+ """Test that creator parsing limits to 5."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine()+ creators = [{"name": f"Author{i}"} for i in range(10)]++ result = engine._parse_creators(creators)+ assert len(result) == 5++ def test_parse_creators_empty(self):+ """Test parsing empty creators list."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine()+ result = engine._parse_creators([])+ assert result == []+++class TestZenodoResourceType:+ """Tests for Zenodo resource type handling."""++ def test_get_resource_type_label_with_title(self):+ """Test resource type label extraction."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine()+ resource_type = {"title": "Dataset", "type": "dataset"}++ result = engine._get_resource_type_label(resource_type)+ assert result == "Dataset"++ def test_get_resource_type_label_fallback(self):+ """Test resource type label fallback to type."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine()+ resource_type = {"type": "software"}++ result = engine._get_resource_type_label(resource_type)+ assert result == "software"++ def test_get_resource_type_label_empty(self):+ """Test resource type label with empty dict."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine()+ result = engine._get_resource_type_label({})+ assert result == "Unknown"+++class TestZenodoSearchExecution:+ """Tests for Zenodo search execution."""++ @pytest.fixture+ def engine(self):+ """Create a Zenodo engine."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ return ZenodoSearchEngine(max_results=10)++ def test_get_previews_success(self, engine, monkeypatch):+ """Test successful preview retrieval."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "hits": {+ "total": 100,+ "hits": [+ {+ "id": 12345,+ "metadata": {+ "title": "Test Dataset",+ "creators": [{"name": "John Smith"}],+ "description": "<p>A test dataset</p>",+ "doi": "10.5281/zenodo.12345",+ "publication_date": "2024-01-01",+ "resource_type": {+ "title": "Dataset",+ "type": "dataset",+ },+ "access_right": "open",+ "keywords": ["test", "data"],+ "license": {"id": "cc-by-4.0"},+ },+ "links": {+ "self_html": "https://zenodo.org/records/12345",+ "doi": "https://doi.org/10.5281/zenodo.12345",+ },+ }+ ],+ }+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_zenodo.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("test query")++ assert len(previews) == 1+ assert previews[0]["title"] == "Test Dataset"+ assert "John Smith" in previews[0]["authors"]+ assert previews[0]["doi"] == "10.5281/zenodo.12345"+ assert previews[0]["source"] == "Zenodo"+ assert previews[0]["resource_type"] == "Dataset"++ def test_get_previews_rate_limit_error(self, engine, monkeypatch):+ """Test that 429 errors raise RateLimitError."""+ from local_deep_research.web_search_engines.rate_limiting import (+ RateLimitError,+ )++ mock_response = Mock()+ mock_response.status_code = 429++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_zenodo.safe_get",+ Mock(return_value=mock_response),+ )++ with pytest.raises(RateLimitError):+ engine._get_previews("test")++ def test_get_previews_handles_exception(self, engine, monkeypatch):+ """Test that exceptions are handled gracefully."""+ import requests++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_zenodo.safe_get",+ Mock(side_effect=requests.RequestException("Network error")),+ )++ previews = engine._get_previews("test")+ assert previews == []+++class TestZenodoEdgeCases:+ """Tests for Zenodo edge cases and error handling."""++ @pytest.fixture+ def engine(self):+ """Create a Zenodo engine."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ return ZenodoSearchEngine(max_results=10)++ def test_get_previews_empty_results(self, engine, monkeypatch):+ """Test handling of empty search results."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "hits": {+ "total": 0,+ "hits": [],+ }+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_zenodo.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("xyznonexistentquery12345")+ assert previews == []++ def test_get_previews_html_in_description(self, engine, monkeypatch):+ """Test that HTML is stripped from description."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "hits": {+ "total": 1,+ "hits": [+ {+ "id": 12345,+ "metadata": {+ "title": "Test Record",+ "description": "<p>This is <strong>bold</strong> and <em>italic</em> text.</p>",+ "creators": [{"name": "Test Author"}],+ },+ "links": {},+ }+ ],+ }+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_zenodo.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("test")+ assert len(previews) == 1+ # HTML should be stripped+ assert "<p>" not in previews[0]["description"]+ assert "<strong>" not in previews[0]["description"]+ assert "bold" in previews[0]["description"]++ def test_get_previews_html_entities_decoded(self, engine, monkeypatch):+ """Test that HTML entities are decoded."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "hits": {+ "total": 1,+ "hits": [+ {+ "id": 12345,+ "metadata": {+ "title": "Test Record",+ "description": "Test & verify <data>",+ "creators": [],+ },+ "links": {},+ }+ ],+ }+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_zenodo.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("test")+ assert len(previews) == 1+ # HTML entities should be decoded+ assert "&" not in previews[0]["description"]+ assert "&" in previews[0]["description"]++ def test_get_previews_missing_optional_fields(self, engine, monkeypatch):+ """Test handling of missing optional fields."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "hits": {+ "total": 1,+ "hits": [+ {+ "id": 12345,+ "metadata": {+ "title": "Minimal Record",+ # Missing: creators, description, doi, etc.+ },+ "links": {},+ }+ ],+ }+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_zenodo.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("test")+ assert len(previews) == 1+ assert previews[0]["title"] == "Minimal Record"+ assert previews[0]["authors"] == []+ assert previews[0]["doi"] == ""++ def test_get_previews_unicode_in_title(self, engine, monkeypatch):+ """Test handling of Unicode characters in title."""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json = Mock(+ return_value={+ "hits": {+ "total": 1,+ "hits": [+ {+ "id": 12345,+ "metadata": {+ "title": "Données géographiques français",+ "creators": [{"name": "François Müller"}],+ },+ "links": {},+ }+ ],+ }+ }+ )+ mock_response.raise_for_status = Mock()++ monkeypatch.setattr(+ "local_deep_research.web_search_engines.engines.search_engine_zenodo.safe_get",+ Mock(return_value=mock_response),+ )++ previews = engine._get_previews("geographic data")+ assert len(previews) == 1+ assert "géographiques" in previews[0]["title"]+ assert "François Müller" in previews[0]["authors"]++ def test_get_full_content_without_raw(self, engine):+ """Test full content handling when _raw is missing."""+ items = [+ {+ "title": "Test Record",+ "authors": ["Test Author"],+ }+ ]++ results = engine._get_full_content(items)+ assert len(results) == 1+ # Should not crash++ def test_all_sort_options(self):+ """Test that various sort options can be used."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ sort_options = ["bestmatch", "mostrecent", "-mostrecent"]+ for sort in sort_options:+ engine = ZenodoSearchEngine(sort=sort)+ assert engine.sort == sort++ def test_all_access_rights(self):+ """Test that various access rights can be used."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ access_rights = [None, "open", "closed", "embargoed", "restricted"]+ for access in access_rights:+ engine = ZenodoSearchEngine(access_right=access)+ assert engine.access_right == access++ def test_all_resource_types(self):+ """Test that various resource types can be used."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ types = [+ None,+ "dataset",+ "software",+ "publication",+ "poster",+ "presentation",+ ]+ for resource_type in types:+ engine = ZenodoSearchEngine(resource_type=resource_type)+ assert engine.resource_type == resource_type+++class TestZenodoFullContent:+ """Tests for Zenodo full content retrieval."""++ def test_get_full_content_builds_content(self):+ """Test that full content builds proper content string."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine()++ items = [+ {+ "title": "Test Dataset",+ "authors": ["Author One", "Author Two"],+ "doi": "10.5281/zenodo.12345",+ "publication_date": "2024-01-01",+ "resource_type": "Dataset",+ "keywords": ["test", "data", "science"],+ "license": "cc-by-4.0",+ "description": "A test dataset for testing.",+ "_raw": {+ "metadata": {+ "description": "Full description of the dataset.",+ "keywords": ["test", "data", "science", "research"],+ "related_identifiers": [],+ "references": [],+ },+ "files": [+ {+ "key": "data.csv",+ "size": 1024,+ # Zenodo API returns checksums - using sha256 for test data+ "checksum": "sha256:abc123def456",+ }+ ],+ },+ }+ ]++ results = engine._get_full_content(items)++ assert len(results) == 1+ assert "Authors: Author One, Author Two" in results[0]["content"]+ assert "DOI: 10.5281/zenodo.12345" in results[0]["content"]+ assert "_raw" not in results[0]+ assert len(results[0]["files"]) == 1+++class TestZenodoIntegration:+ """Integration tests making real API calls to Zenodo.++ Note: These tests depend on external Zenodo API availability.+ They handle empty results gracefully since API may be rate-limited in CI.+ """++ def test_real_search_machine_learning(self):+ """Test real search for machine learning datasets."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine(max_results=5)+ results = engine._get_previews("machine learning")++ # API may be rate-limited; verify structure if results returned+ if len(results) > 0:+ for r in results:+ assert "title" in r, "Each result should have a title"+ assert "link" in r, "Each result should have a link"+ assert r["source"] == "Zenodo", "Source should be Zenodo"+ assert "zenodo.org" in r["link"], "Link should be Zenodo URL"++ def test_real_search_returns_doi(self):+ """Test that real search returns DOIs."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine(max_results=5)+ results = engine._get_previews("climate data")++ # API may be rate-limited; verify DOI if results returned+ if len(results) > 0:+ has_doi = any(r.get("doi") for r in results)+ assert has_doi, "At least one result should have a DOI"++ def test_real_search_datasets(self):+ """Test real search filtered to datasets."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine(max_results=5, resource_type="dataset")+ results = engine._get_previews("genomics")++ # API may be rate-limited; verify type if results returned+ if len(results) > 0:+ for r in results:+ assert r.get("resource_type") in [+ "Dataset",+ "dataset",+ "Other",+ ], f"Should be dataset type, got: {r.get('resource_type')}"++ def test_real_search_software(self):+ """Test real search filtered to software."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine(max_results=5, resource_type="software")+ results = engine._get_previews("python")++ # API may be rate-limited; verify links if results returned+ if len(results) > 0:+ for r in results:+ assert r["link"].startswith("https://zenodo.org"), (+ f"Link should be Zenodo URL: {r['link']}"+ )++ def test_real_search_returns_authors(self):+ """Test that real search returns authors."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine(max_results=5)+ results = engine._get_previews("neural network")++ # API may be rate-limited; verify authors if results returned+ if len(results) > 0:+ has_authors = any(r.get("authors") for r in results)+ assert has_authors, (+ f"At least one should have authors, got: {[r.get('authors') for r in results]}"+ )++ def test_real_search_open_access(self):+ """Test real search for open access records."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine(max_results=5, access_right="open")+ results = engine._get_previews("biology")++ # API may be rate-limited; verify access_right if results returned+ if len(results) > 0:+ for r in results:+ assert r.get("access_right") == "open", (+ f"Should be open access, got: {r.get('access_right')}"+ )++ def test_real_search_returns_publication_date(self):+ """Test that real search returns publication dates."""+ from local_deep_research.web_search_engines.engines.search_engine_zenodo import (+ ZenodoSearchEngine,+ )++ engine = ZenodoSearchEngine(max_results=5)+ results = engine._get_previews("astronomy")++ # API may be rate-limited; verify publication_date if results returned+ if len(results) > 0:+ has_date = any(r.get("publication_date") for r in results)+ assert has_date, "At least one should have publication_date"diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.jsonindex 990c0da056..ca2060e414 100644--- a/tests/settings/golden_master_settings.json+++ b/tests/settings/golden_master_settings.json@@ -3590,6 +3590,132 @@],"visible": true},+ "search.engine.web.gutenberg": {+ "category": "gutenberg",+ "description": "Project Gutenberg search engine configuration",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "Project Gutenberg Search Engine",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "json",+ "value": {+ "class_name": "GutenbergSearchEngine",+ "description": "Search 70,000+ free public domain books with full text via Gutendex.",+ "module_path": ".engines.search_engine_gutenberg",+ "reliability": 0.95,+ "requires_api_key": false,+ "requires_llm": true+ },+ "visible": false+ },+ "search.engine.web.gutenberg.class_name": {+ "category": "gutenberg",+ "description": "Python class implementing Project Gutenberg search.",+ "editable": false,+ "name": "Class Name",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "GutenbergSearchEngine",+ "visible": false+ },+ "search.engine.web.gutenberg.default_params.max_results": {+ "category": "gutenberg",+ "description": "Maximum number of results to retrieve from Project Gutenberg.",+ "editable": true,+ "max_value": 32,+ "min_value": 1,+ "name": "Max Results",+ "type": "SEARCH",+ "ui_element": "number",+ "value": 20,+ "visible": true+ },+ "search.engine.web.gutenberg.description": {+ "category": "gutenberg",+ "description": "Human-readable description of the search engine.",+ "editable": false,+ "name": "Description",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "Search 70,000+ free public domain books with full text via Gutendex.",+ "visible": false+ },+ "search.engine.web.gutenberg.display_name": {+ "category": "gutenberg",+ "description": "Display name for Project Gutenberg search engine.",+ "editable": false,+ "name": "Display Name",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "Project Gutenberg",+ "visible": false+ },+ "search.engine.web.gutenberg.module_path": {+ "category": "gutenberg",+ "description": "Python module path for Project Gutenberg search engine.",+ "editable": false,+ "name": "Module Path",+ "type": "SEARCH",+ "ui_element": "text",+ "value": ".engines.search_engine_gutenberg",+ "visible": false+ },+ "search.engine.web.gutenberg.reliability": {+ "category": "gutenberg",+ "description": "Reliability score for Project Gutenberg.",+ "editable": true,+ "max_value": 1.0,+ "min_value": 0.0,+ "name": "Reliability",+ "step": 0.05,+ "type": "SEARCH",+ "ui_element": "range",+ "value": 0.95,+ "visible": true+ },+ "search.engine.web.gutenberg.requires_api_key": {+ "category": "gutenberg",+ "description": "Project Gutenberg is free and does not require an API key.",+ "editable": false,+ "name": "Requires API Key",+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": false,+ "visible": false+ },+ "search.engine.web.gutenberg.strengths": {+ "category": "gutenberg",+ "description": "Key strengths of Project Gutenberg.",+ "editable": true,+ "name": "Strengths",+ "type": "SEARCH",+ "ui_element": "json",+ "value": [+ "public domain",+ "full text",+ "classic literature",+ "free ebooks",+ "multiple formats"+ ],+ "visible": true+ },+ "search.engine.web.gutenberg.weaknesses": {+ "category": "gutenberg",+ "description": "Limitations of Project Gutenberg.",+ "editable": true,+ "name": "Weaknesses",+ "type": "SEARCH",+ "ui_element": "json",+ "value": [+ "public domain only",+ "older works",+ "limited modern titles"+ ],+ "visible": true+ },"search.engine.web.mojeek.api_key": {"category": "mojeek","description": "The Mojeek API key to use. Get one at mojeek.com/services/api.",@@ -4342,6 +4468,133 @@],"visible": true},+ "search.engine.web.openlibrary": {+ "category": "openlibrary",+ "description": "Open Library search engine configuration",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "Open Library Search Engine",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "json",+ "value": {+ "class_name": "OpenLibrarySearchEngine",+ "description": "Search 2M+ books with metadata, covers, and full text from Internet Archive.",+ "module_path": ".engines.search_engine_openlibrary",+ "reliability": 0.9,+ "requires_api_key": false,+ "requires_llm": true+ },+ "visible": false+ },+ "search.engine.web.openlibrary.class_name": {+ "category": "openlibrary",+ "description": "Python class implementing Open Library search.",+ "editable": false,+ "name": "Class Name",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "OpenLibrarySearchEngine",+ "visible": false+ },+ "search.engine.web.openlibrary.default_params.max_results": {+ "category": "openlibrary",+ "description": "Maximum number of results to retrieve from Open Library.",+ "editable": true,+ "max_value": 100,+ "min_value": 1,+ "name": "Max Results",+ "type": "SEARCH",+ "ui_element": "number",+ "value": 20,+ "visible": true+ },+ "search.engine.web.openlibrary.description": {+ "category": "openlibrary",+ "description": "Human-readable description of the search engine.",+ "editable": false,+ "name": "Description",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "Search 2M+ books with metadata, covers, and full text from Internet Archive.",+ "visible": false+ },+ "search.engine.web.openlibrary.display_name": {+ "category": "openlibrary",+ "description": "Display name for Open Library search engine.",+ "editable": false,+ "name": "Display Name",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "Open Library",+ "visible": false+ },+ "search.engine.web.openlibrary.module_path": {+ "category": "openlibrary",+ "description": "Python module path for Open Library search engine.",+ "editable": false,+ "name": "Module Path",+ "type": "SEARCH",+ "ui_element": "text",+ "value": ".engines.search_engine_openlibrary",+ "visible": false+ },+ "search.engine.web.openlibrary.reliability": {+ "category": "openlibrary",+ "description": "Reliability score for Open Library.",+ "editable": true,+ "max_value": 1.0,+ "min_value": 0.0,+ "name": "Reliability",+ "step": 0.05,+ "type": "SEARCH",+ "ui_element": "range",+ "value": 0.9,+ "visible": true+ },+ "search.engine.web.openlibrary.requires_api_key": {+ "category": "openlibrary",+ "description": "Open Library is free and does not require an API key.",+ "editable": false,+ "name": "Requires API Key",+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": false,+ "visible": false+ },+ "search.engine.web.openlibrary.strengths": {+ "category": "openlibrary",+ "description": "Key strengths of Open Library.",+ "editable": true,+ "name": "Strengths",+ "type": "SEARCH",+ "ui_element": "json",+ "value": [+ "books",+ "literature",+ "metadata",+ "covers",+ "full text",+ "Internet Archive"+ ],+ "visible": true+ },+ "search.engine.web.openlibrary.weaknesses": {+ "category": "openlibrary",+ "description": "Limitations of Open Library.",+ "editable": true,+ "name": "Weaknesses",+ "type": "SEARCH",+ "ui_element": "json",+ "value": [+ "books only",+ "variable metadata quality",+ "English focus"+ ],+ "visible": true+ },"search.engine.web.paperless.api_key": {"category": "paperless","description": "API key for authentication (get from Paperless admin panel)",@@ -4788,6 +5041,142 @@"value": "[\"Higher resource usage\", \"May hit rate limits on multiple engines\", \"Results may vary in quality\", \"Requires LLM for optimal selection\"]","visible": true},+ "search.engine.web.pubchem": {+ "category": "pubchem",+ "description": "PubChem search engine configuration",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "PubChem Search Engine",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "json",+ "value": {+ "class_name": "PubChemSearchEngine",+ "description": "Search millions of chemical compounds with structures, properties, and bioactivity data.",+ "module_path": ".engines.search_engine_pubchem",+ "reliability": 0.95,+ "requires_api_key": false,+ "requires_llm": true+ },+ "visible": false+ },+ "search.engine.web.pubchem.class_name": {+ "category": "pubchem",+ "description": "Python class implementing PubChem search.",+ "editable": false,+ "name": "Class Name",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "PubChemSearchEngine",+ "visible": false+ },+ "search.engine.web.pubchem.default_params.include_synonyms": {+ "category": "pubchem",+ "description": "Include compound synonyms in full content results.",+ "editable": true,+ "name": "Include Synonyms",+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": true,+ "visible": true+ },+ "search.engine.web.pubchem.default_params.max_results": {+ "category": "pubchem",+ "description": "Maximum number of results to retrieve from PubChem.",+ "editable": true,+ "max_value": 50,+ "min_value": 1,+ "name": "Max Results",+ "type": "SEARCH",+ "ui_element": "number",+ "value": 10,+ "visible": true+ },+ "search.engine.web.pubchem.description": {+ "category": "pubchem",+ "description": "Human-readable description of the search engine.",+ "editable": false,+ "name": "Description",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "Search millions of chemical compounds with structures, properties, and bioactivity data.",+ "visible": false+ },+ "search.engine.web.pubchem.display_name": {+ "category": "pubchem",+ "description": "Display name for PubChem search engine.",+ "editable": false,+ "name": "Display Name",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "PubChem",+ "visible": false+ },+ "search.engine.web.pubchem.module_path": {+ "category": "pubchem",+ "description": "Python module path for PubChem search engine.",+ "editable": false,+ "name": "Module Path",+ "type": "SEARCH",+ "ui_element": "text",+ "value": ".engines.search_engine_pubchem",+ "visible": false+ },+ "search.engine.web.pubchem.reliability": {+ "category": "pubchem",+ "description": "Reliability score for PubChem.",+ "editable": true,+ "max_value": 1.0,+ "min_value": 0.0,+ "name": "Reliability",+ "step": 0.05,+ "type": "SEARCH",+ "ui_element": "range",+ "value": 0.95,+ "visible": true+ },+ "search.engine.web.pubchem.requires_api_key": {+ "category": "pubchem",+ "description": "PubChem is free and does not require an API key.",+ "editable": false,+ "name": "Requires API Key",+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": false,+ "visible": false+ },+ "search.engine.web.pubchem.strengths": {+ "category": "pubchem",+ "description": "Key strengths of PubChem.",+ "editable": true,+ "name": "Strengths",+ "type": "SEARCH",+ "ui_element": "json",+ "value": [+ "chemistry",+ "compounds",+ "drug information",+ "molecular properties",+ "bioactivity"+ ],+ "visible": true+ },+ "search.engine.web.pubchem.weaknesses": {+ "category": "pubchem",+ "description": "Limitations of PubChem.",+ "editable": true,+ "name": "Weaknesses",+ "type": "SEARCH",+ "ui_element": "json",+ "value": [+ "chemistry only",+ "technical data",+ "requires chemical knowledge"+ ],+ "visible": true+ },"search.engine.web.pubmed.api_key": {"category": "pubmed","description": "The PubMed API key to use.",@@ -6564,6 +6953,154 @@],"visible": false},+ "search.engine.web.stackexchange": {+ "category": "stackexchange",+ "description": "Stack Exchange search engine configuration",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "Stack Exchange Search Engine",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "json",+ "value": {+ "class_name": "StackExchangeSearchEngine",+ "description": "Search Stack Overflow and other Q&A sites for programming answers.",+ "module_path": ".engines.search_engine_stackexchange",+ "reliability": 0.9,+ "requires_api_key": false,+ "requires_llm": true+ },+ "visible": false+ },+ "search.engine.web.stackexchange.class_name": {+ "category": "stackexchange",+ "description": "Python class implementing Stack Exchange search.",+ "editable": false,+ "name": "Class Name",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "StackExchangeSearchEngine",+ "visible": false+ },+ "search.engine.web.stackexchange.default_params.max_results": {+ "category": "stackexchange",+ "description": "Maximum number of results to retrieve from Stack Exchange.",+ "editable": true,+ "max_value": 100,+ "min_value": 1,+ "name": "Max Results",+ "type": "SEARCH",+ "ui_element": "number",+ "value": 20,+ "visible": true+ },+ "search.engine.web.stackexchange.default_params.site": {+ "category": "stackexchange",+ "description": "Stack Exchange site to search (stackoverflow, serverfault, superuser, etc.).",+ "editable": true,+ "name": "Site",+ "options": [+ "stackoverflow",+ "serverfault",+ "superuser",+ "askubuntu",+ "unix",+ "math",+ "physics",+ "stats",+ "security",+ "dba"+ ],+ "type": "SEARCH",+ "ui_element": "select",+ "value": "stackoverflow",+ "visible": true+ },+ "search.engine.web.stackexchange.description": {+ "category": "stackexchange",+ "description": "Human-readable description of the search engine.",+ "editable": false,+ "name": "Description",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "Search Stack Overflow and other Q&A sites for programming answers.",+ "visible": false+ },+ "search.engine.web.stackexchange.display_name": {+ "category": "stackexchange",+ "description": "Display name for Stack Exchange search engine.",+ "editable": false,+ "name": "Display Name",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "Stack Exchange",+ "visible": false+ },+ "search.engine.web.stackexchange.module_path": {+ "category": "stackexchange",+ "description": "Python module path for Stack Exchange search engine.",+ "editable": false,+ "name": "Module Path",+ "type": "SEARCH",+ "ui_element": "text",+ "value": ".engines.search_engine_stackexchange",+ "visible": false+ },+ "search.engine.web.stackexchange.reliability": {+ "category": "stackexchange",+ "description": "Reliability score for Stack Exchange.",+ "editable": true,+ "max_value": 1.0,+ "min_value": 0.0,+ "name": "Reliability",+ "step": 0.05,+ "type": "SEARCH",+ "ui_element": "range",+ "value": 0.9,+ "visible": true+ },+ "search.engine.web.stackexchange.requires_api_key": {+ "category": "stackexchange",+ "description": "Stack Exchange is free without an API key (300 requests/day).",+ "editable": false,+ "name": "Requires API Key",+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": false,+ "visible": false+ },+ "search.engine.web.stackexchange.strengths": {+ "category": "stackexchange",+ "description": "Key strengths of Stack Exchange.",+ "editable": true,+ "name": "Strengths",+ "type": "SEARCH",+ "ui_element": "json",+ "value": [+ "programming",+ "Q&A",+ "code examples",+ "community moderated",+ "multiple sites"+ ],+ "visible": true+ },+ "search.engine.web.stackexchange.weaknesses": {+ "category": "stackexchange",+ "description": "Limitations of Stack Exchange.",+ "editable": true,+ "name": "Weaknesses",+ "type": "SEARCH",+ "ui_element": "json",+ "value": [+ "technical focus",+ "rate limited",+ "Q&A format only"+ ],+ "visible": true+ },"search.engine.web.tavily.api_key": {"category": "tavily","description": "The Tavily API key to use.",@@ -7279,6 +7816,133 @@],"visible": true},+ "search.engine.web.zenodo": {+ "category": "zenodo",+ "description": "Zenodo search engine configuration",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "Zenodo Search Engine",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "json",+ "value": {+ "class_name": "ZenodoSearchEngine",+ "description": "Search millions of research datasets, software, and publications with DOIs.",+ "module_path": ".engines.search_engine_zenodo",+ "reliability": 0.95,+ "requires_api_key": false,+ "requires_llm": true+ },+ "visible": false+ },+ "search.engine.web.zenodo.class_name": {+ "category": "zenodo",+ "description": "Python class implementing Zenodo search.",+ "editable": false,+ "name": "Class Name",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "ZenodoSearchEngine",+ "visible": false+ },+ "search.engine.web.zenodo.default_params.max_results": {+ "category": "zenodo",+ "description": "Maximum number of results to retrieve from Zenodo.",+ "editable": true,+ "max_value": 100,+ "min_value": 1,+ "name": "Max Results",+ "type": "SEARCH",+ "ui_element": "number",+ "value": 20,+ "visible": true+ },+ "search.engine.web.zenodo.description": {+ "category": "zenodo",+ "description": "Human-readable description of the search engine.",+ "editable": false,+ "name": "Description",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "Search millions of research datasets, software, and publications with DOIs.",+ "visible": false+ },+ "search.engine.web.zenodo.display_name": {+ "category": "zenodo",+ "description": "Display name for Zenodo search engine.",+ "editable": false,+ "name": "Display Name",+ "type": "SEARCH",+ "ui_element": "text",+ "value": "Zenodo",+ "visible": false+ },+ "search.engine.web.zenodo.module_path": {+ "category": "zenodo",+ "description": "Python module path for Zenodo search engine.",+ "editable": false,+ "name": "Module Path",+ "type": "SEARCH",+ "ui_element": "text",+ "value": ".engines.search_engine_zenodo",+ "visible": false+ },+ "search.engine.web.zenodo.reliability": {+ "category": "zenodo",+ "description": "Reliability score for Zenodo.",+ "editable": true,+ "max_value": 1.0,+ "min_value": 0.0,+ "name": "Reliability",+ "step": 0.05,+ "type": "SEARCH",+ "ui_element": "range",+ "value": 0.95,+ "visible": true+ },+ "search.engine.web.zenodo.requires_api_key": {+ "category": "zenodo",+ "description": "Zenodo is free and does not require an API key for search.",+ "editable": false,+ "name": "Requires API Key",+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": false,+ "visible": false+ },+ "search.engine.web.zenodo.strengths": {+ "category": "zenodo",+ "description": "Key strengths of Zenodo.",+ "editable": true,+ "name": "Strengths",+ "type": "SEARCH",+ "ui_element": "json",+ "value": [+ "research data",+ "datasets",+ "DOIs",+ "software",+ "open access",+ "CERN"+ ],+ "visible": true+ },+ "search.engine.web.zenodo.weaknesses": {+ "category": "zenodo",+ "description": "Limitations of Zenodo.",+ "editable": true,+ "name": "Weaknesses",+ "type": "SEARCH",+ "ui_element": "json",+ "value": [+ "research focus",+ "variable quality",+ "metadata only"+ ],+ "visible": true+ },"search.favorites": {"category": "search_general","description": "List of favorite search engine IDs that appear at the top of the dropdown. Edit as JSON array, e.g. [\"arxiv\", \"brave\"]",