~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
refactor: Address code review feedback from djpetti
LearningCircuit120685cb1e34
diff --git a/src/local_deep_research/advanced_search_system/filters/followup_relevance_filter.py b/src/local_deep_research/advanced_search_system/filters/followup_relevance_filter.pyindex c0f84273c0..b183430d27 100644--- a/src/local_deep_research/advanced_search_system/filters/followup_relevance_filter.py+++ b/src/local_deep_research/advanced_search_system/filters/followup_relevance_filter.py@@ -21,7 +21,7 @@ class FollowUpRelevanceFilter(BaseFilter):"""def filter_results(- self, results: List[Dict], query: str, **kwargs+ self, results: List[Dict], query: str, max_results: int = 10, **kwargs) -> List[Dict]:"""Filter search results by relevance to the follow-up query.@@ -29,8 +29,8 @@ class FollowUpRelevanceFilter(BaseFilter):Args:results: List of source dictionaries from past researchquery: The follow-up query+ max_results: Maximum number of results to return (default: 10)**kwargs: Additional parameters:- - max_results: Maximum number of results to return- past_findings: Summary of past findings for context- original_query: The original research query@@ -40,7 +40,6 @@ class FollowUpRelevanceFilter(BaseFilter):if not results:return []- max_results = kwargs.get("max_results", 10)past_findings = kwargs.get("past_findings", "")original_query = kwargs.get("original_query", "")@@ -126,20 +125,38 @@ Instructions:- Select sources that are most relevant to the follow-up question given the context- Consider which sources directly address the question or provide essential information- Think about what the user is asking for in relation to the previous findings-- Return ONLY a comma-separated list of source numbers (e.g., "0,2,5,7")+- Return ONLY a JSON array of source numbers (e.g., [0, 2, 5, 7])- Do not include any explanation or other text-Return the indices of relevant sources:"""+Return the indices of relevant sources as a JSON array:"""try:response = self.model.invoke(prompt)content = remove_think_tags(response.content).strip()- # Extract numbers from response- import re-- numbers = re.findall(r"\d+", content)- indices = [int(n) for n in numbers if int(n) < len(sources)]+ # Parse JSON response+ import json++ try:+ indices = json.loads(content)+ # Validate it's a list of integers+ if not isinstance(indices, list):+ raise ValueError("Response is not a list")+ indices = [+ int(i)+ for i in indices+ if isinstance(i, (int, float)) and int(i) < len(sources)+ ]++ except (json.JSONDecodeError, ValueError) as parse_error:+ logger.debug(+ f"Failed to parse JSON, attempting regex fallback: {parse_error}"+ )+ # Fallback to regex extraction+ import re++ numbers = re.findall(r"\d+", content)+ indices = [int(n) for n in numbers if int(n) < len(sources)]return indicesexcept Exception as e:diff --git a/src/local_deep_research/advanced_search_system/knowledge/followup_context_manager.py b/src/local_deep_research/advanced_search_system/knowledge/followup_context_manager.pyindex 6e65d3690c..b16ed023d7 100644--- a/src/local_deep_research/advanced_search_system/knowledge/followup_context_manager.py+++ b/src/local_deep_research/advanced_search_system/knowledge/followup_context_manager.py@@ -13,7 +13,7 @@ from langchain_core.language_models.chat_models import BaseChatModelfrom ...utilities.search_utilities import remove_think_tags-class FollowUpContextManager:+class FollowUpContextHandler:"""Manages past research context for follow-up research.diff --git a/src/local_deep_research/advanced_search_system/strategies/followup/enhanced_contextual_followup.py b/src/local_deep_research/advanced_search_system/strategies/followup/enhanced_contextual_followup.pyindex c305e875ba..c21144ef9c 100644--- a/src/local_deep_research/advanced_search_system/strategies/followup/enhanced_contextual_followup.py+++ b/src/local_deep_research/advanced_search_system/strategies/followup/enhanced_contextual_followup.py@@ -10,7 +10,7 @@ from loguru import loggerfrom ..base_strategy import BaseSearchStrategyfrom ...filters.followup_relevance_filter import FollowUpRelevanceFilter-from ...knowledge.followup_context_manager import FollowUpContextManager+from ...knowledge.followup_context_manager import FollowUpContextHandlerclass EnhancedContextualFollowUpStrategy(BaseSearchStrategy):@@ -54,7 +54,7 @@ class EnhancedContextualFollowUpStrategy(BaseSearchStrategy):# Initialize componentsself.relevance_filter = FollowUpRelevanceFilter(model)- self.context_manager = FollowUpContextManager(model)+ self.context_manager = FollowUpContextHandler(model)# For follow-up research, we ALWAYS want to combine sources# This is the whole point of follow-up - building on previous researchdiff --git a/src/local_deep_research/web/utils/formatters.py b/src/local_deep_research/web/utils/formatters.pyindex f80f364319..a01608a94d 100644--- a/src/local_deep_research/web/utils/formatters.py+++ b/src/local_deep_research/web/utils/formatters.py@@ -47,28 +47,6 @@ def convert_debug_to_markdown(raw_text, query):# Keep SEARCH QUESTIONS BY ITERATION section - it's useful information# Previously this was being removed, but users want to see the iteration questions- # if "SEARCH QUESTIONS BY ITERATION:" in content:- # logger.info("Found SEARCH QUESTIONS BY ITERATION section")- # search_index = content.index("SEARCH QUESTIONS BY ITERATION:")- # next_major_section = -1- # for marker in ["DETAILED FINDINGS:", "COMPLETE RESEARCH:"]:- # if marker in content[search_index:]:- # marker_pos = content.index(marker, search_index)- # if (- # next_major_section == -1- # or marker_pos < next_major_section- # ):- # next_major_section = marker_pos-- # if next_major_section != -1:- # logger.info(- # f"Removing section from index {search_index} to {next_major_section}"- # )- # content = content[:search_index] + content[next_major_section:]- # else:- # # If no later section, just remove everything from SEARCH QUESTIONS onwards- # logger.info(f"Removing everything after index {search_index}")- # content = content[:search_index].strip()logger.info(f"Final markdown length: {len(content.strip())}")return content.strip()diff --git a/tests/test_followup_manual.py b/tests/test_followup_manual.pydeleted file mode 100644index dbf317a04f..0000000000--- a/tests/test_followup_manual.py+++ /dev/null@@ -1,77 +0,0 @@-#!/usr/bin/env python3-"""-Manual test script for follow-up research feature.-Run this after starting the server to verify the API works.-"""--import requests-import json--BASE_URL = "http://127.0.0.1:5000"---def test_followup_api():- """Test the follow-up research API endpoints."""-- # Create a session to maintain cookies- session = requests.Session()-- print("🔐 Testing authentication...")- # First, try to login (or register if needed)- auth_response = session.post(- f"{BASE_URL}/auth/login",- data={"username": "testuser", "password": "T3st!Secure#2024$LDR"},- )-- if auth_response.status_code == 302: # Redirect after successful login- print("✅ Authenticated successfully")- else:- print(f"⚠️ Auth returned status: {auth_response.status_code}")- # Try registration- reg_response = session.post(- f"{BASE_URL}/auth/register",- data={- "username": "testuser",- "password": "T3st!Secure#2024$LDR",- "confirm_password": "T3st!Secure#2024$LDR",- "acknowledge": "on",- },- )- if reg_response.status_code == 302:- print("✅ Registered and authenticated")- else:- print(f"❌ Registration failed: {reg_response.status_code}")- return-- print("\n📝 Testing /api/followup/prepare endpoint...")-- # Test with a dummy parent research ID- prepare_data = {- "parent_research_id": "test-parent-id",- "question": "How does this work in more detail?",- }-- prepare_response = session.post(- f"{BASE_URL}/api/followup/prepare",- json=prepare_data,- headers={"Content-Type": "application/json"},- )-- print(f"Response status: {prepare_response.status_code}")- if prepare_response.status_code == 200:- print(f"Response data: {json.dumps(prepare_response.json(), indent=2)}")- else:- print(f"Response text: {prepare_response.text[:500]}")-- print("\n✅ API endpoint is accessible!")-- # Test if the button exists on a results page- print("\n🔍 Checking if follow-up button exists on UI...")- # This would require actually having a completed research, so we'll skip for now- print("⚠️ Skipping UI check (requires completed research)")-- print("\n🎉 Follow-up research API test completed!")---if __name__ == "__main__":- test_followup_api()