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.

Fix PubMed search and improve snippet retrieval

LearningCircuit24a43a3ddda7
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index 36bbfe0467..a9b4009877 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -2825,6 +2825,202 @@
"value": true,
"visible": true
},
+ "search.engine.web.pubmed.default_params.show_publication_type": {
+ "category": "pubmed",
+ "description": "Show publication type (e.g., Clinical Trial, Meta-Analysis) in snippets",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Show Publication Type",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
+ },
+ "search.engine.web.pubmed.default_params.show_journal": {
+ "category": "pubmed",
+ "description": "Show journal name in snippets",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Show Journal",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
+ },
+ "search.engine.web.pubmed.default_params.show_year": {
+ "category": "pubmed",
+ "description": "Show publication year in snippets",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Show Year",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
+ },
+ "search.engine.web.pubmed.default_params.show_authors": {
+ "category": "pubmed",
+ "description": "Show author names in snippets",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Show Authors",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ },
+ "search.engine.web.pubmed.default_params.show_full_date": {
+ "category": "pubmed",
+ "description": "Show full publication date instead of just year",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Show Full Date",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ },
+ "search.engine.web.pubmed.default_params.show_mesh_terms": {
+ "category": "pubmed",
+ "description": "Show MeSH terms (medical subject headings) for classification",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Show MeSH Terms",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
+ },
+ "search.engine.web.pubmed.default_params.show_keywords": {
+ "category": "pubmed",
+ "description": "Show article keywords",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Show Keywords",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
+ },
+ "search.engine.web.pubmed.default_params.show_doi": {
+ "category": "pubmed",
+ "description": "Show DOI (Digital Object Identifier)",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Show DOI",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ },
+ "search.engine.web.pubmed.default_params.show_pmid": {
+ "category": "pubmed",
+ "description": "Show PubMed ID",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Show PMID",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ },
+ "search.engine.web.pubmed.default_params.show_pmc_availability": {
+ "category": "pubmed",
+ "description": "Show if free full text is available in PMC",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Show PMC Availability",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ },
+ "search.engine.web.pubmed.default_params.max_mesh_terms": {
+ "category": "pubmed",
+ "description": "Maximum number of MeSH terms to show (0 = all)",
+ "editable": true,
+ "max_value": 10,
+ "min_value": 0,
+ "name": "Max MeSH Terms",
+ "options": null,
+ "step": 1,
+ "type": "SEARCH",
+ "ui_element": "number",
+ "value": 3,
+ "visible": true
+ },
+ "search.engine.web.pubmed.default_params.max_keywords": {
+ "category": "pubmed",
+ "description": "Maximum number of keywords to show (0 = all)",
+ "editable": true,
+ "max_value": 10,
+ "min_value": 0,
+ "name": "Max Keywords",
+ "options": null,
+ "step": 1,
+ "type": "SEARCH",
+ "ui_element": "number",
+ "value": 3,
+ "visible": true
+ },
+ "search.engine.web.pubmed.default_params.show_citation": {
+ "category": "pubmed",
+ "description": "Show volume, issue, and pages for proper citation",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Show Citation Details",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ },
+ "search.engine.web.pubmed.default_params.show_language": {
+ "category": "pubmed",
+ "description": "Show language if not English",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Show Language",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ },
"search.engine.web.pubmed.module_path": {
"category": "pubmed",
"description": "Setting for pubmed.module_path",
@@ -4578,7 +4774,7 @@
"step": 0.05,
"type": "APP",
"ui_element": "range",
- "value": 0.3,
+ "value": 0.45,
"visible": true
},
"rate_limiting.memory_window": {
diff --git a/src/local_deep_research/web/routes/metrics_routes.py b/src/local_deep_research/web/routes/metrics_routes.py
index 31bcd5d0b4..880f2fd23b 100644
--- a/src/local_deep_research/web/routes/metrics_routes.py
+++ b/src/local_deep_research/web/routes/metrics_routes.py
@@ -780,7 +780,7 @@ def get_rate_limiting_analytics(period="30d", username=None):
engine_stat["last_updated"] = datetime.fromtimestamp(
estimate.last_updated, UTC
- ).strftime("%Y-%m-%d %H:%M:%S")
+ ).isoformat() # ISO format already includes timezone
else:
engine_stat["last_updated"] = "Never"
@@ -1012,7 +1012,7 @@ def api_current_rate_limits():
"total_attempts": total_attempts,
"last_updated": datetime.fromtimestamp(
last_updated, UTC
- ).strftime("%Y-%m-%d %H:%M:%S"),
+ ).isoformat(), # ISO format already includes timezone
"status": "healthy"
if success_rate > 0.8
else "degraded"
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 26ec19afd6..fdddb4d194 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -952,7 +952,6 @@ def run_research_process(
else:
metadata = {}
- logger.info(f"Metadata after loading: {metadata}")
metadata.update(
{
"iterations": results["iterations"],
@@ -1225,7 +1224,6 @@ def run_research_process(
else:
metadata = {}
- logger.info(f"Full report - Metadata after loading: {metadata}")
metadata.update(final_report["metadata"])
metadata["iterations"] = results["iterations"]
diff --git a/src/local_deep_research/web/templates/pages/metrics.html b/src/local_deep_research/web/templates/pages/metrics.html
index a625aa596e..9e6284387c 100644
--- a/src/local_deep_research/web/templates/pages/metrics.html
+++ b/src/local_deep_research/web/templates/pages/metrics.html
@@ -1876,17 +1876,30 @@
return 'No rate limits yet';
}
const date = new Date(timeString);
+ if (isNaN(date.getTime())) {
+ console.error('Invalid date:', timeString);
+ return 'No rate limits yet';
+ }
const now = new Date();
- const diffHours = (now - date) / (1000 * 60 * 60);
+ const diffMs = now - date;
+ const diffHours = diffMs / (1000 * 60 * 60);
- if (diffHours < 1) {
+ if (diffHours < 0) {
+ // Future time (shouldn't happen but handle it)
return 'Just now';
+ } else if (diffHours < 1) {
+ const diffMinutes = Math.floor(diffMs / (1000 * 60));
+ if (diffMinutes < 1) {
+ return 'Just now';
+ }
+ return `${diffMinutes}m ago`;
} else if (diffHours < 24) {
return `${Math.floor(diffHours)}h ago`;
} else {
return `${Math.floor(diffHours / 24)}d ago`;
}
- } catch {
+ } catch (error) {
+ console.error('Error formatting time:', error, timeString);
return 'No rate limits yet';
}
}
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 1dcdf78f11..a903a72d23 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
@@ -28,6 +28,20 @@ class PubMedSearchEngine(BaseSearchEngine):
llm: Optional[BaseLLM] = None,
max_filtered_results: Optional[int] = None,
optimize_queries: bool = True,
+ show_publication_type: bool = True,
+ show_journal: bool = True,
+ show_year: bool = True,
+ show_authors: bool = False,
+ show_full_date: bool = False,
+ show_mesh_terms: bool = True,
+ show_keywords: bool = True,
+ show_doi: bool = False,
+ show_pmid: bool = False,
+ show_pmc_availability: bool = False,
+ max_mesh_terms: int = 3,
+ max_keywords: int = 3,
+ show_citation: bool = False,
+ show_language: bool = False,
):
"""
Initialize the PubMed search engine.
@@ -56,6 +70,20 @@ class PubMedSearchEngine(BaseSearchEngine):
self.get_full_text = get_full_text
self.full_text_limit = full_text_limit
self.optimize_queries = optimize_queries
+ self.show_publication_type = show_publication_type
+ self.show_journal = show_journal
+ self.show_year = show_year
+ self.show_authors = show_authors
+ self.show_full_date = show_full_date
+ self.show_mesh_terms = show_mesh_terms
+ self.show_keywords = show_keywords
+ self.show_doi = show_doi
+ self.show_pmid = show_pmid
+ self.show_pmc_availability = show_pmc_availability
+ self.max_mesh_terms = max_mesh_terms
+ self.max_keywords = max_keywords
+ self.show_citation = show_citation
+ self.show_language = show_language
# Base API URLs
self.base_url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils"
@@ -305,31 +333,28 @@ Return ONLY the search query without any explanations.
]
optimized_query = " AND ".join(words[:3])
- # Safety check for invalid or overly complex MeSH terms
- # This helps prevent errors with non-existent or complex MeSH terms
+ # Basic cleanup: standardize field tag case for consistency
import re
- mesh_terms = re.findall(r'"[^"]+"[Mesh]', optimized_query)
- known_valid_mesh = [
- "Vaccines",
- "COVID-19",
- "Influenza",
- "Infectious Disease Medicine",
- "Communicable Diseases",
- "RNA, Messenger",
- "Vaccination",
- "Immunization",
- ]
+ optimized_query = re.sub(
+ r"\[mesh\]", "[Mesh]", optimized_query, flags=re.IGNORECASE
+ )
+ optimized_query = re.sub(
+ r"\[title/abstract\]",
+ "[Title/Abstract]",
+ optimized_query,
+ flags=re.IGNORECASE,
+ )
+ optimized_query = re.sub(
+ r"\[publication type\]",
+ "[Publication Type]",
+ optimized_query,
+ flags=re.IGNORECASE,
+ )
- # Replace potentially problematic MeSH terms with Title/Abstract searches
- for term in mesh_terms:
- term_name = term.split('"')[
- 1
- ] # Extract term name without quotes and [Mesh]
- if not any(valid in term_name for valid in known_valid_mesh):
- # Replace with Title/Abstract search
- replacement = f"{term_name.lower()}[Title/Abstract]"
- optimized_query = optimized_query.replace(term, replacement)
+ # Fix unclosed quotes followed by field tags
+ # Pattern: "term[Field] -> "term"[Field]
+ optimized_query = re.sub(r'"([^"]+)\[', r'"\1"[', optimized_query)
# Simplify the query if still no results are found
self._simplify_query_cache = optimized_query
@@ -337,11 +362,15 @@ Return ONLY the search query without any explanations.
# Log original and optimized queries
logger.info("Original query: '%s'", query)
logger.info(f"Optimized for PubMed: '{optimized_query}'")
+ logger.debug(
+ f"Query optimization complete: '{query[:50]}...' -> '{optimized_query[:100]}...'"
+ )
return optimized_query
- except Exception:
- logger.exception("Error optimizing query")
+ except Exception as e:
+ logger.exception(f"Error optimizing query: {str(e)}")
+ logger.debug(f"Falling back to original query: '{query}'")
return query # Fall back to original query on error
def _simplify_query(self, query: str) -> str:
@@ -356,23 +385,34 @@ Return ONLY the search query without any explanations.
Simplified query
"""
logger.info(f"Simplifying query: {query}")
+ logger.debug(f"Query simplification started for: '{query[:100]}...'")
- # Attempt different simplification strategies
-
- # 1. Remove any MeSH terms and replace with Title/Abstract
+ # Simple approach: remove field restrictions to broaden the search
import re
+ # Remove field tags to make search broader
+ simplified = query
+
+ # Remove [Mesh] tags - search in all fields instead
+ simplified = re.sub(r"\[Mesh\]", "", simplified, flags=re.IGNORECASE)
+
+ # Remove [Publication Type] tags
simplified = re.sub(
- r'"[^"]+"[Mesh]',
- lambda m: m.group(0).split('"')[1].lower() + "[Title/Abstract]",
- query,
+ r"\[Publication Type\]", "", simplified, flags=re.IGNORECASE
)
- # 2. If that doesn't work, focus on just mRNA and vaccines - the core concepts
- if simplified == query: # No changes were made
- simplified = '(mRNA[Title/Abstract] OR "messenger RNA"[Title/Abstract]) AND vaccin*[Title/Abstract]'
+ # Keep [Title/Abstract] as it's usually helpful
+ # Clean up any double spaces
+ simplified = re.sub(r"\s+", " ", simplified).strip()
+
+ # If no simplification was possible, return the original query
+ if simplified == query:
+ logger.debug("No simplification possible, returning original query")
logger.info(f"Simplified query: {simplified}")
+ logger.debug(
+ f"Query simplified from {len(query)} to {len(simplified)} chars"
+ )
return simplified
def _is_historical_focused(self, query: str) -> bool:
@@ -552,31 +592,49 @@ The default assumption should be that medical and scientific queries want RECENT
# Add API key if available
if self.api_key:
params["api_key"] = self.api_key
+ logger.debug("Using PubMed API key for higher rate limits")
+ else:
+ logger.debug("No PubMed API key - using default rate limits")
# Add date restriction if specified
if self.days_limit:
params["reldate"] = self.days_limit
params["datetype"] = "pdat" # Publication date
+ logger.debug(f"Limiting results to last {self.days_limit} days")
+
+ logger.debug(
+ f"PubMed search query: '{query}' with max_results={self.max_results}"
+ )
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"
+ )
# Execute search request
+ logger.debug(f"Sending request to PubMed API: {self.search_url}")
response = requests.get(self.search_url, params=params)
response.raise_for_status()
+ logger.debug(f"PubMed API response status: {response.status_code}")
# Parse response
data = response.json()
id_list = data["esearchresult"]["idlist"]
+ total_count = data["esearchresult"].get("count", "unknown")
logger.info(
- f"PubMed search for '{query}' found {len(id_list)} results"
+ f"PubMed search for '{query}' found {len(id_list)} results (total available: {total_count})"
)
+ if len(id_list) > 0:
+ logger.debug(f"First 5 PMIDs: {id_list[:5]}")
return id_list
- except Exception:
- logger.exception("Error searching PubMed")
+ except Exception as e:
+ logger.exception(
+ f"Error searching PubMed for query '{query}': {str(e)}"
+ )
return []
def _get_article_summaries(
@@ -592,8 +650,11 @@ The default assumption should be that medical and scientific queries want RECENT
List of article summary dictionaries
"""
if not id_list:
+ logger.debug("Empty ID list provided to _get_article_summaries")
return []
+ logger.debug(f"Fetching summaries for {len(id_list)} PubMed articles")
+
try:
# Prepare parameters
params = {
@@ -610,18 +671,29 @@ The default assumption should be that medical and scientific queries want RECENT
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"
+ )
# Execute request
+ logger.debug(f"Requesting summaries from: {self.summary_url}")
response = requests.get(self.summary_url, params=params)
response.raise_for_status()
+ logger.debug(f"Summary API response status: {response.status_code}")
# Parse response
data = response.json()
+ logger.debug(
+ f"PubMed API returned data for {len(id_list)} requested IDs"
+ )
summaries = []
for pmid in id_list:
if pmid in data["result"]:
article = data["result"][pmid]
+ logger.debug(
+ f"Processing article {pmid}: {article.get('title', 'NO TITLE')[:50]}"
+ )
# Extract authors (if available)
authors = []
@@ -630,25 +702,52 @@ The default assumption should be that medical and scientific queries want RECENT
author["name"] for author in article["authors"]
]
- # Create summary dictionary
+ # Extract DOI from articleids if not in main field
+ doi = article.get("doi", "")
+ if not doi and "articleids" in article:
+ for aid in article["articleids"]:
+ if aid.get("idtype") == "doi":
+ doi = aid.get("value", "")
+ break
+
+ # Create summary dictionary with all available fields
summary = {
"id": pmid,
"title": article.get("title", ""),
"pubdate": article.get("pubdate", ""),
+ "epubdate": article.get("epubdate", ""),
"source": article.get("source", ""),
"authors": authors,
+ "lastauthor": article.get("lastauthor", ""),
"journal": article.get("fulljournalname", ""),
- "doi": article.get("doi", ""),
+ "volume": article.get("volume", ""),
+ "issue": article.get("issue", ""),
+ "pages": article.get("pages", ""),
+ "doi": doi,
+ "issn": article.get("issn", ""),
+ "essn": article.get("essn", ""),
+ "pubtype": article.get(
+ "pubtype", []
+ ), # Publication types from esummary
+ "recordstatus": article.get("recordstatus", ""),
+ "lang": article.get("lang", []),
+ "pmcrefcount": article.get("pmcrefcount", None),
"link": f"https://pubmed.ncbi.nlm.nih.gov/{pmid}/",
}
summaries.append(summary)
+ else:
+ logger.warning(
+ f"PMID {pmid} not found in PubMed API response"
+ )
return summaries
except Exception as e:
error_msg = str(e)
- logger.exception("Error getting article summaries")
+ logger.exception(
+ f"Error getting article summaries for {len(id_list)} articles: {error_msg}"
+ )
# Check for rate limiting patterns
if (
@@ -674,8 +773,11 @@ The default assumption should be that medical and scientific queries want RECENT
Dictionary mapping PubMed IDs to their abstracts
"""
if not id_list:
+ logger.debug("Empty ID list provided to _get_article_abstracts")
return {}
+ logger.debug(f"Fetching abstracts for {len(id_list)} PubMed articles")
+
try:
# Prepare parameters
params = {
@@ -692,13 +794,23 @@ The default assumption should be that medical and scientific queries want RECENT
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"
+ )
# Execute request
+ logger.debug(f"Requesting abstracts from: {self.fetch_url}")
response = requests.get(self.fetch_url, params=params)
response.raise_for_status()
+ logger.debug(
+ f"Abstract fetch response status: {response.status_code}, size: {len(response.text)} bytes"
+ )
# Parse XML response
root = ET.fromstring(response.text)
+ logger.debug(
+ f"Parsing abstracts from XML for {len(id_list)} articles"
+ )
# Extract abstracts
abstracts = {}
@@ -718,7 +830,13 @@ The default assumption should be that medical and scientific queries want RECENT
abstract_text = abstract_elem.text or ""
# Some abstracts are split into multiple sections
- for section in article.findall(".//AbstractText"):
+ abstract_sections = article.findall(".//AbstractText")
+ if len(abstract_sections) > 1:
+ logger.debug(
+ f"Article {pmid} has {len(abstract_sections)} abstract sections"
+ )
+
+ for section in abstract_sections:
# Get section label if it exists
label = section.get("Label")
section_text = section.text or ""
@@ -737,13 +855,259 @@ The default assumption should be that medical and scientific queries want RECENT
# Store in dictionary
if pmid and abstract_text:
abstracts[pmid] = abstract_text
+ logger.debug(
+ f"Abstract for {pmid}: {len(abstract_text)} chars"
+ )
+ elif pmid:
+ logger.warning(f"No abstract found for PMID {pmid}")
+ logger.info(
+ f"Successfully retrieved {len(abstracts)} abstracts out of {len(id_list)} requested"
+ )
return abstracts
+ except Exception as e:
+ logger.exception(
+ f"Error getting article abstracts for {len(id_list)} articles: {str(e)}"
+ )
+ return {}
+
+ def _get_article_detailed_metadata(
+ self, id_list: List[str]
+ ) -> Dict[str, Dict[str, Any]]:
+ """
+ Get detailed metadata for PubMed articles including publication types,
+ MeSH terms, keywords, and affiliations.
+
+ Args:
+ id_list: List of PubMed IDs
+
+ Returns:
+ Dictionary mapping PubMed IDs to their detailed metadata
+ """
+ if not id_list:
+ return {}
+
+ try:
+ # Prepare parameters
+ params = {
+ "db": "pubmed",
+ "id": ",".join(id_list),
+ "retmode": "xml",
+ "rettype": "medline",
+ }
+
+ # Add API key if available
+ if self.api_key:
+ params["api_key"] = self.api_key
+
+ self._last_wait_time = self.rate_tracker.apply_rate_limit(
+ self.engine_type
+ )
+
+ # Execute request
+ response = requests.get(self.fetch_url, params=params)
+ response.raise_for_status()
+
+ # Parse XML response
+ root = ET.fromstring(response.text)
+
+ metadata = {}
+
+ for article in root.findall(".//PubmedArticle"):
+ pmid_elem = article.find(".//PMID")
+ pmid = pmid_elem.text if pmid_elem is not None else None
+
+ if pmid is None:
+ continue
+
+ article_metadata = {}
+
+ # Extract publication types
+ pub_types = []
+ for pub_type in article.findall(".//PublicationType"):
+ if pub_type.text:
+ pub_types.append(pub_type.text)
+ if pub_types:
+ article_metadata["publication_types"] = pub_types
+
+ # Extract MeSH terms
+ mesh_terms = []
+ for mesh in article.findall(".//MeshHeading"):
+ descriptor = mesh.find(".//DescriptorName")
+ if descriptor is not None and descriptor.text:
+ mesh_terms.append(descriptor.text)
+ if mesh_terms:
+ article_metadata["mesh_terms"] = mesh_terms
+
+ # Extract keywords
+ keywords = []
+ for keyword in article.findall(".//Keyword"):
+ if keyword.text:
+ keywords.append(keyword.text)
+ if keywords:
+ article_metadata["keywords"] = keywords
+
+ # Extract affiliations
+ affiliations = []
+ for affiliation in article.findall(".//Affiliation"):
+ if affiliation.text:
+ affiliations.append(affiliation.text)
+ if affiliations:
+ article_metadata["affiliations"] = affiliations
+
+ # Extract grant information
+ grants = []
+ for grant in article.findall(".//Grant"):
+ grant_info = {}
+ grant_id = grant.find(".//GrantID")
+ if grant_id is not None and grant_id.text:
+ grant_info["id"] = grant_id.text
+ agency = grant.find(".//Agency")
+ if agency is not None and agency.text:
+ grant_info["agency"] = agency.text
+ if grant_info:
+ grants.append(grant_info)
+ if grants:
+ article_metadata["grants"] = grants
+
+ # Check for free full text in PMC
+ pmc_elem = article.find(".//ArticleId[@IdType='pmc']")
+ if pmc_elem is not None:
+ article_metadata["has_free_full_text"] = True
+ article_metadata["pmc_id"] = pmc_elem.text
+
+ # Extract conflict of interest statement
+ coi_elem = article.find(".//CoiStatement")
+ if coi_elem is not None and coi_elem.text:
+ article_metadata["conflict_of_interest"] = coi_elem.text
+
+ metadata[pmid] = article_metadata
+
+ return metadata
+
except Exception:
- logger.exception("Error getting article abstracts")
+ logger.exception("Error getting detailed article metadata")
return {}
+ def _create_enriched_content(
+ self, result: Dict[str, Any], base_content: str
+ ) -> str:
+ """
+ Create enriched content by adding relevant metadata context to help the LLM.
+
+ Args:
+ result: The result dictionary with metadata
+ base_content: The base content (abstract or full text)
+
+ Returns:
+ Enriched content string with metadata context
+ """
+ enriched_parts = []
+
+ # Add study type information
+ if "publication_types" in result:
+ pub_types = result["publication_types"]
+ # Filter for significant types
+ significant_types = [
+ pt
+ for pt in pub_types
+ if any(
+ key in pt.lower()
+ for key in [
+ "clinical trial",
+ "randomized",
+ "meta-analysis",
+ "systematic review",
+ "case report",
+ "guideline",
+ "comparative study",
+ "multicenter",
+ ]
+ )
+ ]
+ if significant_types:
+ enriched_parts.append(
+ f"[Study Type: {', '.join(significant_types)}]"
+ )
+
+ # Add the main content
+ enriched_parts.append(base_content)
+
+ # Add metadata footer
+ metadata_footer = []
+
+ # Add ALL MeSH terms
+ if "mesh_terms" in result and len(result["mesh_terms"]) > 0:
+ metadata_footer.append(
+ f"Medical Topics (MeSH): {', '.join(result['mesh_terms'])}"
+ )
+
+ # Add ALL keywords
+ if "keywords" in result and len(result["keywords"]) > 0:
+ metadata_footer.append(f"Keywords: {', '.join(result['keywords'])}")
+
+ # Add ALL affiliations
+ if "affiliations" in result and len(result["affiliations"]) > 0:
+ if len(result["affiliations"]) == 1:
+ metadata_footer.append(
+ f"Institution: {result['affiliations'][0]}"
+ )
+ else:
+ affiliations_text = "\n - " + "\n - ".join(
+ result["affiliations"]
+ )
+ metadata_footer.append(f"Institutions:{affiliations_text}")
+
+ # Add ALL funding information with full details
+ if "grants" in result and len(result["grants"]) > 0:
+ grant_details = []
+ for grant in result["grants"]:
+ grant_text = []
+ if "agency" in grant:
+ grant_text.append(grant["agency"])
+ if "id" in grant:
+ grant_text.append(f"(Grant ID: {grant['id']})")
+ if grant_text:
+ grant_details.append(" ".join(grant_text))
+ if grant_details:
+ if len(grant_details) == 1:
+ metadata_footer.append(f"Funded by: {grant_details[0]}")
+ else:
+ funding_text = "\n - " + "\n - ".join(grant_details)
+ metadata_footer.append(f"Funding Sources:{funding_text}")
+
+ # Add FULL conflict of interest statement
+ if "conflict_of_interest" in result:
+ coi_text = result["conflict_of_interest"]
+ if coi_text:
+ # Still skip trivial "no conflict" statements to reduce noise
+ if not any(
+ phrase in coi_text.lower()
+ for phrase in [
+ "no conflict",
+ "no competing",
+ "nothing to disclose",
+ "none declared",
+ "authors declare no",
+ ]
+ ):
+ metadata_footer.append(f"Conflict of Interest: {coi_text}")
+ elif (
+ "but" in coi_text.lower()
+ or "except" in coi_text.lower()
+ or "however" in coi_text.lower()
+ ):
+ # Include if there's a "no conflict BUT..." type statement
+ metadata_footer.append(f"Conflict of Interest: {coi_text}")
+
+ # Combine everything
+ if metadata_footer:
+ enriched_parts.append("\n---\nStudy Metadata:")
+ enriched_parts.extend(metadata_footer)
+
+ return "\n".join(enriched_parts)
+
def _find_pmc_ids(self, pmid_list: List[str]) -> Dict[str, str]:
"""
Find PMC IDs for the given PubMed IDs (for full-text access).
@@ -872,10 +1236,14 @@ The default assumption should be that medical and scientific queries want RECENT
if text:
full_text.append(text)
- return "\n\n".join(full_text)
+ result_text = "\n\n".join(full_text)
+ logger.debug(
+ f"Successfully extracted {len(result_text)} chars of PMC full text with {len(full_text)} sections"
+ )
+ return result_text
- except Exception:
- logger.exception("Error getting PMC full text")
+ except Exception as e:
+ logger.exception(f"Error getting PMC full text: {str(e)}")
return ""
def _get_previews(self, query: str) -> List[Dict[str, Any]]:
@@ -915,23 +1283,123 @@ The default assumption should be that medical and scientific queries want RECENT
return []
# Get article summaries
+ logger.debug(f"Fetching article summaries for {len(pmid_list)} PMIDs")
summaries = self._get_article_summaries(pmid_list)
+ logger.debug(f"Retrieved {len(summaries)} summaries")
+
+ # ALWAYS fetch abstracts for snippet-only mode to provide context for LLM
+ logger.debug(
+ f"Fetching abstracts for {len(pmid_list)} articles for snippet enrichment"
+ )
+ abstracts = self._get_article_abstracts(pmid_list)
+ logger.debug(f"Retrieved {len(abstracts)} abstracts")
# Format as previews
previews = []
for summary in summaries:
- # Authors formatting
- authors_text = ", ".join(summary.get("authors", []))
- if len(authors_text) > 100:
- # Truncate long author lists
- authors_text = authors_text[:97] + "..."
+ # Build snippet from individual metadata preferences
+ snippet_parts = []
+
+ # Check for publication type from esummary (earlier than detailed metadata)
+ pub_type_prefix = ""
+ if self.show_publication_type and summary.get("pubtype"):
+ # Use first publication type from esummary
+ pub_type_prefix = f"[{summary['pubtype'][0]}] "
+
+ # Add authors if enabled
+ if self.show_authors and summary.get("authors"):
+ authors_text = ", ".join(summary.get("authors", []))
+ if len(authors_text) > 100:
+ # Truncate long author lists
+ authors_text = authors_text[:97] + "..."
+ snippet_parts.append(authors_text)
+
+ # Add journal if enabled
+ if self.show_journal and summary.get("journal"):
+ snippet_parts.append(summary["journal"])
+
+ # Add date (full or year only)
+ if summary.get("pubdate"):
+ if self.show_full_date:
+ snippet_parts.append(summary["pubdate"])
+ elif self.show_year and len(summary["pubdate"]) >= 4:
+ snippet_parts.append(summary["pubdate"][:4])
+
+ # Add citation details if enabled
+ if self.show_citation:
+ citation_parts = []
+ if summary.get("volume"):
+ citation_parts.append(f"Vol {summary['volume']}")
+ if summary.get("issue"):
+ citation_parts.append(f"Issue {summary['issue']}")
+ if summary.get("pages"):
+ citation_parts.append(f"pp {summary['pages']}")
+ if citation_parts:
+ snippet_parts.append(f"({', '.join(citation_parts)})")
+
+ # Join snippet parts or provide default
+ if snippet_parts:
+ # Use different separators based on what's included
+ if self.show_authors:
+ snippet = ". ".join(
+ snippet_parts
+ ) # Authors need period separator
+ else:
+ snippet = " - ".join(
+ snippet_parts
+ ) # Journal and year use dash
+ else:
+ snippet = "Research article"
+
+ # Add publication type prefix
+ snippet = pub_type_prefix + snippet
+
+ # Add language indicator if not English
+ if self.show_language and summary.get("lang"):
+ langs = summary["lang"]
+ if langs and langs[0] != "eng" and langs[0]:
+ snippet = f"{snippet} [{langs[0].upper()}]"
+
+ # Add identifiers if enabled
+ identifier_parts = []
+ if self.show_pmid and summary.get("id"):
+ identifier_parts.append(f"PMID: {summary['id']}")
+ if self.show_doi and summary.get("doi"):
+ identifier_parts.append(f"DOI: {summary['doi']}")
+
+ if identifier_parts:
+ snippet = f"{snippet} | {' | '.join(identifier_parts)}"
+
+ # ALWAYS include title and abstract in snippet for LLM analysis
+ pmid = summary["id"]
+ title = summary["title"]
+ abstract_text = abstracts.get(pmid, "")
+
+ # Truncate abstract if too long
+ if len(abstract_text) > 500:
+ abstract_text = abstract_text[:497] + "..."
+
+ # Build the enriched snippet with title and abstract
+ if abstract_text:
+ enriched_snippet = f"Title: {title}\n\nAbstract: {abstract_text}\n\nMetadata: {snippet}"
+ else:
+ enriched_snippet = f"Title: {title}\n\nMetadata: {snippet}"
+
+ # Log the complete snippet for debugging
+ logger.debug(f"Complete snippet for PMID {pmid}:")
+ logger.debug(f" Title: {title[:100]}...")
+ logger.debug(f" Abstract length: {len(abstract_text)} chars")
+ logger.debug(f" Metadata: {snippet}")
+ logger.debug(
+ f" Full enriched snippet ({len(enriched_snippet)} chars): {enriched_snippet[:500]}..."
+ )
# Create preview with basic information
preview = {
"id": summary["id"],
"title": summary["title"],
"link": summary["link"],
- "snippet": f"{authors_text}. {summary.get('journal', '')}. {summary.get('pubdate', '')}",
+ "snippet": enriched_snippet, # Use enriched snippet with title and abstract
"authors": summary.get("authors", []),
"journal": summary.get("journal", ""),
"pubdate": summary.get("pubdate", ""),
@@ -946,6 +1414,10 @@ The default assumption should be that medical and scientific queries want RECENT
logger.info(
f"Found {len(previews)} PubMed previews using strategy: {strategy}"
)
+ if previews:
+ logger.debug(
+ f"Sample preview title: '{previews[0].get('title', 'NO TITLE')[:80]}...'"
+ )
return previews
def _get_full_content(
@@ -990,6 +1462,11 @@ The default assumption should be that medical and scientific queries want RECENT
if (self.get_abstracts or snippets_only_mode) and pmids:
abstracts = self._get_article_abstracts(pmids)
+ # Get detailed metadata for all articles (publication types, MeSH terms, etc.)
+ detailed_metadata = {}
+ if pmids:
+ detailed_metadata = self._get_article_detailed_metadata(pmids)
+
# Find PMC IDs for full-text retrieval (if enabled and not in snippet-only mode)
pmid_to_pmcid = {}
if self.get_full_text and pmids and not snippets_only_mode:
@@ -1001,24 +1478,133 @@ The default assumption should be that medical and scientific queries want RECENT
result = item.copy()
pmid = item.get("_pmid", "")
+ # Add detailed metadata if available
+ if pmid in detailed_metadata:
+ metadata = detailed_metadata[pmid]
+
+ # Add publication types (e.g., "Clinical Trial", "Meta-Analysis")
+ if "publication_types" in metadata:
+ result["publication_types"] = metadata["publication_types"]
+
+ # Add first publication type to snippet if enabled
+ if (
+ self.show_publication_type
+ and metadata["publication_types"]
+ ):
+ # Just take the first publication type as is
+ pub_type = metadata["publication_types"][0]
+ if "snippet" in result:
+ result["snippet"] = (
+ f"[{pub_type}] {result['snippet']}"
+ )
+
+ # Add MeSH terms for medical categorization
+ if "mesh_terms" in metadata:
+ result["mesh_terms"] = metadata["mesh_terms"]
+
+ # Add MeSH terms to snippet if enabled
+ if self.show_mesh_terms and metadata["mesh_terms"]:
+ mesh_to_show = (
+ metadata["mesh_terms"][: self.max_mesh_terms]
+ if self.max_mesh_terms > 0
+ else metadata["mesh_terms"]
+ )
+ if mesh_to_show and "snippet" in result:
+ mesh_text = "MeSH: " + ", ".join(mesh_to_show)
+ result["snippet"] = (
+ f"{result['snippet']} | {mesh_text}"
+ )
+
+ # Add keywords
+ if "keywords" in metadata:
+ result["keywords"] = metadata["keywords"]
+
+ # Add keywords to snippet if enabled
+ if self.show_keywords and metadata["keywords"]:
+ keywords_to_show = (
+ metadata["keywords"][: self.max_keywords]
+ if self.max_keywords > 0
+ else metadata["keywords"]
+ )
+ if keywords_to_show and "snippet" in result:
+ keywords_text = "Keywords: " + ", ".join(
+ keywords_to_show
+ )
+ result["snippet"] = (
+ f"{result['snippet']} | {keywords_text}"
+ )
+
+ # Add affiliations
+ if "affiliations" in metadata:
+ result["affiliations"] = metadata["affiliations"]
+
+ # Add funding/grant information
+ if "grants" in metadata:
+ result["grants"] = metadata["grants"]
+
+ # Add conflict of interest statement
+ if "conflict_of_interest" in metadata:
+ result["conflict_of_interest"] = metadata[
+ "conflict_of_interest"
+ ]
+
+ # Add free full text availability
+ if "has_free_full_text" in metadata:
+ result["has_free_full_text"] = metadata[
+ "has_free_full_text"
+ ]
+ if "pmc_id" in metadata:
+ result["pmc_id"] = metadata["pmc_id"]
+
+ # Add PMC availability to snippet if enabled
+ if (
+ self.show_pmc_availability
+ and metadata["has_free_full_text"]
+ and "snippet" in result
+ ):
+ result["snippet"] = (
+ f"{result['snippet']} | [Free Full Text]"
+ )
+
# Add abstract if available
if pmid in abstracts:
result["abstract"] = abstracts[pmid]
- # In snippet-only mode, use abstract as snippet
- if snippets_only_mode:
+ # Create enriched content with metadata context
+ enriched_content = self._create_enriched_content(
+ result, abstracts[pmid]
+ )
+
+ # ALWAYS include title and abstract in snippet for LLM analysis
+ # Build comprehensive snippet with title and abstract
+ title = result.get("title", "")
+ abstract_text = (
+ abstracts[pmid][:500]
+ if len(abstracts[pmid]) > 500
+ else abstracts[pmid]
+ )
+
+ # Prepend title and abstract to the existing metadata snippet
+ if "snippet" in result:
+ # Keep metadata snippet and add content
+ result["snippet"] = (
+ f"Title: {title}\n\nAbstract: {abstract_text}\n\nMetadata: {result['snippet']}"
+ )
+ else:
+ # No metadata snippet, just title and abstract
result["snippet"] = (
- abstracts[pmid][:500]
- if len(abstracts[pmid]) > 500
- else abstracts[pmid]
+ f"Title: {title}\n\nAbstract: {abstract_text}"
)
- result["full_content"] = abstracts[pmid]
- result["content"] = abstracts[pmid]
+
+ # In snippet-only mode, use enriched content
+ if snippets_only_mode:
+ result["full_content"] = enriched_content
+ result["content"] = enriched_content
result["content_type"] = "abstract"
# Use abstract as content if no full text
elif pmid not in pmid_to_pmcid:
- result["full_content"] = abstracts[pmid]
- result["content"] = abstracts[pmid]
+ result["full_content"] = enriched_content
+ result["content"] = enriched_content
result["content_type"] = "abstract"
# Add full text for a limited number of top articles
@@ -1035,14 +1621,20 @@ The default assumption should be that medical and scientific queries want RECENT
full_text = self._get_pmc_full_text(pmcid)
if full_text:
- result["full_content"] = full_text
- result["content"] = full_text
+ enriched_full_text = self._create_enriched_content(
+ result, full_text
+ )
+ result["full_content"] = enriched_full_text
+ result["content"] = enriched_full_text
result["content_type"] = "full_text"
result["pmcid"] = pmcid
elif pmid in abstracts:
# Fall back to abstract if full text retrieval fails
- result["full_content"] = abstracts[pmid]
- result["content"] = abstracts[pmid]
+ enriched_content = self._create_enriched_content(
+ result, abstracts[pmid]
+ )
+ result["full_content"] = enriched_content
+ result["content"] = enriched_content
result["content_type"] = "abstract"
# Remove temporary fields
diff --git a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
index 34f2a8ba10..928395eb80 100644
--- a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
+++ b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
@@ -447,13 +447,13 @@ class AdaptiveRateLimitTracker:
# Cap the base wait time to prevent runaway growth
new_base = min(new_base, 10.0) # Max 10 seconds base when all fail
else:
- # Use 25th percentile of successful waits to try going faster
- # If these wait times succeeded, we can try shorter ones
+ # Use 50th percentile (median) of successful waits for more stability
+ # This provides a balanced approach between speed and reliability
successful_waits.sort()
- percentile_25 = successful_waits[
- max(0, int(len(successful_waits) * 0.25) - 1)
+ percentile_50 = successful_waits[
+ max(0, int(len(successful_waits) * 0.50) - 1)
]
- new_base = percentile_25
+ new_base = percentile_50
# Update estimate with learning rate (exponential moving average)
if engine_type in self.current_estimates: