Skip to content

~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.

bug fixes and semantic scholar added

LearningCircuit3fd1ac627460
diff --git a/src/local_deep_research/config.py b/src/local_deep_research/config.py
index bd4ffe4362..0bfceaa320 100644
--- a/src/local_deep_research/config.py
+++ b/src/local_deep_research/config.py
@@ -91,15 +91,15 @@ def get_search(search_tool=None):
params = {
"search_tool": tool,
"llm_instance": get_llm(),
- "max_results": settings.get("max_results"),
- "region": settings.get("region"),
- "time_period": settings.get("time_period"),
- "safe_search": settings.get("safe_search"),
- "search_snippets_only": settings.get("snippets_only"),
- "search_language": settings.get("search_language"),
- "max_filtered_results": settings.get("max_filtered_results")
+ "max_results": settings.search.max_results,
+ "region": settings.search.region,
+ "time_period": settings.search.time_period,
+ "safe_search": settings.search.safe_search,
+ "search_snippets_only": settings.search.snippets_only,
+ "search_language": settings.search.search_language,
+ "max_filtered_results": settings.search.max_filtered_results
}
-
+ logger.info(f"Search config params: {params}")
# Create and return search engine
return factory_get_search(**params)
diff --git a/src/local_deep_research/defaults/search_engines.toml b/src/local_deep_research/defaults/search_engines.toml
index 9733630212..479c64bea5 100644
--- a/src/local_deep_research/defaults/search_engines.toml
+++ b/src/local_deep_research/defaults/search_engines.toml
@@ -186,9 +186,48 @@ strengths = ["searches all local collections", "personal documents", "offline ac
weaknesses = ["may return too many results", "requires indexing"]
requires_llm = true
+[semantic_scholar]
+module_path = "local_deep_research.web_search_engines.engines.search_engine_semantic_scholar"
+class_name = "SemanticScholarSearchEngine"
+requires_api_key = false
+api_key_env = "S2_API_KEY"
+reliability = 0.95
+strengths = [
+ "comprehensive scientific literature",
+ "extensive citation network",
+ "AI-generated summaries (TLDRs)",
+ "academic paper metadata",
+ "cross-disciplinary coverage",
+ "200M+ papers across all fields",
+ "usable without API key"
+]
+weaknesses = [
+ "rate limited (1000 requests/day) without API key",
+ "limited to academic content"
+]
+supports_full_search = true
+requires_llm = false
+
+[semantic_scholar.default_params]
+max_results = 20
+get_abstracts = true
+get_tldr = true
+get_references = false
+get_citations = false
+get_embeddings = false
+citation_limit = 10
+reference_limit = 10
+optimize_queries = true
+max_retries = 5
+retry_backoff_factor = 1.0
+
# Default search engine to use if none specified
DEFAULT_SEARCH_ENGINE = "wikipedia"
+
+
+
+
# Additional search engines can be added below
# Uncomment and modify these templates as needed
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index 3db386cc2c..ccacf89624 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -216,11 +216,12 @@ class AdvancedSearchSystem:
}
)
- if settings.general.knowledge_accumulation != KnowledgeAccumulationApproach.NO_KNOWLEDGE:
+ if settings.general.knowledge_accumulation != str(KnowledgeAccumulationApproach.NO_KNOWLEDGE.value):
current_knowledge = current_knowledge + "\n\n\n New: \n" + results_with_links
- print(current_knowledge)
- if settings.general.knowledge_accumulation == KnowledgeAccumulationApproach.QUESTION:
+ logger.info(settings.general.knowledge_accumulation)
+ if settings.general.knowledge_accumulation == str(KnowledgeAccumulationApproach.QUESTION.value):
+ logger.info("Compressing knowledge")
self._update_progress(f"Compress Knowledge for: {question}",
int(question_progress_base + 0),
{"phase": "analysis"})
@@ -240,10 +241,14 @@ class AdvancedSearchSystem:
self._update_progress(f"Compressing knowledge after iteration {iteration}",
int((iteration / total_iterations) * 100 - 5),
{"phase": "knowledge_compression"})
-
- if settings.general.knowledge_accumulation == KnowledgeAccumulationApproach.ITERATION:
+ logger.info(str(iteration))
+ logger.info(settings.general.knowledge_accumulation)
+ logger.info(str(KnowledgeAccumulationApproach.ITERATION.value))
+ if settings.general.knowledge_accumulation == KnowledgeAccumulationApproach.ITERATION.value:
try:
+ logger.info("ITERATION - Compressing Knowledge")
current_knowledge = self._compress_knowledge(current_knowledge , query, section_links)
+ logger.info("FINISHED ITERATION - Compressing Knowledge")
except Exception as e:
error_msg = f"Error compressing knowledge: {str(e)}"
print(f"COMPRESSION ERROR: {error_msg}")
@@ -278,6 +283,7 @@ class AdvancedSearchSystem:
}
def _save_findings(self, findings: List[Dict], current_knowledge: str, query: str):
+ logger.info("Saving findings ...")
self._update_progress("Saving research findings...", None)
formatted_findings = format_findings_to_text(
@@ -287,15 +293,15 @@ class AdvancedSearchSystem:
:50
]
safe_query = safe_query.replace(" ", "_").lower()
-
- output_dir = "research_outputs"
+ import local_deep_research.config as conf
+ output_dir = f"{conf.get_config_dir()}/research_outputs"
if not os.path.exists(output_dir):
os.makedirs(output_dir)
-
+
filename = os.path.join(output_dir, f"formatted_output_{safe_query}.txt")
with open(filename, "w", encoding="utf-8") as text_file:
text_file.write(formatted_findings)
-
+ logger.info("Saved findings")
self._update_progress("Research findings saved", None, {"filename": filename})
return formatted_findings
\ No newline at end of file
diff --git a/src/local_deep_research/utilties/enums.py b/src/local_deep_research/utilties/enums.py
index e082679096..01eaffcf4b 100644
--- a/src/local_deep_research/utilties/enums.py
+++ b/src/local_deep_research/utilties/enums.py
@@ -2,8 +2,8 @@
from enum import Enum, auto
class KnowledgeAccumulationApproach(Enum):
- QUESTION = auto()
- ITERATION = auto()
- NO_KNOWLEDGE = auto()
- MAX_NR_OF_CHARACTERS = auto()
+ QUESTION = "QUESTION"
+ ITERATION = "ITERATION"
+ NO_KNOWLEDGE = "NO_KNOWLEDGE"
+ MAX_NR_OF_CHARACTERS = "MAX_NR_OF_CHARACTERS"
diff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.py
index ee37eb6542..7d85c79ddc 100644
--- a/src/local_deep_research/web/app.py
+++ b/src/local_deep_research/web/app.py
@@ -1009,14 +1009,15 @@ def run_research_process(research_id, query, mode):
# Check if formatted_findings exists in results
if 'formatted_findings' not in results:
- print("WARNING: 'formatted_findings' not found in results, using fallback")
+ logger.info("WARNING: 'formatted_findings' not found in results, using fallback")
# Create fallback formatted findings from available data
raw_formatted_findings = "# Research Findings\n\n"
+ raw_formatted_findings = raw_formatted_findings + str(results.get('current_knowledge'))
for i, finding in enumerate(results.get('findings', [])):
raw_formatted_findings += f"## Finding {i+1}\n\n{finding.get('content', '')}\n\n"
else:
raw_formatted_findings = results['formatted_findings']
- print(f"Found formatted_findings of length: {len(str(raw_formatted_findings))}")
+ logger.info(f"Found formatted_findings of length: {len(str(raw_formatted_findings))}")
try:
# ADDED CODE: Convert debug output to clean markdown
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
index b1b3310923..a2a5c1011c 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
@@ -32,11 +32,9 @@ class ArXivSearchEngine(BaseSearchEngine):
llm: Language model for relevance filtering
max_filtered_results: Maximum number of results to keep after filtering
"""
- # Initialize the BaseSearchEngine with the LLM and max_filtered_results
- super().__init__(llm=llm, max_filtered_results=max_filtered_results)
-
- #max_results = min(max_results, 20) # required for arxiv
- self.max_results = 20 # TODO this needs to be corrected.
+ # Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
+ super().__init__(llm=llm, max_filtered_results=max_filtered_results, max_results=max_results)
+ self.max_results=max(self.max_results,25)
self.sort_by = sort_by
self.sort_order = sort_order
self.include_full_text = include_full_text
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_brave.py b/src/local_deep_research/web_search_engines/engines/search_engine_brave.py
index 21dd068cb2..1bf8e54940 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_brave.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_brave.py
@@ -19,7 +19,7 @@ class BraveSearchEngine(BaseSearchEngine):
api_key: Optional[str] = None,
language_code_mapping: Optional[Dict[str, str]] = None,
llm: Optional[BaseLLM] = None,
- include_full_content: bool = False,
+ include_full_content: bool = True,
max_filtered_results: Optional[int] = None,
**kwargs):
"""
@@ -38,10 +38,8 @@ class BraveSearchEngine(BaseSearchEngine):
max_filtered_results: Maximum number of results to keep after filtering
**kwargs: Additional parameters (ignored but accepted for compatibility)
"""
- # Initialize the BaseSearchEngine with the LLM and max_filtered_results
- super().__init__(llm=llm, max_filtered_results=max_filtered_results)
-
- self.max_results = max_results
+ # Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
+ super().__init__(llm=llm, max_filtered_results=max_filtered_results, max_results=max_results)
self.include_full_content = include_full_content
# Set up language code mapping
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py b/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py
index 806174ec06..6975058c2a 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py
@@ -14,7 +14,8 @@ class DuckDuckGoSearchEngine(BaseSearchEngine):
safe_search: bool = True,
llm: Optional[BaseLLM] = None,
language: str = "English",
- include_full_content: bool = False):
+ include_full_content: bool = False,
+ max_filtered_results=5):
"""
Initialize the DuckDuckGo search engine.
@@ -26,8 +27,8 @@ class DuckDuckGoSearchEngine(BaseSearchEngine):
language: Language for content processing
include_full_content: Whether to include full webpage content in results
"""
- super().__init__(llm=llm)
- self.max_results = max_results
+ # Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
+ super().__init__(llm=llm, max_filtered_results=max_filtered_results, max_results=max_results)
self.region = region
self.safe_search = safe_search
self.language = language
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_github.py b/src/local_deep_research/web_search_engines/engines/search_engine_github.py
index 01477acab4..6205cc5fbe 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_github.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_github.py
@@ -39,10 +39,8 @@ class GitHubSearchEngine(BaseSearchEngine):
llm: Language model for relevance filtering
max_filtered_results: Maximum number of results to keep after filtering
"""
- # Initialize the BaseSearchEngine with the LLM and max_filtered_results
- super().__init__(llm=llm, max_filtered_results=max_filtered_results)
-
- self.max_results = max_results
+ # Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
+ super().__init__(llm=llm, max_filtered_results=max_filtered_results, max_results=max_results)
self.api_key = api_key or os.getenv("GITHUB_API_KEY")
self.search_type = search_type
self.include_readme = include_readme
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py b/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py
index e033b10aff..09305fd5c4 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py
@@ -47,10 +47,8 @@ class GooglePSESearchEngine(BaseSearchEngine):
retry_delay: Base delay in seconds between retry attempts
**kwargs: Additional parameters (ignored but accepted for compatibility)
"""
- # Initialize the BaseSearchEngine with the LLM and max_filtered_results
- super().__init__(llm=llm, max_filtered_results=max_filtered_results)
-
- self.max_results = max_results
+ # Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
+ super().__init__(llm=llm, max_filtered_results=max_filtered_results, max_results=max_results)
self.include_full_content = include_full_content
# Retry configuration
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py b/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py
index f0c9200977..26b266787b 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py
@@ -1,15 +1,20 @@
import requests
-from typing import Dict, List, Any, Optional
+import logging
+from typing import Dict, List, Any, Optional, Tuple
import os
from datetime import datetime, timedelta
from langchain_core.language_models import BaseLLM
from local_deep_research.web_search_engines.search_engine_base import BaseSearchEngine
from local_deep_research import config
+from local_deep_research.utilties.search_utilities import remove_think_tags
+# Setup logging
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)
class GuardianSearchEngine(BaseSearchEngine):
- """The Guardian API search engine implementation"""
+ """Enhanced Guardian API search engine implementation with LLM query optimization"""
def __init__(self,
max_results: int = 10,
@@ -18,9 +23,12 @@ class GuardianSearchEngine(BaseSearchEngine):
to_date: Optional[str] = None,
section: Optional[str] = None,
order_by: str = "relevance",
- llm: Optional[BaseLLM] = None):
+ llm: Optional[BaseLLM] = None,
+ max_filtered_results: Optional[int] = None,
+ optimize_queries: bool = True,
+ adaptive_search: bool = True):
"""
- Initialize The Guardian search engine.
+ Initialize The Guardian search engine with enhanced features.
Args:
max_results: Maximum number of search results
@@ -29,13 +37,16 @@ class GuardianSearchEngine(BaseSearchEngine):
to_date: End date for search (YYYY-MM-DD format, default today)
section: Filter by section (e.g., "politics", "technology", "sport")
order_by: Sort order ("relevance", "newest", "oldest")
- llm: Language model for relevance filtering
+ llm: Language model for relevance filtering and query optimization
+ max_filtered_results: Maximum number of results to keep after filtering
+ optimize_queries: Whether to optimize queries using LLM
+ adaptive_search: Whether to use adaptive search (adjusting date ranges)
"""
- # Initialize the BaseSearchEngine with the LLM
- super().__init__(llm=llm)
-
- self.max_results = max_results
+ # Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
+ super().__init__(llm=llm, max_filtered_results=max_filtered_results, max_results=max_results)
self.api_key = api_key or os.getenv("GUARDIAN_API_KEY")
+ self.optimize_queries = optimize_queries
+ self.adaptive_search = adaptive_search
if not self.api_key:
raise ValueError("Guardian API key not found. Please provide api_key or set the GUARDIAN_API_KEY environment variable.")
@@ -56,10 +67,203 @@ class GuardianSearchEngine(BaseSearchEngine):
self.section = section
self.order_by = order_by
+ self._original_date_params = {
+ "from_date": self.from_date,
+ "to_date": self.to_date
+ }
# API base URL
self.api_url = "https://content.guardianapis.com/search"
+ def _optimize_query_for_guardian(self, query: str) -> str:
+ """
+ Optimize a natural language query for Guardian search.
+ Uses LLM to transform questions into effective news search queries.
+
+ Args:
+ query: Natural language query
+
+ Returns:
+ Optimized query string for Guardian
+ """
+ # Handle extremely long queries by truncating first
+ if len(query) > 150:
+ simple_query = " ".join(query.split()[:10])
+ logger.info(f"Query too long ({len(query)} chars), truncating to: {simple_query}")
+ query = simple_query
+
+ if not self.llm or not self.optimize_queries:
+ # Return original query if no LLM available or optimization disabled
+ return query
+
+ try:
+ # Prompt for query optimization
+ prompt = f"""Transform this natural language question into a very short Guardian news search query.
+
+Original query: "{query}"
+
+CRITICAL RULES:
+1. ONLY RETURN THE EXACT SEARCH QUERY - NO EXPLANATIONS, NO COMMENTS
+2. Keep it EXTREMELY BRIEF - MAXIMUM 3-4 words total
+3. Focus only on the main topic/person/event
+4. Include proper names when relevant
+5. Remove ALL unnecessary words
+6. DO NOT use Boolean operators (no AND/OR)
+7. DO NOT use quotes
+
+EXAMPLE CONVERSIONS:
+✓ "What's the impact of rising interest rates on UK housing market?" → "UK housing rates"
+✓ "Latest developments in the Ukraine-Russia peace negotiations" → "Ukraine Russia negotiations"
+✓ "How are tech companies responding to AI regulation?" → "tech AI regulation"
+✓ "What is Donald Trump's current political activity?" → "Trump political activity"
+
+Return ONLY the extremely brief search query.
+"""
+
+ # Get response from LLM
+ response = self.llm.invoke(prompt)
+ optimized_query = remove_think_tags(response.content).strip()
+
+ # Clean up the query - remove any explanations
+ lines = optimized_query.split('\n')
+ for line in lines:
+ line = line.strip()
+ if line and not line.lower().startswith(('here', 'i would', 'the best', 'this query')):
+ optimized_query = line
+ break
+
+ # Remove any quotes that wrap the entire query
+ if optimized_query.startswith('"') and optimized_query.endswith('"') and optimized_query.count('"') == 2:
+ optimized_query = optimized_query[1:-1]
+
+ logger.info(f"Original query: '{query}'")
+ logger.info(f"Optimized for Guardian: '{optimized_query}'")
+
+ return optimized_query
+
+ except Exception as e:
+ logger.error(f"Error optimizing query: {e}")
+ return query # Fall back to original query on error
+
+ def _adapt_dates_for_query_type(self, query: str) -> None:
+ """
+ Adapt date range based on query type (historical vs current).
+
+ Args:
+ query: The search query
+ """
+ # Fast path - for very short queries, default to recent news
+ if len(query.split()) <= 4:
+ logger.info("Short query detected, defaulting to recent news")
+ # Default to 60 days for short queries
+ recent = (datetime.now() - timedelta(days=60)).strftime("%Y-%m-%d")
+ self.from_date = recent
+ self.order_by = "newest"
+ return
+
+ if not self.llm or not self.adaptive_search:
+ return
+
+ try:
+ prompt = f"""Is this query asking about HISTORICAL events or CURRENT events?
+
+Query: "{query}"
+
+ONE WORD ANSWER ONLY:
+- "HISTORICAL" if about past events (older than 1 year)
+- "CURRENT" if about recent events (within past year)
+- "UNCLEAR" if can't determine
+
+ONE WORD ONLY:"""
+
+ response = self.llm.invoke(prompt)
+ answer = remove_think_tags(response.content).strip().upper()
+
+ # Reset to original parameters first
+ self.from_date = self._original_date_params["from_date"]
+ self.to_date = self._original_date_params["to_date"]
+
+ if "HISTORICAL" in answer:
+ # For historical queries, go back 10 years
+ logger.info("Query classified as HISTORICAL - extending search timeframe")
+ ten_years_ago = (datetime.now() - timedelta(days=3650)).strftime("%Y-%m-%d")
+ self.from_date = ten_years_ago
+
+ elif "CURRENT" in answer:
+ # For current events, focus on recent content
+ logger.info("Query classified as CURRENT - focusing on recent content")
+ recent = (datetime.now() - timedelta(days=60)).strftime("%Y-%m-%d")
+ self.from_date = recent
+ self.order_by = "newest" # Prioritize newest for current events
+
+ except Exception as e:
+ logger.error(f"Error adapting dates for query type: {e}")
+ # Keep original date parameters on error
+
+ def _adaptive_search(self, query: str) -> Tuple[List[Dict[str, Any]], str]:
+ """
+ Perform adaptive search that progressively adjusts parameters based on results.
+
+ Args:
+ query: The search query
+
+ Returns:
+ Tuple of (list of articles, search strategy used)
+ """
+ # Try with current parameters
+ articles = self._get_all_data(query)
+ strategy = "initial"
+
+ # If no results or too few, try different strategies
+ if len(articles) < 3 and self.adaptive_search:
+ logger.info(f"Initial search found only {len(articles)} results, trying alternative strategies")
+
+ # Try with expanded date range
+ original_from_date = self.from_date
+ original_order_by = self.order_by
+
+ # Strategy 1: Expand to 6 months
+ logger.info("Strategy 1: Expanding time range to 6 months")
+ six_months_ago = (datetime.now() - timedelta(days=180)).strftime("%Y-%m-%d")
+ self.from_date = six_months_ago
+
+ articles1 = self._get_all_data(query)
+ if len(articles1) > len(articles):
+ articles = articles1
+ strategy = "expanded_6mo"
+
+ # Strategy 2: Expand to all time and try relevance order
+ if len(articles) < 3:
+ logger.info("Strategy 2: Expanding to all time with relevance ordering")
+ self.from_date = "2000-01-01" # Effectively "all time"
+ self.order_by = "relevance"
+
+ articles2 = self._get_all_data(query)
+ if len(articles2) > len(articles):
+ articles = articles2
+ strategy = "all_time_relevance"
+
+ # Strategy 3: Try removing section constraints
+ if len(articles) < 3 and self.section:
+ logger.info("Strategy 3: Removing section constraint")
+ original_section = self.section
+ self.section = None
+
+ articles3 = self._get_all_data(query)
+ if len(articles3) > len(articles):
+ articles = articles3
+ strategy = "no_section"
+
+ # Restore section setting
+ self.section = original_section
+
+ # Restore original settings
+ self.from_date = original_from_date
+ self.order_by = original_order_by
+
+ logger.info(f"Adaptive search using strategy '{strategy}' found {len(articles)} results")
+ return articles, strategy
+
def _get_all_data(self, query: str) -> List[Dict[str, Any]]:
"""
Get all article data from The Guardian API in a single call.
@@ -72,14 +276,31 @@ class GuardianSearchEngine(BaseSearchEngine):
List of articles with all data
"""
try:
+ # Ensure query is not empty
+ if not query or query.strip() == "":
+ query = "news"
+ logger.warning("Empty query provided, using 'news' as default")
+
+ # Ensure query is not too long for API
+ if len(query) > 100:
+ logger.warning(f"Query too long for Guardian API ({len(query)} chars), truncating")
+ query = query[:100]
+
# Always request all fields for simplicity
+ # Ensure max_results is an integer to avoid comparison errors
+ page_size = min(int(self.max_results) if self.max_results is not None else 10, 50)
+
+ # Log full parameters for debugging
+ logger.info(f"Guardian API search query: '{query}'")
+ logger.info(f"Guardian API date range: {self.from_date} to {self.to_date}")
+
params = {
"q": query,
"api-key": self.api_key,
"from-date": self.from_date,
"to-date": self.to_date,
"order-by": self.order_by,
- "page-size": min(self.max_results, 50), # API maximum is 50
+ "page-size": page_size, # API maximum is 50
"show-fields": "headline,trailText,byline,body,publication",
"show-tags": "keyword"
}
@@ -88,6 +309,11 @@ class GuardianSearchEngine(BaseSearchEngine):
if self.section:
params["section"] = self.section
+ # Log the complete request parameters (except API key)
+ log_params = params.copy()
+ log_params["api-key"] = "REDACTED"
+ logger.info(f"Guardian API request parameters: {log_params}")
+
# Execute the API request
response = requests.get(self.api_url, params=params)
response.raise_for_status()
@@ -96,6 +322,7 @@ class GuardianSearchEngine(BaseSearchEngine):
# Extract results from the response
articles = data.get("response", {}).get("results", [])
+ logger.info(f"Guardian API returned {len(articles)} articles")
# Format results to include all data
formatted_articles = []
@@ -127,13 +354,12 @@ class GuardianSearchEngine(BaseSearchEngine):
return formatted_articles
except Exception as e:
- print(f"Error getting data from The Guardian API: {e}")
+ logger.error(f"Error getting data from The Guardian API: {e}")
return []
def _get_previews(self, query: str) -> List[Dict[str, Any]]:
"""
- Get preview information for Guardian articles.
- Actually gets all data but returns only preview fields.
+ Get preview information for Guardian articles with enhanced optimization.
Args:
query: The search query
@@ -141,12 +367,29 @@ class GuardianSearchEngine(BaseSearchEngine):
Returns:
List of preview dictionaries
"""
- print("Getting articles from The Guardian API")
+ logger.info(f"Getting articles from The Guardian API for query: {query}")
- # Get all article data
- articles = self._get_all_data(query)
+ # Step 1: Optimize the query using LLM
+ optimized_query = self._optimize_query_for_guardian(query)
+
+ # Step 2: Adapt date parameters based on query type
+ self._adapt_dates_for_query_type(optimized_query)
+
+ # Step 3: Perform adaptive search
+ articles, strategy = self._adaptive_search(optimized_query)
- # Store full articles for later use (implementation detail)
+ # Store search metadata for debugging
+ self._search_metadata = {
+ "original_query": query,
+ "optimized_query": optimized_query,
+ "strategy": strategy,
+ "from_date": self.from_date,
+ "to_date": self.to_date,
+ "section": self.section,
+ "order_by": self.order_by
+ }
+
+ # Store full articles for later use
self._full_articles = {a["id"]: a for a in articles}
# Return only preview fields for each article
@@ -177,7 +420,7 @@ class GuardianSearchEngine(BaseSearchEngine):
Returns:
List of result dictionaries with full content
"""
- print("Adding full content to relevant Guardian articles")
+ logger.info(f"Adding full content to {len(relevant_items)} relevant Guardian articles")
# Check if we should add full content
if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:
@@ -199,7 +442,7 @@ class GuardianSearchEngine(BaseSearchEngine):
def run(self, query: str) -> List[Dict[str, Any]]:
"""
- Execute a search using The Guardian API with the two-phase approach.
+ Execute a search using The Guardian API with the enhanced approach.
Args:
query: The search query
@@ -207,75 +450,77 @@ class GuardianSearchEngine(BaseSearchEngine):
Returns:
List of search results
"""
- print("---Execute a search using The Guardian---")
+ logger.info(f"---Execute a search using The Guardian (enhanced)---")
- # Use the implementation from the parent class which handles all phases
- results = super().run(query)
+ # Additional safety check for None query
+ if query is None:
+ logger.error("None query passed to Guardian search engine")
+ query = "news"
- # Clean up the cache after use
- if hasattr(self, '_full_articles'):
- del self._full_articles
+ try:
+ # Get previews with our enhanced method
+ previews = self._get_previews(query)
- return results
-
- def get_article_by_id(self, article_id: str) -> Dict[str, Any]:
- """
- Get a specific article by its ID.
-
- Args:
- article_id: The Guardian article ID
+ # If no results, try one more time with a simplified query
+ if not previews:
+ simple_query = " ".join([w for w in query.split() if len(w) > 3][:3])
+ logger.warning(f"No Guardian articles found, trying simplified query: {simple_query}")
+ previews = self._get_previews(simple_query)
+
+ # If still no results, try with a very generic query as last resort
+ if not previews and "trump" in query.lower():
+ logger.warning("Trying last resort query: 'Donald Trump'")
+ previews = self._get_previews("Donald Trump")
+ elif not previews:
+ logger.warning("Trying last resort query: 'news'")
+ previews = self._get_previews("news")
- Returns:
- Dictionary with article information
- """
- try:
- # Guardian article API URL
- url = f"https://content.guardianapis.com/{article_id}"
-
- # Always request all fields
- response = requests.get(
- url,
- params={
- "api-key": self.api_key,
- "show-fields": "headline,trailText,body,byline,publication",
- "show-tags": "keyword"
- }
- )
- response.raise_for_status()
+ # If still no results after all attempts, return empty list
+ if not previews:
+ logger.warning(f"No Guardian articles found after multiple attempts")
+ return []
- data = response.json()
- article = data.get("response", {}).get("content", {})
+ # Filter for relevance if we have an LLM
+ if self.llm and hasattr(self, 'max_filtered_results') and self.max_filtered_results:
+ filtered_items = self._filter_for_relevance(previews, query)
+ if not filtered_items:
+ # Fall back to unfiltered results if everything was filtered out
+ logger.warning("All articles filtered out, using unfiltered results")
+ filtered_items = previews[:self.max_filtered_results]
+ else:
+ filtered_items = previews
- if not article:
- return {}
-
- fields = article.get("fields", {})
-
- # Format the article with all fields
- result = {
- "id": article_id,
- "title": fields.get("headline", article.get("webTitle", "")),
- "link": article.get("webUrl", ""),
- "snippet": fields.get("trailText", ""),
- "publication_date": article.get("webPublicationDate", ""),
- "section": article.get("sectionName", ""),
- "author": fields.get("byline", "")
- }
+ # Get full content for relevant items
+ results = self._get_full_content(filtered_items)
- # Only include full content if not in snippet-only mode
- if not hasattr(config, 'SEARCH_SNIPPETS_ONLY') or not config.SEARCH_SNIPPETS_ONLY:
- result["content"] = fields.get("body", "")
- result["full_content"] = fields.get("body", "")
+ # Add source information to make it clear these are from The Guardian
+ for result in results:
+ if "source" not in result:
+ result["source"] = "The Guardian"
- # Extract tags/keywords
- tags = article.get("tags", [])
- result["keywords"] = [tag.get("webTitle", "") for tag in tags if tag.get("type") == "keyword"]
+ # Clean up the cache after use
+ if hasattr(self, '_full_articles'):
+ del self._full_articles
+
+ # Restore original date parameters
+ self.from_date = self._original_date_params["from_date"]
+ self.to_date = self._original_date_params["to_date"]
- return result
+ # Log search metadata if available
+ if hasattr(self, '_search_metadata'):
+ logger.info(f"Search metadata: {self._search_metadata}")
+ del self._search_metadata
+
+ return results
except Exception as e:
- print(f"Error getting article details: {e}")
- return {}
+ logger.error(f"Error in Guardian search: {e}")
+
+ # Restore original date parameters on error
+ self.from_date = self._original_date_params["from_date"]
+ self.to_date = self._original_date_params["to_date"]
+
+ return []
def search_by_section(self, section: str, max_results: Optional[int] = None) -> List[Dict[str, Any]]:
"""
@@ -283,7 +528,7 @@ class GuardianSearchEngine(BaseSearchEngine):
Args:
section: The Guardian section name (e.g., "politics", "technology")
- max_results: Maximum number of search results (defaults to self.max_results)
+ max_results: Maximum number of results (defaults to self.max_results)
Returns:
List of articles in the section
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_local_all.py b/src/local_deep_research/web_search_engines/engines/search_engine_local_all.py
index 256c5a2a3e..da49c0902a 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_local_all.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_local_all.py
@@ -35,11 +35,9 @@ class LocalAllSearchEngine(BaseSearchEngine):
max_filtered_results: Maximum results after filtering
**kwargs: Additional parameters passed to LocalSearchEngine instances
"""
- # Initialize the base search engine
- super().__init__(llm=llm, max_filtered_results=max_filtered_results)
-
- self.max_results = max_results
-
+ # Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
+ super().__init__(llm=llm, max_filtered_results=max_filtered_results, max_results=max_results)
+
# Find all local collection search engines
self.local_engines = {}
try:
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py
index 45f693eacd..adf6351a10 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py
@@ -44,10 +44,9 @@ class PubMedSearchEngine(BaseSearchEngine):
max_filtered_results: Maximum number of results to keep after filtering
optimize_queries: Whether to optimize natural language queries for PubMed
"""
- # Initialize the BaseSearchEngine with the LLM and max_filtered_results
- super().__init__(llm=llm, max_filtered_results=max_filtered_results)
-
- self.max_results = max_results
+ # Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
+ super().__init__(llm=llm, max_filtered_results=max_filtered_results, max_results=max_results)
+ self.max_results=max(self.max_results,25)
self.api_key = api_key
self.days_limit = days_limit
self.get_abstracts = get_abstracts
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py
index 7104a2b8a1..2ce16218d1 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py
@@ -51,8 +51,9 @@ class SearXNGSearchEngine(BaseSearchEngine):
include_full_content: Whether to include full webpage content in results
api_key: Alternative way to provide instance URL (takes precedence over instance_url)
"""
- # Initialize the BaseSearchEngine with the LLM and max_filtered_results
- super().__init__(llm=llm, max_filtered_results=max_filtered_results)
+
+ # Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
+ super().__init__(llm=llm, max_filtered_results=max_filtered_results, max_results=max_results)
# Get instance URL from various sources in priority order:
# 1. api_key parameter (which is actually the instance URL)
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py b/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py
new file mode 100644
index 0000000000..44572af8aa
--- /dev/null
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py
@@ -0,0 +1,1128 @@
+import requests
+import logging
+import json
+from typing import Dict, List, Any, Optional, Tuple, Union
+from langchain_core.language_models import BaseLLM
+import time
+import re
+from datetime import datetime
+from requests.adapters import HTTPAdapter
+from urllib3.util import Retry
+
+from local_deep_research.web_search_engines.search_engine_base import BaseSearchEngine
+from local_deep_research import config
+
+# Setup logging
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)
+
+class SemanticScholarSearchEngine(BaseSearchEngine):
+ """
+ Semantic Scholar search engine implementation with two-phase approach.
+ Provides efficient access to scientific literature across all fields.
+ """
+
+ def __init__(self,
+ max_results: int = 10,
+ api_key: Optional[str] = None,
+ year_range: Optional[Tuple[int, int]] = None,
+ get_abstracts: bool = True,
+ get_references: bool = False,
+ get_citations: bool = False,
+ get_embeddings: bool = False,
+ get_tldr: bool = True,
+ citation_limit: int = 10,
+ reference_limit: int = 10,
+ llm: Optional[BaseLLM] = None,
+ max_filtered_results: Optional[int] = None,
+ optimize_queries: bool = True,
+ max_retries: int = 5,
+ retry_backoff_factor: float = 1.0,
+ fields_of_study: Optional[List[str]] = None,
+ publication_types: Optional[List[str]] = None):
+ """
+ Initialize the Semantic Scholar search engine.
+
+ Args:
+ max_results: Maximum number of search results
+ api_key: Semantic Scholar API key for higher rate limits (optional)
+ year_range: Optional tuple of (start_year, end_year) to filter results
+ get_abstracts: Whether to fetch abstracts for all results
+ get_references: Whether to fetch references for papers
+ get_citations: Whether to fetch citations for papers
+ get_embeddings: Whether to fetch SPECTER embeddings for papers
+ get_tldr: Whether to fetch TLDR summaries for papers
+ citation_limit: Maximum number of citations to fetch per paper
+ reference_limit: Maximum number of references to fetch per paper
+ llm: Language model for relevance filtering
+ max_filtered_results: Maximum number of results to keep after filtering
+ optimize_queries: Whether to optimize natural language queries
+ max_retries: Maximum number of retries for API requests
+ retry_backoff_factor: Backoff factor for retries
+ fields_of_study: List of fields of study to filter results
+ publication_types: List of publication types to filter results
+ """
+ # Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
+ super().__init__(llm=llm, max_filtered_results=max_filtered_results, max_results=max_results)
+ self.api_key = api_key
+ self.year_range = year_range
+ self.get_abstracts = get_abstracts
+ self.get_references = get_references
+ self.get_citations = get_citations
+ self.get_embeddings = get_embeddings
+ self.get_tldr = get_tldr
+ self.citation_limit = citation_limit
+ self.reference_limit = reference_limit
+ self.optimize_queries = optimize_queries
+ self.max_retries = max_retries
+ self.retry_backoff_factor = retry_backoff_factor
+ self.fields_of_study = fields_of_study
+ self.publication_types = publication_types
+
+ # Base API URLs
+ self.base_url = "https://api.semanticscholar.org/graph/v1"
+ self.paper_search_url = f"{self.base_url}/paper/search"
+ self.paper_bulk_search_url = f"{self.base_url}/paper/search/bulk"
+ self.paper_batch_url = f"{self.base_url}/paper/batch"
+ self.paper_details_url = f"{self.base_url}/paper"
+ self.author_search_url = f"{self.base_url}/author/search"
+ self.author_details_url = f"{self.base_url}/author"
+ self.recommendations_url = "https://api.semanticscholar.org/recommendations/v1/papers"
+ self.datasets_url = "https://api.semanticscholar.org/datasets/v1"
+
+ # Create a session with retry capabilities
+ self.session = self._create_session()
+
+ # Rate limiting
+ self.rate_limit_wait = 1.0 # Default 1 second between requests
+ self.last_request_time = 0
+
+ def _create_session(self) -> requests.Session:
+ """Create and configure a requests session with retry capabilities"""
+ session = requests.Session()
+
+ # Configure automatic retries with exponential backoff
+ retry_strategy = Retry(
+ total=self.max_retries,
+ backoff_factor=self.retry_backoff_factor,
+ status_forcelist=[429, 500, 502, 503, 504],
+ allowed_methods={"HEAD", "GET", "POST", "OPTIONS"}
+ )
+
+ adapter = HTTPAdapter(max_retries=retry_strategy)
+ session.mount("https://", adapter)
+
+ # Set up headers
+ headers = {"Accept": "application/json"}
+ if self.api_key:
+ headers["x-api-key"] = self.api_key
+
+ session.headers.update(headers)
+
+ return session
+
+ def _respect_rate_limit(self):
+ """Apply rate limiting between requests"""
+ current_time = time.time()
+ elapsed = current_time - self.last_request_time
+
+ if elapsed < self.rate_limit_wait:
+ wait_time = self.rate_limit_wait - elapsed
+ logger.debug(f"Rate limiting: waiting {wait_time:.2f}s")
+ time.sleep(wait_time)
+
+ self.last_request_time = time.time()
+
+ def _get_headers(self) -> Dict[str, str]:
+ """Get the headers for API requests"""
+ headers = {"Accept": "application/json"}
+
+ if self.api_key:
+ headers["x-api-key"] = self.api_key
+
+ return headers
+
+ def _make_request(self, url: str, params: Optional[Dict] = None, data: Optional[Dict] = None,
+ method: str = "GET") -> Dict:
+ """
+ Make a request to the Semantic Scholar API.
+
+ Args:
+ url: API endpoint URL
+ params: Query parameters
+ data: JSON data for POST requests
+ method: HTTP method (GET or POST)
+
+ Returns:
+ API response as dictionary
+ """
+ self._respect_rate_limit()
+
+ try:
+ if method.upper() == "GET":
+ response = self.session.get(url, params=params, timeout=30)
+ elif method.upper() == "POST":
+ response = self.session.post(url, params=params, json=data, timeout=30)
+ else:
+ raise ValueError(f"Unsupported HTTP method: {method}")
+
+ # Handle rate limiting manually if retry strategy fails
+ if response.status_code == 429:
+ logger.warning("Rate limit exceeded, waiting and retrying...")
+ time.sleep(2.0) # Wait longer on rate limit
+ self.rate_limit_wait *= 1.5 # Increase wait time for future requests
+ return self._make_request(url, params, data, method) # Retry
+
+ response.raise_for_status()
+ return response.json()
+ except requests.RequestException as e:
+ logger.error(f"API request failed: {e}")
+ return {}
+
+ def _optimize_query(self, query: str) -> str:
+ """
+ Optimize a natural language query for Semantic Scholar search.
+ If LLM is available, uses it to extract key terms and concepts.
+
+ Args:
+ query: Natural language query
+
+ Returns:
+ Optimized query string
+ """
+ if not self.llm or not self.optimize_queries:
+ return query
+
+ try:
+ prompt = f"""Transform this natural language question into an optimized academic search query.
+
+Original query: "{query}"
+
+INSTRUCTIONS:
+1. Extract key academic concepts, technical terms, and proper nouns
+2. Remove generic words, filler words, and non-technical terms
+3. Add quotation marks around specific phrases that should be kept together
+4. Return ONLY the optimized search query with no explanation
+5. Keep it under 100 characters if possible
+
+EXAMPLE TRANSFORMATIONS:
+"What are the latest findings about mRNA vaccines and COVID-19?" → "mRNA vaccines COVID-19 recent findings"
+"How does machine learning impact climate change prediction?" → "machine learning "climate change" prediction"
+"Tell me about quantum computing approaches for encryption" → "quantum computing encryption"
+
+Return ONLY the optimized search query with no explanation.
+"""
+
+ response = self.llm.invoke(prompt)
+ optimized_query = response.content.strip()
+
+ # Clean up the query - remove any explanations
+ lines = optimized_query.split('\n')
+ optimized_query = lines[0].strip()
+
+ # Safety check - if query looks too much like an explanation, use original
+ if len(optimized_query.split()) > 15 or ":" in optimized_query:
+ logger.warning("Query optimization result looks too verbose, using original")
+ return query
+
+ logger.info(f"Original query: '{query}'")
+ logger.info(f"Optimized for Semantic Scholar: '{optimized_query}'")
+
+ return optimized_query
+ except Exception as e:
+ logger.error(f"Error optimizing query: {e}")
+ return query # Fall back to original query on error
+
+ def _search_papers(self, query: str) -> List[Dict[str, Any]]:
+ """
+ Search for papers matching the query.
+
+ Args:
+ query: The search query
+
+ Returns:
+ List of paper dictionaries
+ """
+ try:
+ fields = [
+ "paperId",
+ "externalIds",
+ "url",
+ "title",
+ "abstract",
+ "venue",
+ "year",
+ "authors"
+ ]
+
+ if self.get_tldr:
+ fields.append("tldr")
+
+ params = {
+ "query": query,
+ "limit": min(self.max_results, 100), # Regular search API can return up to 100 results
+ "fields": ",".join(fields)
+ }
+
+ # Add year filter if specified
+ if self.year_range:
+ start_year, end_year = self.year_range
+ params["year"] = f"{start_year}-{end_year}"
+
+ # Add fields of study filter if specified
+ if self.fields_of_study:
+ params["fieldsOfStudy"] = ",".join(self.fields_of_study)
+
+ # Add publication types filter if specified
+ if self.publication_types:
+ params["publicationTypes"] = ",".join(self.publication_types)
+
+ response = self._make_request(self.paper_search_url, params)
+
+ if "data" in response:
+ papers = response["data"]
+ logger.info(f"Found {len(papers)} papers matching query: '{query}'")
+ return papers
+ else:
+ logger.warning(f"No data in response for query: '{query}'")
+ return []
+
+ except Exception as e:
+ logger.error(f"Error searching papers: {e}")
+ return []
+
+ def _search_papers_bulk(self, query: str, limit: int = 1000) -> List[Dict[str, Any]]:
+ """
+ Search for papers using the bulk search API, which can return up to 1000 papers.
+
+ Args:
+ query: The search query
+ limit: Maximum number of results (up to 1000)
+
+ Returns:
+ List of paper dictionaries
+ """
+ try:
+ fields = [
+ "paperId",
+ "externalIds",
+ "url",
+ "title",
+ "abstract",
+ "venue",
+ "year",
+ "authors",
+ "fieldsOfStudy"
+ ]
+
+ if self.get_tldr:
+ fields.append("tldr")
+
+ params = {
+ "query": query,
+ "limit": min(limit, 1000), # Bulk search API can return up to 1000 results
+ "fields": ",".join(fields)
+ }
+
+ # Add year filter if specified
+ if self.year_range:
+ start_year, end_year = self.year_range
+ params["year"] = f"{start_year}-{end_year}"
+
+ # Add fields of study filter if specified
+ if self.fields_of_study:
+ params["fieldsOfStudy"] = ",".join(self.fields_of_study)
+
+ # Add publication types filter if specified
+ if self.publication_types:
+ params["publicationTypes"] = ",".join(self.publication_types)
+
+ response = self._make_request(self.paper_bulk_search_url, params)
+
+ if "data" in response:
+ papers = response["data"]
+ logger.info(f"Found {len(papers)} papers using bulk search for query: '{query}'")
+ total_count = response.get("total", 0)
+ logger.info(f"Total available results: {total_count}")
+
+ # Handle continuation token for pagination if needed
+ if "token" in response and len(papers) < min(total_count, limit):
+ token = response["token"]
+ logger.info(f"Continuation token available: {token}")
+ # The caller would need to handle continuation tokens for pagination
+
+ return papers
+ else:
+ logger.warning(f"No data in response for bulk query: '{query}'")
+ return []
+
+ except Exception as e:
+ logger.error(f"Error in bulk paper search: {e}")
+ return []
+
+ def _get_paper_details(self, paper_id: str) -> Dict[str, Any]:
+ """
+ Get detailed information about a specific paper.
+
+ Args:
+ paper_id: Semantic Scholar Paper ID
+
+ Returns:
+ Dictionary with paper details
+ """
+ try:
+ # Construct fields parameter
+ fields = [
+ "paperId",
+ "externalIds",
+ "corpusId",
+ "url",
+ "title",
+ "abstract",
+ "venue",
+ "year",
+ "authors",
+ "fieldsOfStudy"
+ ]
+
+ if self.get_tldr:
+ fields.append("tldr")
+
+ if self.get_embeddings:
+ fields.append("embedding")
+
+ # Add citation and reference fields if requested
+ if self.get_citations:
+ fields.append(f"citations.limit({self.citation_limit})")
+
+ if self.get_references:
+ fields.append(f"references.limit({self.reference_limit})")
+
+ # Make the request
+ url = f"{self.paper_details_url}/{paper_id}"
+ params = {"fields": ",".join(fields)}
+
+ return self._make_request(url, params)
+
+ except Exception as e:
+ logger.error(f"Error getting paper details for {paper_id}: {e}")
+ return {}
+
+
+ def _adaptive_search(self, query: str) -> Tuple[List[Dict[str, Any]], str]:
+ """
+ Perform an adaptive search that adjusts based on result volume.
+ Uses LLM to generate better fallback queries when available.
+
+ Args:
+ query: The search query (already optimized)
+
+ Returns:
+ Tuple of (list of paper results, search strategy used)
+ """
+ # Start with a standard search
+ papers = self._search_papers(query)
+ strategy = "standard"
+
+ # If no results, try different variations
+ if not papers:
+ # Try removing quotes to broaden search
+ if '"' in query:
+ unquoted_query = query.replace('"', '')
+ logger.info(f"No results with quoted terms, trying without quotes: {unquoted_query}")
+ papers = self._search_papers(unquoted_query)
+
+ if papers:
+ strategy = "unquoted"
+ return papers, strategy
+
+ # If LLM is available, use it to generate better fallback queries
+ if self.llm:
+ try:
+ # Generate alternate search queries focusing on core concepts
+ prompt = f"""You are helping refine a search query for academic papers related to cancer research that returned no results.
+
+ Original query: "{query}"
+
+ The query might be too specific, contain future dates, or use natural language phrasing that doesn't match academic paper keywords.
+
+ Please provide THREE alternative search queries that:
+ 1. Focus on the core academic concepts about cancer treatment, research, or therapies
+ 2. Remove future dates or references to "latest" or "current" (replace with terms like "recent" or "novel")
+ 3. Use precise medical/scientific terminology commonly found in academic papers
+ 4. Break down complex queries into more searchable components
+ 5. Format each as a concise keyword-focused search term (not a natural language question)
+
+ Format each query on a new line with no numbering or explanation. Keep each query under 8 words and very focused.
+ """
+ # Get the LLM's response
+ response = self.llm.invoke(prompt)
+
+ # Extract the alternative queries
+ alt_queries = []
+ if hasattr(response, 'content'): # Handle various LLM response formats
+ content = response.content
+ alt_queries = [q.strip() for q in content.strip().split('\n') if q.strip()]
+ elif isinstance(response, str):
+ alt_queries = [q.strip() for q in response.strip().split('\n') if q.strip()]
+
+ # Try each alternative query
+ for alt_query in alt_queries[:3]: # Limit to first 3 alternatives
+ logger.info(f"Trying LLM-suggested query: {alt_query}")
+ alt_papers = self._search_papers(alt_query)
+
+ if alt_papers:
+ logger.info(f"Found {len(alt_papers)} papers using LLM-suggested query: {alt_query}")
+ strategy = "llm_alternative"
+ return alt_papers, strategy
+ except Exception as e:
+ logger.error(f"Error using LLM for query refinement: {e}")
+ # Fall through to simpler strategies
+
+ # Fallback 1: Try extracting important cancer-related terms
+ cancer_terms = ["cancer", "tumor", "oncology", "carcinoma", "sarcoma", "leukemia",
+ "lymphoma", "metastasis", "therapy", "immunotherapy", "targeted",
+ "treatment", "drug", "clinical", "trial", "biomarker"]
+
+ words = re.findall(r'\b\w+\b', query.lower())
+ important_terms = [word for word in words if word in cancer_terms or len(word) > 7]
+
+ if important_terms:
+ important_query = ' '.join(important_terms[:5]) # Limit to 5 terms
+ logger.info(f"Trying with important cancer terms: {important_query}")
+ papers = self._search_papers(important_query)
+
+ if papers:
+ strategy = "cancer_terms"
+ return papers, strategy
+
+ # Fallback 2: Try with just specific cancer types or treatment modalities
+ cancer_types = ["breast", "lung", "colorectal", "prostate", "melanoma", "lymphoma",
+ "leukemia", "myeloma", "sarcoma", "glioblastoma"]
+ treatment_types = ["immunotherapy", "chemotherapy", "radiotherapy", "targeted",
+ "surgery", "vaccine", "antibody", "CAR-T", "inhibitor"]
+
+ cancer_matches = [word for word in words if word in cancer_types]
+ treatment_matches = [word for word in words if word in treatment_types]
+
+ if cancer_matches and treatment_matches:
+ specific_query = f"{cancer_matches[0]} {treatment_matches[0]}"
+ logger.info(f"Trying with specific cancer-treatment pair: {specific_query}")
+ papers = self._search_papers(specific_query)
+
+ if papers:
+ strategy = "specific_pair"
+ return papers, strategy
+
+ # Fallback 3: Extract the longest word (likely a specific term)
+ longest_word = max(re.findall(r'\w+', query), key=len, default='')
+ if len(longest_word) > 6:
+ logger.info(f"Trying with primary keyword: {longest_word}")
+ papers = self._search_papers(longest_word)
+
+ if papers:
+ strategy = "primary_keyword"
+ return papers, strategy
+
+ return papers, strategy
+
+
+ def _get_previews(self, query: str) -> List[Dict[str, Any]]:
+ """
+ Get preview information for Semantic Scholar papers.
+
+ Args:
+ query: The search query
+
+ Returns:
+ List of preview dictionaries
+ """
+ logger.info(f"Getting Semantic Scholar previews for query: {query}")
+
+ # Optimize the query if LLM is available
+ optimized_query = self._optimize_query(query)
+
+ # Perform adaptive search
+ papers, strategy = self._adaptive_search(optimized_query)
+
+ if not papers:
+ logger.warning(f"No Semantic Scholar results found using strategy: {strategy}")
+ return []
+
+ # Format as previews
+ previews = []
+ for paper in papers:
+ try:
+ # Format authors - ensure we have a valid list with string values
+ authors = []
+ if "authors" in paper and paper["authors"]:
+ authors = [author.get("name", "") for author in paper["authors"] if author and author.get("name")]
+
+ # Ensure we have valid strings for all fields
+ paper_id = paper.get("paperId", "")
+ title = paper.get("title", "")
+ url = paper.get("url", "")
+
+ # Handle abstract safely, ensuring we always have a string
+ abstract = paper.get("abstract")
+ snippet = ""
+ if abstract:
+ snippet = abstract[:250] + "..." if len(abstract) > 250 else abstract
+
+ venue = paper.get("venue", "")
+ year = paper.get("year")
+ external_ids = paper.get("externalIds", {})
+
+ # Handle TLDR safely
+ tldr_text = ""
+ if paper.get("tldr") and isinstance(paper.get("tldr"), dict):
+ tldr_text = paper.get("tldr", {}).get("text", "")
+
+ # Create preview with basic information, ensuring no None values
+ preview = {
+ "id": paper_id if paper_id else "",
+ "title": title if title else "",
+ "link": url if url else "",
+ "snippet": snippet, # Already handled above
+ "authors": authors, # List of strings, safe to use directly
+ "venue": venue if venue else "",
+ "year": year, # Can be None, handled in downstream processing
+ "external_ids": external_ids if external_ids else {},
+ "source": "Semantic Scholar",
+ "_paper_id": paper_id if paper_id else "",
+ "_search_strategy": strategy,
+ "tldr": tldr_text
+ }
+
+ # Store the full paper object for later reference
+ preview["_full_paper"] = paper
+
+ previews.append(preview)
+ except Exception as e:
+ logger.error(f"Error processing paper preview: {e}")
+ # Continue with the next paper
+
+ logger.info(f"Found {len(previews)} Semantic Scholar previews using strategy: {strategy}")
+ return previews
+
+ def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
+ """
+ Get full content for the relevant Semantic Scholar papers.
+ Gets additional details like citations, references, and full metadata.
+
+ Args:
+ relevant_items: List of relevant preview dictionaries
+
+ Returns:
+ List of result dictionaries with full content
+ """
+ # Check if we should add full content
+ if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:
+ logger.info("Snippet-only mode, skipping full content retrieval")
+ return relevant_items
+
+ logger.info(f"Getting content for {len(relevant_items)} Semantic Scholar papers")
+
+ results = []
+ for item in relevant_items:
+ result = item.copy()
+ paper_id = item.get("_paper_id", "")
+
+ # Skip if no paper ID
+ if not paper_id:
+ results.append(result)
+ continue
+
+ # Get paper details if citations or references are requested
+ if self.get_citations or self.get_references or self.get_embeddings:
+ paper_details = self._get_paper_details(paper_id)
+
+ if paper_details:
+ # Add citation information
+ if self.get_citations and "citations" in paper_details:
+ result["citations"] = paper_details["citations"]
+
+ # Add reference information
+ if self.get_references and "references" in paper_details:
+ result["references"] = paper_details["references"]
+
+ # Add embedding if available
+ if self.get_embeddings and "embedding" in paper_details:
+ result["embedding"] = paper_details["embedding"]
+
+ # Add fields of study
+ if "fieldsOfStudy" in paper_details:
+ result["fields_of_study"] = paper_details["fieldsOfStudy"]
+
+ # Remove temporary fields
+ if "_paper_id" in result:
+ del result["_paper_id"]
+ if "_search_strategy" in result:
+ del result["_search_strategy"]
+ if "_full_paper" in result:
+ del result["_full_paper"]
+
+ results.append(result)
+
+ return results
+
+ def search_by_author(self, author_name: str, max_results: Optional[int] = None) -> List[Dict[str, Any]]:
+ """
+ Search for papers by a specific author.
+
+ Args:
+ author_name: Name of the author
+ max_results: Maximum number of results (defaults to self.max_results)
+
+ Returns:
+ List of papers by the author
+ """
+ original_max_results = self.max_results
+
+ try:
+ if max_results:
+ self.max_results = max_results
+
+ # First search for the author
+ params = {
+ "query": author_name,
+ "limit": 5 # Limit to top 5 author matches
+ }
+
+ response = self._make_request(self.author_search_url, params)
+
+ if "data" not in response or not response["data"]:
+ logger.warning(f"No authors found matching: {author_name}")
+ return []
+
+ # Use the first (best) author match
+ author = response["data"][0]
+ author_id = author.get("authorId")
+
+ if not author_id:
+ logger.warning(f"No valid author ID found for: {author_name}")
+ return []
+
+ # Get the author's papers
+ fields = [
+ "papers.paperId",
+ "papers.title",
+ "papers.abstract",
+ "papers.venue",
+ "papers.year",
+ "papers.authors"
+ ]
+
+ if self.get_tldr:
+ fields.append("papers.tldr")
+
+ url = f"{self.author_details_url}/{author_id}"
+ author_params = {
+ "fields": ",".join(fields)
+ }
+
+ author_data = self._make_request(url, author_params)
+
+ if "papers" not in author_data or not author_data["papers"]:
+ logger.warning(f"No papers found for author: {author_name}")
+ return []
+
+ # Format as paper results
+ papers = author_data["papers"][:self.max_results]
+
+ # Convert to standard results format
+ results = []
+ for paper in papers:
+ # Format authors
+ authors = []
+ if "authors" in paper and paper["authors"]:
+ authors = [author.get("name", "") for author in paper["authors"]]
+
+ result = {
+ "id": paper.get("paperId", ""),
+ "title": paper.get("title", ""),
+ "link": f"https://www.semanticscholar.org/paper/{paper.get('paperId', '')}",
+ "snippet": paper.get("abstract", "")[:250] + "..." if paper.get("abstract", "") and len(paper.get("abstract", "")) > 250 else paper.get("abstract", ""),
+ "authors": authors,
+ "venue": paper.get("venue", ""),
+ "year": paper.get("year"),
+ "source": "Semantic Scholar",
+
+ # Include TLDR if available
+ "tldr": paper.get("tldr", {}).get("text", "") if paper.get("tldr") else ""
+ }
+
+ results.append(result)
+
+ # Add citations and references if needed
+ if self.get_citations or self.get_references:
+ results = self._get_full_content(results)
+
+ return results
+
+ finally:
+ # Restore original value
+ self.max_results = original_max_results
+
+ def search_by_venue(self, venue_name: str, max_results: Optional[int] = None) -> List[Dict[str, Any]]:
+ """
+ Search for papers in a specific venue.
+
+ Args:
+ venue_name: Name of the venue (conference or journal)
+ max_results: Maximum number of results (defaults to self.max_results)
+
+ Returns:
+ List of papers from the venue
+ """
+ original_max_results = self.max_results
+
+ try:
+ if max_results:
+ self.max_results = max_results
+
+ # Semantic Scholar doesn't have a dedicated venue search API
+ # So we search for papers with the venue in the query
+ query = f'venue:"{venue_name}"'
+ return self.run(query)
+
+ finally:
+ # Restore original value
+ self.max_results = original_max_results
+
+ def search_by_year(self, query: str, year: int, max_results: Optional[int] = None) -> List[Dict[str, Any]]:
+ """
+ Search for papers from a specific year matching the query.
+
+ Args:
+ query: The search query
+ year: Publication year
+ max_results: Maximum number of results (defaults to self.max_results)
+
+ Returns:
+ List of papers from the specified year matching the query
+ """
+ original_max_results = self.max_results
+ original_year_range = self.year_range
+
+ try:
+ if max_results:
+ self.max_results = max_results
+
+ # Set year range for this search
+ self.year_range = (year, year)
+
+ return self.run(query)
+
+ finally:
+ # Restore original values
+ self.max_results = original_max_results
+ self.year_range = original_year_range
+
+ def search_by_field(self, query: str, field_of_study: str, max_results: Optional[int] = None) -> List[Dict[str, Any]]:
+ """
+ Search for papers in a specific field of study.
+
+ Args:
+ query: The search query
+ field_of_study: Field of study (e.g., "Computer Science", "Medicine")
+ max_results: Maximum number of results (defaults to self.max_results)
+
+ Returns:
+ List of papers in the specified field matching the query
+ """
+ original_max_results = self.max_results
+
+ try:
+ if max_results:
+ self.max_results = max_results
+
+ # Add field of study to query
+ field_query = f'{query} fieldofstudy:"{field_of_study}"'
+ return self.run(field_query)
+
+ finally:
+ # Restore original value
+ self.max_results = original_max_results
+
+ def get_paper_by_id(self, paper_id: str) -> Dict[str, Any]:
+ """
+ Get a specific paper by its Semantic Scholar ID.
+
+ Args:
+ paper_id: Semantic Scholar paper ID
+
+ Returns:
+ Dictionary with paper information
+ """
+ paper_details = self._get_paper_details(paper_id)
+
+ if not paper_details:
+ return {}
+
+ # Format authors
+ authors = []
+ if "authors" in paper_details and paper_details["authors"]:
+ authors = [author.get("name", "") for author in paper_details["authors"]]
+
+ # Create formatted result
+ result = {
+ "id": paper_details.get("paperId", ""),
+ "title": paper_details.get("title", ""),
+ "link": paper_details.get("url", ""),
+ "abstract": paper_details.get("abstract", ""),
+ "authors": authors,
+ "venue": paper_details.get("venue", ""),
+ "year": paper_details.get("year"),
+ "fields_of_study": paper_details.get("fieldsOfStudy", []),
+ "external_ids": paper_details.get("externalIds", {}),
+ "source": "Semantic Scholar",
+
+ # Include TLDR if available
+ "tldr": paper_details.get("tldr", {}).get("text", "") if paper_details.get("tldr") else ""
+ }
+
+ # Add citations and references if requested
+ if self.get_citations and "citations" in paper_details:
+ result["citations"] = paper_details["citations"]
+
+ if self.get_references and "references" in paper_details:
+ result["references"] = paper_details["references"]
+
+ # Add embedding if requested
+ if self.get_embeddings and "embedding" in paper_details:
+ result["embedding"] = paper_details["embedding"]
+
+ return result
+
+ def get_paper_by_doi(self, doi: str) -> Dict[str, Any]:
+ """
+ Get a paper by its DOI.
+
+ Args:
+ doi: Digital Object Identifier
+
+ Returns:
+ Dictionary with paper information
+ """
+ try:
+ # The Semantic Scholar API supports DOI lookup
+ url = f"{self.paper_details_url}/DOI:{doi}"
+ fields = [
+ "paperId",
+ "externalIds",
+ "url",
+ "title",
+ "abstract",
+ "venue",
+ "year",
+ "authors",
+ "fieldsOfStudy"
+ ]
+
+ if self.get_tldr:
+ fields.append("tldr")
+
+ if self.get_embeddings:
+ fields.append("embedding")
+
+ # Add citation and reference fields if requested
+ if self.get_citations:
+ fields.append(f"citations.limit({self.citation_limit})")
+
+ if self.get_references:
+ fields.append(f"references.limit({self.reference_limit})")
+
+ params = {"fields": ",".join(fields)}
+ paper_details = self._make_request(url, params)
+
+ if not paper_details:
+ return {}
+
+ # Format the paper info the same way as get_paper_by_id
+ # Format authors
+ authors = []
+ if "authors" in paper_details and paper_details["authors"]:
+ authors = [author.get("name", "") for author in paper_details["authors"]]
+
+ # Create formatted result
+ result = {
+ "id": paper_details.get("paperId", ""),
+ "title": paper_details.get("title", ""),
+ "link": paper_details.get("url", ""),
+ "abstract": paper_details.get("abstract", ""),
+ "authors": authors,
+ "venue": paper_details.get("venue", ""),
+ "year": paper_details.get("year"),
+ "fields_of_study": paper_details.get("fieldsOfStudy", []),
+ "external_ids": paper_details.get("externalIds", {}),
+ "source": "Semantic Scholar",
+
+ # Include TLDR if available
+ "tldr": paper_details.get("tldr", {}).get("text", "") if paper_details.get("tldr") else ""
+ }
+
+ # Add citations and references if requested
+ if self.get_citations and "citations" in paper_details:
+ result["citations"] = paper_details["citations"]
+
+ if self.get_references and "references" in paper_details:
+ result["references"] = paper_details["references"]
+
+ # Add embedding if requested
+ if self.get_embeddings and "embedding" in paper_details:
+ result["embedding"] = paper_details["embedding"]
+
+ return result
+
+ except Exception as e:
+ logger.error(f"Error getting paper by DOI {doi}: {e}")
+ return {}
+
+ def get_papers_batch(self, paper_ids: List[str], fields: Optional[List[str]] = None) -> List[Dict[str, Any]]:
+ """
+ Get details for multiple papers in a single batch request.
+
+ Args:
+ paper_ids: List of paper IDs (Semantic Scholar IDs, DOIs, arXiv IDs, etc.)
+ fields: Fields to include in the response
+
+ Returns:
+ List of paper details
+ """
+ if not paper_ids:
+ return []
+
+ if fields is None:
+ fields = [
+ "paperId",
+ "externalIds",
+ "url",
+ "title",
+ "abstract",
+ "venue",
+ "year",
+ "authors",
+ "referenceCount",
+ "citationCount"
+ ]
+
+ if self.get_tldr:
+ fields.append("tldr")
+
+ try:
+ # Construct request params
+ params = {
+ "fields": ",".join(fields)
+ }
+
+ # Make POST request with paper IDs in the body
+ response = self._make_request(
+ self.paper_batch_url,
+ params=params,
+ data={"ids": paper_ids},
+ method="POST"
+ )
+
+ if isinstance(response, list):
+ return response
+ else:
+ logger.warning("Unexpected response format from batch API")
+ return []
+
+ except Exception as e:
+ logger.error(f"Error in batch paper lookup: {e}")
+ return []
+
+ def get_paper_recommendations(self,
+ positive_paper_ids: List[str],
+ negative_paper_ids: Optional[List[str]] = None,
+ max_results: Optional[int] = None) -> List[Dict[str, Any]]:
+ """
+ Get recommended papers based on positive and negative examples.
+
+ Args:
+ positive_paper_ids: List of paper IDs to use as positive examples
+ negative_paper_ids: Optional list of paper IDs to use as negative examples
+ max_results: Maximum number of recommendations to return
+
+ Returns:
+ List of recommended papers
+ """
+ if not positive_paper_ids:
+ return []
+
+ limit = max_results or self.max_results
+
+ try:
+ # Construct the request payload
+ payload = {
+ "positivePaperIds": positive_paper_ids
+ }
+
+ if negative_paper_ids:
+ payload["negativePaperIds"] = negative_paper_ids
+
+ # Define fields to include in the response
+ fields = [
+ "paperId",
+ "externalIds",
+ "url",
+ "title",
+ "abstract",
+ "venue",
+ "year",
+ "authors"
+ ]
+
+ if self.get_tldr:
+ fields.append("tldr")
+
+ # Request parameters
+ params = {
+ "fields": ",".join(fields),
+ "limit": limit
+ }
+
+ # Make POST request to recommendations endpoint
+ response = self._make_request(
+ self.recommendations_url,
+ params=params,
+ data=payload,
+ method="POST"
+ )
+
+ if "recommendedPapers" not in response:
+ return []
+
+ papers = response["recommendedPapers"]
+
+ # Format as standard results
+ results = []
+ for paper in papers:
+ # Format authors
+ authors = []
+ if "authors" in paper and paper["authors"]:
+ authors = [author.get("name", "") for author in paper["authors"]]
+
+ result = {
+ "id": paper.get("paperId", ""),
+ "title": paper.get("title", ""),
+ "link": paper.get("url", ""),
+ "snippet": paper.get("abstract", "")[:250] + "..." if paper.get("abstract", "") and len(paper.get("abstract", "")) > 250 else paper.get("abstract", ""),
+ "authors": authors,
+ "venue": paper.get("venue", ""),
+ "year": paper.get("year"),
+ "source": "Semantic Scholar",
+
+ # Include TLDR if available
+ "tldr": paper.get("tldr", {}).get("text", "") if paper.get("tldr") else ""
+ }
+
+ results.append(result)
+
+ return results
+
+ except Exception as e:
+ logger.error(f"Error getting paper recommendations: {e}")
+ return []
\ No newline at end of file
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py b/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py
index c0f2b04f02..c6db06b754 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py
@@ -38,10 +38,8 @@ class SerpAPISearchEngine(BaseSearchEngine):
max_filtered_results: Maximum number of results to keep after filtering
**kwargs: Additional parameters (ignored but accepted for compatibility)
"""
- # Initialize the BaseSearchEngine with the LLM and max_filtered_results
- super().__init__(llm=llm, max_filtered_results=max_filtered_results)
-
- self.max_results = max_results
+ # Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
+ super().__init__(llm=llm, max_filtered_results=max_filtered_results, max_results=max_results)
self.include_full_content = include_full_content
# Set up language code mapping
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py b/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py
index 8e767c5225..82e761d9c2 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py
@@ -38,10 +38,8 @@ class WaybackSearchEngine(BaseSearchEngine):
max_filtered_results: Maximum number of results to keep after filtering
closest_only: If True, only retrieves the closest snapshot for each URL
"""
- # Initialize the BaseSearchEngine with the LLM and max_filtered_results
- super().__init__(llm=llm, max_filtered_results=max_filtered_results)
-
- self.max_results = max_results
+ # Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
+ super().__init__(llm=llm, max_filtered_results=max_filtered_results, max_results=max_results)
self.max_snapshots_per_url = max_snapshots_per_url
self.language = language
self.closest_only = closest_only
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py b/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py
index 3bf65de312..193b0653f4 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py
@@ -33,10 +33,8 @@ class WikipediaSearchEngine(BaseSearchEngine):
max_filtered_results: Maximum number of results to keep after filtering
**kwargs: Additional parameters (ignored but accepted for compatibility)
"""
- # Initialize the BaseSearchEngine with the LLM and max_filtered_results
- super().__init__(llm=llm, max_filtered_results=max_filtered_results)
-
- self.max_results = max_results
+ # Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
+ super().__init__(llm=llm, max_filtered_results=max_filtered_results, max_results=max_results)
self.include_content = include_content
self.sentences = sentences
diff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.py
index 0e66f788f5..25a37e145e 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
@@ -15,20 +15,28 @@ class BaseSearchEngine(ABC):
"""
def __init__(self,
- llm: Optional[BaseLLM] = None,
- max_filtered_results: Optional[int] = 5,
- **kwargs):
+ llm: Optional[BaseLLM] = None,
+ max_filtered_results: Optional[int] = None,
+ max_results: Optional[int] = 10, # Default value if not provided
+ **kwargs):
"""
Initialize the search engine with common parameters.
Args:
llm: Optional language model for relevance filtering
max_filtered_results: Maximum number of results to keep after filtering
+ max_results: Maximum number of search results to return
**kwargs: Additional engine-specific parameters
"""
- if max_filtered_results == None: max_filtered_results=5
+ if max_filtered_results == None: max_filtered_results = 5
self.llm = llm # LLM for relevance filtering
self.max_filtered_results = max_filtered_results # Limit filtered results
+
+ # Ensure max_results is never None and is a positive integer
+ if max_results is None:
+ self.max_results = 25 # Default if None
+ else:
+ self.max_results = max(1, int(max_results))
def run(self, query: str) -> List[Dict[str, Any]]:
"""