~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 OpenAlex academic search engine
LearningCircuitbeb29d7c5f89
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.jsonindex 5649744471..d278d7d3b0 100644--- a/src/local_deep_research/defaults/default_settings.json+++ b/src/local_deep_research/defaults/default_settings.json@@ -973,6 +973,10 @@"label": "Pubmed","value": "pubmed"},+ {+ "label": "OpenAlex",+ "value": "openalex"+ },{"label": "Github","value": "github"diff --git a/src/local_deep_research/defaults/settings_openalex.json b/src/local_deep_research/defaults/settings_openalex.jsonnew file mode 100644index 0000000000..4ea056771e--- /dev/null+++ b/src/local_deep_research/defaults/settings_openalex.json@@ -0,0 +1,252 @@+{+ "search.engine.web.openalex": {+ "category": "openalex",+ "description": "OpenAlex academic search engine configuration",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "OpenAlex Search Engine",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "json",+ "value": {+ "module_path": ".engines.search_engine_openalex",+ "class_name": "OpenAlexSearchEngine",+ "requires_api_key": false,+ "requires_llm": true,+ "description": "Search 250+ million academic papers with natural language queries",+ "reliability": 0.95+ },+ "visible": false+ },+ "search.engine.web.openalex.display_name": {+ "category": "openalex",+ "description": "Display name to use in the U.I. for this search engine.",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "Display Name",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "text",+ "value": "OpenAlex",+ "visible": false+ },+ "search.engine.web.openalex.description": {+ "category": "openalex",+ "description": "Human-readable description of the search engine.",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "Description",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "text",+ "value": "Search 250+ million academic papers with natural language queries. Comprehensive scholarly database covering all disciplines.",+ "visible": false+ },+ "search.engine.web.openalex.class_name": {+ "category": "openalex",+ "description": "Setting for openalex.class_name",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Class Name",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "text",+ "value": "OpenAlexSearchEngine",+ "visible": true+ },+ "search.engine.web.openalex.module_path": {+ "category": "openalex",+ "description": "Setting for openalex.module_path",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Module Path",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "text",+ "value": ".engines.search_engine_openalex",+ "visible": true+ },+ "search.engine.web.openalex.reliability": {+ "category": "openalex",+ "description": "Setting for openalex.reliability",+ "editable": true,+ "max_value": 1.0,+ "min_value": 0.0,+ "name": "Reliability",+ "options": null,+ "step": 0.05,+ "type": "SEARCH",+ "ui_element": "range",+ "value": 0.95,+ "visible": true+ },+ "search.engine.web.openalex.requires_api_key": {+ "category": "openalex",+ "description": "Setting for openalex.requires_api_key",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Requires Api Key",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": false,+ "visible": true+ },+ "search.engine.web.openalex.email": {+ "category": "openalex",+ "description": "Email address for polite pool access (optional but recommended). Provides faster response times.",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Email (for Polite Pool)",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "text",+ "value": "",+ "visible": true+ },+ "search.engine.web.openalex.default_params.max_results": {+ "category": "openalex",+ "description": "Maximum number of results to retrieve from OpenAlex",+ "editable": true,+ "max_value": 200,+ "min_value": 1,+ "name": "Max Results",+ "options": null,+ "step": 1,+ "type": "SEARCH",+ "ui_element": "number",+ "value": 25,+ "visible": true+ },+ "search.engine.web.openalex.default_params.sort_by": {+ "category": "openalex",+ "description": "How to sort the search results",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Sort By",+ "options": [+ {"label": "Relevance", "value": "relevance"},+ {"label": "Citation Count", "value": "cited_by_count"},+ {"label": "Publication Date", "value": "publication_date"}+ ],+ "step": null,+ "type": "SEARCH",+ "ui_element": "select",+ "value": "relevance",+ "visible": true+ },+ "search.engine.web.openalex.default_params.filter_open_access": {+ "category": "openalex",+ "description": "Only return open access papers that are freely available",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Open Access Only",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": false,+ "visible": true+ },+ "search.engine.web.openalex.default_params.min_citations": {+ "category": "openalex",+ "description": "Minimum number of citations required (0 for no filter)",+ "editable": true,+ "max_value": 1000,+ "min_value": 0,+ "name": "Minimum Citations",+ "options": null,+ "step": 1,+ "type": "SEARCH",+ "ui_element": "number",+ "value": 0,+ "visible": true+ },+ "search.engine.web.openalex.default_params.from_publication_date": {+ "category": "openalex",+ "description": "Only return papers published after this date (YYYY-MM-DD format, leave empty for all dates)",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "From Publication Date",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "text",+ "value": "",+ "visible": true+ },+ "search.engine.web.openalex.journal_reputation.enabled": {+ "category": "openalex",+ "description": "Enable journal quality filtering for this search engine.",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Filter Low-Quality Journals",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": true,+ "visible": true+ },+ "search.engine.web.openalex.strengths": {+ "category": "openalex",+ "description": "Setting for openalex.strengths",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Strengths",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "json",+ "value": [+ "academic papers",+ "scholarly research",+ "natural language queries",+ "all disciplines",+ "citation analysis",+ "open access content",+ "comprehensive coverage",+ "no API key required",+ "high rate limits"+ ],+ "visible": true+ },+ "search.engine.web.openalex.weaknesses": {+ "category": "openalex",+ "description": "Setting for openalex.weaknesses",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Weaknesses",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "json",+ "value": [+ "non-academic content",+ "news articles",+ "general web content",+ "real-time information"+ ],+ "visible": true+ }+}diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py b/src/local_deep_research/web_search_engines/engines/search_engine_openalex.pynew file mode 100644index 0000000000..54ffbd3cb8--- /dev/null+++ b/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py@@ -0,0 +1,411 @@+"""OpenAlex search engine implementation for academic papers and research."""++import time+from typing import Any, Dict, List, Optional++import requests+from langchain_core.language_models import BaseLLM+from loguru import logger++from ...advanced_search_system.filters.journal_reputation_filter import (+ JournalReputationFilter,+)+from ..rate_limiting import RateLimitError+from ..search_engine_base import BaseSearchEngine+++class OpenAlexSearchEngine(BaseSearchEngine):+ """OpenAlex search engine implementation with natural language query support."""++ def __init__(+ self,+ max_results: int = 25,+ email: Optional[str] = None,+ sort_by: str = "relevance",+ filter_open_access: bool = False,+ min_citations: int = 0,+ from_publication_date: Optional[str] = None,+ llm: Optional[BaseLLM] = None,+ max_filtered_results: Optional[int] = None,+ settings_snapshot: Optional[Dict[str, Any]] = None,+ **kwargs,+ ):+ """+ Initialize the OpenAlex search engine.++ Args:+ max_results: Maximum number of search results+ email: Email for polite pool (gets faster response) - optional+ sort_by: Sort order ('relevance', 'cited_by_count', 'publication_date')+ filter_open_access: Only return open access papers+ min_citations: Minimum citation count filter+ from_publication_date: Filter papers from this date (YYYY-MM-DD)+ llm: Language model for relevance filtering+ max_filtered_results: Maximum number of results to keep after filtering+ settings_snapshot: Settings snapshot for configuration+ **kwargs: Additional parameters to pass to parent class+ """+ # Initialize journal reputation filter if needed+ content_filters = []+ journal_filter = JournalReputationFilter.create_default(+ model=llm,+ engine_name="openalex",+ settings_snapshot=settings_snapshot,+ )+ if journal_filter is not None:+ content_filters.append(journal_filter)++ # Initialize the BaseSearchEngine+ super().__init__(+ llm=llm,+ max_filtered_results=max_filtered_results,+ max_results=max_results,+ content_filters=content_filters,+ settings_snapshot=settings_snapshot,+ **kwargs,+ )++ self.sort_by = sort_by+ self.filter_open_access = filter_open_access+ self.min_citations = min_citations+ self.from_publication_date = from_publication_date++ # Get email from settings if not provided+ if not email and settings_snapshot:+ from ...config.search_config import get_setting_from_snapshot++ try:+ email = get_setting_from_snapshot(+ "search.engine.web.openalex.email",+ settings_snapshot=settings_snapshot,+ )+ except Exception:+ pass++ self.email = email++ # API configuration+ self.api_base = "https://api.openalex.org"+ self.headers = {+ "User-Agent": f"Local-Deep-Research-Agent{f' ({email})' if email else ''}",+ "Accept": "application/json",+ }++ if email:+ # Email allows access to polite pool with faster response times+ logger.info(f"Using OpenAlex polite pool with email: {email}")+ else:+ logger.info(+ "Using OpenAlex without email (consider adding email for faster responses)"+ )++ def _get_previews(self, query: str) -> List[Dict[str, Any]]:+ """+ Get preview information for OpenAlex search results.++ Args:+ query: The search query (natural language supported!)++ Returns:+ List of preview dictionaries+ """+ logger.info(f"Searching OpenAlex for: {query}")++ # Build the search URL with parameters+ params = {+ "search": query, # OpenAlex handles natural language beautifully+ "per_page": min(self.max_results, 200), # OpenAlex allows up to 200+ "page": 1,+ }++ # Add optional filters+ filters = []++ if self.filter_open_access:+ filters.append("is_oa:true")++ if self.min_citations > 0:+ filters.append(f"cited_by_count:>{self.min_citations}")++ if self.from_publication_date:+ filters.append(+ f"from_publication_date:{self.from_publication_date}"+ )++ if filters:+ params["filter"] = ",".join(filters)++ # Add sorting+ sort_map = {+ "relevance": "relevance_score:desc",+ "cited_by_count": "cited_by_count:desc",+ "publication_date": "publication_date:desc",+ }+ params["sort"] = sort_map.get(self.sort_by, "relevance_score:desc")++ # Add email to params for polite pool+ if self.email:+ params["mailto"] = self.email++ try:+ # Apply rate limiting before making the request+ self._last_wait_time = self.rate_tracker.apply_rate_limit(+ self.engine_type+ )+ logger.debug(+ f"Applied rate limit wait: {self._last_wait_time:.2f}s"+ )++ # Make the API request+ response = requests.get(+ f"{self.api_base}/works",+ params=params,+ headers=self.headers,+ timeout=30,+ )++ # Log rate limit info if available+ if "x-ratelimit-remaining" in response.headers:+ remaining = response.headers.get("x-ratelimit-remaining")+ limit = response.headers.get("x-ratelimit-limit", "unknown")+ logger.debug(+ f"OpenAlex rate limit: {remaining}/{limit} requests remaining"+ )++ if response.status_code == 200:+ data = response.json()+ results = data.get("results", [])+ meta = data.get("meta", {})+ total_count = meta.get("count", 0)++ logger.info(+ f"OpenAlex returned {len(results)} results (total available: {total_count:,})"+ )++ # Record successful outcome for adaptive rate limiting+ if self.rate_tracker.enabled:+ self.rate_tracker.record_outcome(+ self.engine_type,+ self._last_wait_time,+ success=True,+ results_count=len(results),+ )++ # Format results as previews+ previews = []+ for work in results:+ preview = self._format_work_preview(work)+ if preview:+ previews.append(preview)++ return previews++ elif response.status_code == 429:+ # Rate limited (very rare with OpenAlex)+ logger.warning(+ "OpenAlex rate limit reached. Waiting 1 second..."+ )++ # Record rate limit failure for adaptive learning+ if self.rate_tracker.enabled:+ self.rate_tracker.record_outcome(+ self.engine_type,+ self._last_wait_time,+ success=False,+ results_count=0,+ )++ time.sleep(1)+ raise RateLimitError("OpenAlex rate limit exceeded")++ else:+ logger.error(+ f"OpenAlex API error: {response.status_code} - {response.text[:200]}"+ )++ # Record failure for adaptive learning+ if self.rate_tracker.enabled:+ self.rate_tracker.record_outcome(+ self.engine_type,+ self._last_wait_time,+ success=False,+ results_count=0,+ )++ return []++ except Exception:+ logger.exception("Error searching OpenAlex")++ # Record failure for adaptive learning+ if self.rate_tracker.enabled and hasattr(self, "_last_wait_time"):+ self.rate_tracker.record_outcome(+ self.engine_type,+ self._last_wait_time,+ success=False,+ results_count=0,+ )++ return []++ def _format_work_preview(+ self, work: Dict[str, Any]+ ) -> Optional[Dict[str, Any]]:+ """+ Format an OpenAlex work as a preview dictionary.++ Args:+ work: OpenAlex work object++ Returns:+ Formatted preview dictionary or None if formatting fails+ """+ try:+ # Extract basic information+ work_id = work.get("id", "")+ title = work.get("display_name", "No title")++ # Build snippet from abstract or first part of title+ abstract = None+ if work.get("abstract_inverted_index"):+ # Reconstruct abstract from inverted index+ abstract = self._reconstruct_abstract(+ work["abstract_inverted_index"]+ )++ snippet = abstract[:500] if abstract else f"Academic paper: {title}"++ # Get publication info+ publication_year = work.get("publication_year", "")+ publication_date = work.get("publication_date", "")++ # Get venue/journal info+ venue = work.get("primary_location", {})+ journal_name = ""+ if venue:+ source = venue.get("source", {})+ if source:+ journal_name = source.get("display_name", "")++ # Get authors+ authors = []+ for authorship in work.get("authorships", [])[+ :5+ ]: # Limit to 5 authors+ author = authorship.get("author", {})+ if author:+ authors.append(author.get("display_name", ""))++ authors_str = ", ".join(authors)+ if len(work.get("authorships", [])) > 5:+ authors_str += " et al."++ # Get metrics+ cited_by_count = work.get("cited_by_count", 0)++ # Get URL - prefer DOI, fallback to OpenAlex URL+ url = work.get("doi", work_id)+ if not url.startswith("http"):+ if url.startswith("https://doi.org/"):+ pass # Already a full DOI URL+ elif url.startswith("10."):+ url = f"https://doi.org/{url}"+ else:+ url = work_id # OpenAlex URL++ # Check if open access+ is_oa = work.get("is_oa", False)+ oa_url = None+ if is_oa:+ best_location = work.get("best_oa_location", {})+ if best_location:+ oa_url = best_location.get("pdf_url") or best_location.get(+ "landing_page_url"+ )++ preview = {+ "id": work_id,+ "title": title,+ "link": url,+ "snippet": snippet,+ "authors": authors_str,+ "year": publication_year,+ "date": publication_date,+ "journal": journal_name,+ "citations": cited_by_count,+ "is_open_access": is_oa,+ "oa_url": oa_url,+ "abstract": abstract,+ "type": "academic_paper",+ }++ return preview++ except Exception:+ logger.exception(+ f"Error formatting OpenAlex work: {work.get('id', 'unknown')}"+ )+ return None++ def _reconstruct_abstract(+ self, inverted_index: Dict[str, List[int]]+ ) -> str:+ """+ Reconstruct abstract text from OpenAlex inverted index format.++ Args:+ inverted_index: Dictionary mapping words to their positions++ Returns:+ Reconstructed abstract text+ """+ try:+ # Create position-word mapping+ position_word = {}+ for word, positions in inverted_index.items():+ for pos in positions:+ position_word[pos] = word++ # Sort by position and reconstruct+ sorted_positions = sorted(position_word.keys())+ words = [position_word[pos] for pos in sorted_positions]++ return " ".join(words)++ except Exception:+ logger.debug("Could not reconstruct abstract from inverted index")+ return ""++ def _get_full_content(+ self, relevant_items: List[Dict[str, Any]]+ ) -> List[Dict[str, Any]]:+ """+ Get full content for relevant items (OpenAlex provides most content in preview).++ Args:+ relevant_items: List of relevant preview dictionaries++ Returns:+ List of result dictionaries with full content+ """+ # OpenAlex returns comprehensive data in the initial search,+ # so we don't need a separate full content fetch+ results = []+ for item in relevant_items:+ result = {+ "title": item.get("title", ""),+ "link": item.get("link", ""),+ "snippet": item.get("snippet", ""),+ "content": item.get("abstract", item.get("snippet", "")),+ "metadata": {+ "authors": item.get("authors", ""),+ "year": item.get("year", ""),+ "journal": item.get("journal", ""),+ "citations": item.get("citations", 0),+ "is_open_access": item.get("is_open_access", False),+ "oa_url": item.get("oa_url"),+ },+ }+ results.append(result)++ return results