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.

Get very basic version of journal quality filtering working.

Daniel Petti946c714a2a85
diff --git a/pdm.lock b/pdm.lock
index ea65c30718..9c9b38d7d2 100644
--- a/pdm.lock
+++ b/pdm.lock
@@ -5,7 +5,7 @@
groups = ["default", "dev"]
strategy = ["inherit_metadata"]
lock_version = "4.5.0"
-content_hash = "sha256:abe2929d2c2cd54c21b5ac613100a603ff37cdedc88a083d0ac7e5c2bc2e3a30"
+content_hash = "sha256:ee132fa275dedf045b6d9eec0e30e7c86a8f174688ffa0b76e175ccd04d63f91"
[[metadata.targets]]
requires_python = ">=3.10"
@@ -2278,6 +2278,19 @@ files = [
{file = "mccabe-0.7.0.tar.gz", hash = "sha256:348e0240c33b60bbdf4e523192ef919f28cb2c3d7d5c7794f74009290f236325"},
]
+[[package]]
+name = "methodtools"
+version = "0.4.7"
+summary = "Expand standard functools to methods"
+groups = ["default"]
+dependencies = [
+ "wirerope>=0.4.7",
+]
+files = [
+ {file = "methodtools-0.4.7-py2.py3-none-any.whl", hash = "sha256:5e188c780b236adc12e75b5f078c5afb419ef99eb648569fc6d7071f053a1f11"},
+ {file = "methodtools-0.4.7.tar.gz", hash = "sha256:e213439dd64cfe60213f7015da6efe5dd4003fd89376db3baa09fe13ec2bb0ba"},
+]
+
[[package]]
name = "mistune"
version = "3.1.3"
@@ -4925,6 +4938,21 @@ files = [
{file = "wikipedia-1.4.0.tar.gz", hash = "sha256:db0fad1829fdd441b1852306e9856398204dc0786d2996dd2e0c8bb8e26133b2"},
]
+[[package]]
+name = "wirerope"
+version = "1.0.0"
+summary = "'Turn functions and methods into fully controllable objects'"
+groups = ["default"]
+dependencies = [
+ "inspect2>=0.1.0; python_version < \"3\"",
+ "singledispatch>=3.4.0.3; python_version < \"3.4\"",
+ "six>=1.11.0",
+]
+files = [
+ {file = "wirerope-1.0.0-py2.py3-none-any.whl", hash = "sha256:59346555c7b5dbd1c683a4e123f8bed30ca99df646f6867ea6439ceabf43c2f6"},
+ {file = "wirerope-1.0.0.tar.gz", hash = "sha256:7da8bb6feeff9dd939bd7141ef0dc392674e43ba662e20909d6729db81a7c8d0"},
+]
+
[[package]]
name = "wrapt"
version = "1.17.2"
diff --git a/pyproject.toml b/pyproject.toml
index 885cbcc6f6..0efeb1a541 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -55,6 +55,7 @@ dependencies = [
"importlib-resources>=6.5.2",
"setuptools>=78.1.0",
"flask-wtf>=1.2.2",
+ "methodtools>=0.4.7",
]
[project.urls]
diff --git a/src/local_deep_research/advanced_search_system/filters/base_filter.py b/src/local_deep_research/advanced_search_system/filters/base_filter.py
index 63c0eb9bae..74458399b9 100644
--- a/src/local_deep_research/advanced_search_system/filters/base_filter.py
+++ b/src/local_deep_research/advanced_search_system/filters/base_filter.py
@@ -7,13 +7,15 @@ import logging
from abc import ABC, abstractmethod
from typing import Dict, List
+from langchain_core.language_models.chat_models import BaseChatModel
+
logger = logging.getLogger(__name__)
class BaseFilter(ABC):
"""Abstract base class for all search result filters."""
- def __init__(self, model=None):
+ def __init__(self, model: BaseChatModel | None = None):
"""
Initialize the filter.
diff --git a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
new file mode 100644
index 0000000000..e5dde600a2
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
@@ -0,0 +1,208 @@
+import logging
+from typing import Any, Dict, List, Optional
+
+from langchain_core.language_models.chat_models import BaseChatModel
+from methodtools import lru_cache
+
+from ...config.llm_config import get_llm
+from ...search_system import AdvancedSearchSystem
+from ...utilities.db_utils import get_db_setting
+from ...web_search_engines.search_engine_factory import create_search_engine
+from .base_filter import BaseFilter
+
+logger = logging.getLogger(__name__)
+
+
+class JournalFilterError(Exception):
+ """
+ Custom exception for errors related to journal filtering.
+ """
+
+
+class JournalReputationFilter(BaseFilter):
+ """
+ A filter for academic results that considers the reputation of journals.
+
+ Note that this filter requires SearXNG to be available in order to work.
+ """
+
+ def __init__(
+ self,
+ model: BaseChatModel | None = None,
+ reliability_threshold: int | None = None,
+ max_context: int | None = None,
+ exclude_non_published: bool | None = None,
+ ):
+ """
+ Args:
+ model: The LLM model to use for analysis.
+ reliability_threshold: The filter scores journal reliability on a
+ scale of 1-10. Results from any journal with a reliability
+ below this threshold will be culled. Will be read from the
+ settings if not specified.
+ max_context: The maximum number of characters to feed into the
+ LLM when assessing journal reliability.
+ exclude_non_published: If true, it will exclude any results that
+ don't have an associated journal publication.
+
+ """
+ super().__init__(model)
+
+ if self.model is None:
+ self.model = get_llm()
+
+ self.__threshold = reliability_threshold
+ if self.__threshold is None:
+ self.__threshold = int(
+ get_db_setting("search.journal_reputation.threshold", 4)
+ )
+ self.__max_context = max_context
+ if self.__max_context is None:
+ self.__max_context = int(
+ get_db_setting("search.journal_reputation.max_context", 3000)
+ )
+ self.__exclude_non_published = exclude_non_published
+ if self.__exclude_non_published:
+ self.__exclude_non_published = bool(
+ get_db_setting("search.journal_reputation.exclude_non_published", False)
+ )
+
+ # SearXNG is required so we can search the open web for reputational
+ # information.
+ self.__engine = create_search_engine("searxng", llm=self.model)
+ if self.__engine is None:
+ raise JournalFilterError("SearXNG initialization failed.")
+
+ # Search system that will be used internally for the filtering.
+ self.__search_system = AdvancedSearchSystem(
+ llm=self.model,
+ search=self.__engine,
+ # We clamp down on the default iterations and questions for speed.
+ max_iterations=2,
+ questions_per_iteration=3,
+ )
+
+ @classmethod
+ def create_default(
+ cls, model: BaseChatModel | None = None, *, engine_name: str
+ ) -> Optional["JournalReputationFilter"]:
+ """
+ Initializes a default configuration of the filter based on the settings.
+
+ Args:
+ model: Explicitly specify the LLM to use.
+ engine_name: The name of the search engine. Will be used to check
+ the enablement status for that engine.
+
+ Returns:
+ The filter that it created, or None if filtering is disabled in
+ the settings, or misconfigured.
+
+ """
+ if not bool(
+ get_db_setting(
+ f"search.engine.web.{engine_name}.journal_reputation.enabled",
+ True,
+ )
+ ):
+ return None
+
+ try:
+ # Initialize the filter with default settings.
+ return JournalReputationFilter(model=model)
+ except JournalFilterError:
+ logger.error(
+ "SearXNG is not configured, but is required for "
+ "journal reputation filtering. Disabling filtering."
+ )
+ return None
+
+ @lru_cache(maxsize=1024)
+ def __analyze_journal_reputation(self, journal_name: str) -> int:
+ """
+ Analyzes the reputation of a particular journal.
+
+ Args:
+ journal_name: The name of the journal.
+
+ Returns:
+ The reputation of the journal, on a scale from 1-10.
+
+ """
+ logger.info(f"Analyzing reputation of journal '{journal_name}'...")
+
+ # Perform a search for information about this journal.
+ journal_info = self.__search_system.analyze_topic(
+ f'Assess the reputability and reliability of the journal "'
+ f'{journal_name}", with a particular focus on its quartile '
+ f"ranking and peer review status. Be sure to specify the journal "
+ f"name in any generated questions."
+ )
+ journal_info = "\n".join([f["content"] for f in journal_info["findings"]])
+ logger.debug(f"Received raw info about journal: {journal_info}")
+
+ # Have the LLM assess the reliability based on this information.
+ prompt = f"""
+ You are a research assistant helping to assess the reliability and
+ reputability of scientific journals. A reputable journal should be
+ peer-reviewed, not predatory, and high-impact. Please review the
+ following information on the journal "{journal_name}" and output a
+ reputability score between 1 and 10, where 1-3 is not reputable and
+ probably predatory, 4-6 is reputable but low-impact (Q2 or Q3),
+ and 7-10 is reputable Q1 journals. Only output the number, do not
+ provide any explanation or other output.
+
+ JOURNAL INFORMATION:
+
+ {journal_info}
+ """
+ if len(prompt) > self.__max_context:
+ # If the prompt is too long, truncate it to fit within the max context size.
+ prompt = prompt[: self.__max_context] + "..."
+
+ # Generate a response from the LLM model.
+ response = self.model.invoke(prompt).text()
+ logger.debug(f"Got raw LLM response: {response}")
+
+ # Extract the score from the response.
+ try:
+ reputation_score = int(response.strip())
+ except ValueError:
+ logger.error("Failed to parse reputation score from LLM response.")
+ raise ValueError("Failed to parse reputation score from LLM response.")
+
+ return max(min(reputation_score, 10), 1)
+
+ def __check_result(self, result: Dict[str, Any]) -> bool:
+ """
+ Checks a single result to see if the journal is reputable.
+
+ Args:
+ result: The result to check.
+
+ Returns:
+ True if the journal is reputable or if it couldn't determine a
+ reputability score, false otherwise.
+
+ """
+ journal_name = result.get("journal_ref")
+ if journal_name is None:
+ logger.debug(
+ f"Result {result.get('title')} has no associated "
+ f"journal, not evaluating reputation."
+ )
+ return not self.__exclude_non_published
+ # Basic filtering: sometimes the journal ref includes volume and page
+ # information.
+ journal_name = journal_name.split(",")[0]
+
+ # Evaluate reputation.
+ try:
+ return self.__analyze_journal_reputation(journal_name) >= self.__threshold
+ except ValueError:
+ # The LLM behaved weirdly. In this case, we will just assume it's
+ # okay.
+ return True
+
+ def filter_results(self, results: List[Dict], query: str, **kwargs) -> List[Dict]:
+ return list(filter(self.__check_result, results))
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index 96d71bef20..80b4954a32 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -638,6 +638,48 @@
"value": false,
"visible": true
},
+ "search.journal_reputation.threshold": {
+ "category": "journal_quality_filter_parameters",
+ "description": "If enabled, journals with quality scores (scale from 1-10) below this threshold will be filtered out.",
+ "editable": true,
+ "max_value": 10,
+ "min_value": 1,
+ "name": "Journal Quality Threshold",
+ "options": null,
+ "step": 1,
+ "type": "SEARCH",
+ "ui_element": "range",
+ "value": 4,
+ "visible": true
+ },
+ "search.journal_reputation.max_context": {
+ "category": "journal_quality_filter_parameters",
+ "description": "Maximum number of characters to include in the prompt for journal quality checking.",
+ "editable": true,
+ "max_value": 1000000,
+ "min_value": 500,
+ "name": "Journal Quality Context Size",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "number",
+ "value": 3000,
+ "visible": true
+ },
+ "search.journal_reputation.exclude_non_published": {
+ "category": "journal_quality_filter_parameters",
+ "description": "If true, quality filtering will exclude results that do not have a published journal reference.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Exclude Non-Published Results",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": 3000,
+ "visible": true
+ },
"search.snippets_only": {
"category": "search_parameters",
"description": "Only retrieve snippets instead of full search results",
@@ -792,6 +834,20 @@
"value": "ArXivSearchEngine",
"visible": true
},
+ "search.engine.web.arxiv.journal_reputation.enabled": {
+ "category": "arxiv",
+ "description": "Enable journal quality filtering for this search engine.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Filter Low-Quality Journals",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
+ },
"search.engine.web.arxiv.default_params.max_results": {
"category": "arxiv",
"description": "Setting for arxiv.default_params.max_results",
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index 5f8f92bc44..0bf425b05f 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -38,6 +38,8 @@ class AdvancedSearchSystem:
use_cross_engine_filter: bool = True,
llm: BaseChatModel | None = None,
search: BaseSearchEngine | None = None,
+ max_iterations: int | None = None,
+ questions_per_iteration: int | None = None,
):
"""Initialize the advanced search system.
@@ -49,6 +51,11 @@ class AdvancedSearchSystem:
llm: LLM to use. If not provided, it will use the default one.
search: Search engine to use. If not provided, it will use the
default one.
+ max_iterations: The maximum number of search iterations to
+ perform. Will be read from the settings if not specified.
+ questions_per_iteration: The number of questions to include in
+ each iteration. Will be read from the settings if not specified.
+
"""
# Get configuration
self.model = llm
@@ -59,11 +66,14 @@ class AdvancedSearchSystem:
self.search = get_search(llm_instance=self.model)
# Get iterations setting
- self.max_iterations = get_db_setting("search.iterations", 1)
-
- self.questions_per_iteration = get_db_setting(
- "search.questions_per_iteration", 3
- )
+ self.max_iterations = max_iterations
+ if self.max_iterations is None:
+ self.max_iterations = get_db_setting("search.iterations", 1)
+ self.questions_per_iteration = questions_per_iteration
+ if self.questions_per_iteration is None:
+ self.questions_per_iteration = get_db_setting(
+ "search.questions_per_iteration", 3
+ )
# Log the strategy name that's being used
logger.info(
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 5159ad3979..e853612c00 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
@@ -4,6 +4,9 @@ from typing import Any, Dict, List, Optional
import arxiv
from langchain_core.language_models import BaseLLM
+from ...advanced_search_system.filters.journal_reputation_filter import (
+ JournalReputationFilter,
+)
from ...config import search_config
from ..search_engine_base import BaseSearchEngine
@@ -37,9 +40,22 @@ class ArXivSearchEngine(BaseSearchEngine):
llm: Language model for relevance filtering
max_filtered_results: Maximum number of results to keep after filtering
"""
+ # Initialize the journal reputation filter if needed.
+ content_filters = []
+ journal_filter = JournalReputationFilter.create_default(
+ model=llm, engine_name="arxiv"
+ )
+ if journal_filter is not None:
+ content_filters.append(journal_filter)
+
# 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
+ llm=llm,
+ max_filtered_results=max_filtered_results,
+ max_results=max_results,
+ # We deliberately do this filtering after relevancy checks,
+ # because it is potentially quite slow.
+ content_filters=content_filters,
)
self.max_results = max(self.max_results, 25)
self.sort_by = sort_by
@@ -133,6 +149,7 @@ class ArXivSearchEngine(BaseSearchEngine):
if paper.published
else None
),
+ "journal_ref": paper.journal_ref,
}
previews.append(preview)
@@ -203,7 +220,6 @@ class ArXivSearchEngine(BaseSearchEngine):
"categories": paper.categories,
"summary": paper.summary, # Full summary
"comment": paper.comment,
- "journal_ref": paper.journal_ref,
"doi": paper.doi,
}
)
@@ -349,6 +365,7 @@ class ArXivSearchEngine(BaseSearchEngine):
"authors": [
author.name for author in paper.authors[:3]
], # First 3 authors
+ "journal_ref": paper.journal_ref,
}
# Add full content if not in snippet-only mode
@@ -375,7 +392,6 @@ class ArXivSearchEngine(BaseSearchEngine):
"categories": paper.categories,
"summary": paper.summary, # Full summary
"comment": paper.comment,
- "journal_ref": paper.journal_ref,
"doi": paper.doi,
"content": paper.summary, # Use summary as content
"full_content": paper.summary, # For consistency
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 6c46743923..5368279c00 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
@@ -6,6 +6,7 @@ from typing import Any, Dict, List, Optional
from langchain_core.language_models import BaseLLM
+from ..advanced_search_system.filters.base_filter import BaseFilter
from ..config import search_config
logger = logging.getLogger(__name__)
@@ -22,6 +23,8 @@ class BaseSearchEngine(ABC):
llm: Optional[BaseLLM] = None,
max_filtered_results: Optional[int] = None,
max_results: Optional[int] = 10, # Default value if not provided
+ preview_filters: List[BaseFilter] | None = None,
+ content_filters: List[BaseFilter] | None = None,
**kwargs,
):
"""
@@ -31,12 +34,22 @@ class BaseSearchEngine(ABC):
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
+ preview_filters: Filters that will be applied to all previews
+ produced by the search engine, before relevancy checks.
+ content_filters: Filters that will be applied to the full content
+ produced by the search engine, after relevancy checks.
**kwargs: Additional engine-specific parameters
"""
if max_filtered_results is None:
max_filtered_results = 5
if max_results is None:
max_results = 10
+ self._preview_filters: List[BaseFilter] = preview_filters
+ if self._preview_filters is None:
+ self._preview_filters = []
+ self._content_filters: List[BaseFilter] = content_filters
+ if self._content_filters is None:
+ self._content_filters = []
self.llm = llm # LLM for relevance filtering
self._max_filtered_results = int(max_filtered_results) # Ensure it's an integer
@@ -91,6 +104,9 @@ class BaseSearchEngine(ABC):
)
return []
+ for preview_filter in self._preview_filters:
+ previews = preview_filter.filter_results(previews, query)
+
# Step 2: Filter previews for relevance with LLM
filtered_items = self._filter_for_relevance(previews, query)
if not filtered_items:
@@ -112,6 +128,9 @@ class BaseSearchEngine(ABC):
else:
results = self._get_full_content(filtered_items)
+ for content_filter in self._content_filters:
+ results = content_filter.filter_results(results, query)
+
return results
def invoke(self, query: str) -> List[Dict[str, Any]]: