~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
fix: Address remaining code review feedback from djpetti
LearningCircuit01a970947326
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 b16ed023d7..78415ae3e1 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@@ -6,7 +6,7 @@ This is a standalone class that doesn't inherit from BaseKnowledgeGeneratorto avoid implementing many abstract methods."""-from typing import Dict, List, Any+from typing import Dict, List, Any, Optionalfrom loguru import loggerfrom langchain_core.language_models.chat_models import BaseChatModel@@ -24,16 +24,58 @@ class FollowUpContextHandler:4. Building comprehensive context for strategies"""- def __init__(self, model: BaseChatModel):+ def __init__(+ self, model: BaseChatModel, settings_snapshot: Optional[Dict] = None+ ):"""Initialize the context manager.Args:model: Language model for processing context+ settings_snapshot: Optional settings snapshot for context window info"""self.model = model+ self.settings_snapshot = settings_snapshot or {}self.past_research_cache = {}+ # Get context window size from settings+ self._context_window = self._get_context_window_size()++ def _get_context_window_size(self) -> int:+ """+ Get the context window size based on provider and settings.++ Returns:+ Context window size in characters (approx 4 chars per token)+ """+ # Try to get from settings snapshot+ provider = self.settings_snapshot.get("llm", {}).get(+ "provider", "openai"+ )++ if provider in ["ollama", "llamacpp", "lmstudio"]:+ # Local providers: smaller default+ window_tokens = self.settings_snapshot.get("llm", {}).get(+ "local_context_window_size", 4096+ )+ else:+ # Cloud providers+ if self.settings_snapshot.get("llm", {}).get(+ "context_window_unrestricted", True+ ):+ # Unrestricted mode: use large default+ window_tokens = 128000+ else:+ # User-specified limit+ window_tokens = self.settings_snapshot.get("llm", {}).get(+ "context_window_size", 128000+ )++ # Convert tokens to approximate character count (4 chars per token)+ # Reserve 20% for prompt and response overhead+ usable_tokens = int(window_tokens * 0.8)+ return usable_tokens * 4+def build_context(self, research_data: Dict[str, Any], follow_up_query: str) -> Dict[str, Any]:@@ -92,9 +134,12 @@ class FollowUpContextHandler:combined = "\n\n".join(findings_parts)- # Truncate if too long- if len(combined) > 5000:- combined = combined[:5000] + "..."+ # Truncate based on context window size+ max_findings_chars = min(+ self._context_window // 4, 20000+ ) # Use 1/4 of context for findings+ if len(combined) > max_findings_chars:+ combined = combined[:max_findings_chars] + "..."return combined@@ -165,39 +210,27 @@ Return up to 10 most important entities, one per line.def _create_summary(self, research_data: Dict, follow_up_query: str) -> str:"""- Create a targeted summary relevant to the follow-up question.+ Create a targeted summary of past research relevant to the follow-up question.+ This is used internally for building context.Args:research_data: Past research datafollow_up_query: The follow-up questionReturns:- Targeted summary+ Targeted summary for context building"""findings = self._extract_findings(research_data)original_query = research_data.get("query", "")- if not findings or not self.model:- return findings[:500] if findings else ""-- prompt = f"""-Create a brief summary of previous research findings that are relevant to this follow-up question:--Original research question: "{original_query}"-Follow-up question: "{follow_up_query}"--Previous findings:-{findings[:3000]}--Provide a 3-5 sentence summary focusing on aspects relevant to the follow-up question.-"""-- try:- response = self.model.invoke(prompt)- return remove_think_tags(response.content).strip()- except Exception as e:- logger.warning(f"Failed to create summary: {e}")- return findings[:500]+ # For internal context, create a brief targeted summary+ return self._generate_summary(+ findings=findings,+ query=follow_up_query,+ original_query=original_query,+ max_sentences=5,+ purpose="context",+ )def _extract_metadata(self, research_data: Dict) -> Dict:"""@@ -220,26 +253,79 @@ Provide a 3-5 sentence summary focusing on aspects relevant to the follow-up queself, findings: str, query: str, max_length: int = 1000) -> str:"""- Create a concise summary of findings for follow-up research.+ Create a concise summary of findings for external use (e.g., in prompts).+ This creates a length-constrained summary suitable for inclusion in LLM prompts.Args:findings: Past research findingsquery: Follow-up query- max_length: Maximum length of summary+ max_length: Maximum length of summary in characters++ Returns:+ Concise summary constrained to max_length+ """+ # Use the shared summary generation with specific parameters for external use+ return self._generate_summary(+ findings=findings,+ query=query,+ original_query=None,+ max_sentences=max_length+ // 100, # Approximate sentences based on length+ purpose="prompt",+ max_length=max_length,+ )++ def _generate_summary(+ self,+ findings: str,+ query: str,+ original_query: Optional[str] = None,+ max_sentences: int = 5,+ purpose: str = "context",+ max_length: Optional[int] = None,+ ) -> str:+ """+ Shared summary generation logic.++ Args:+ findings: Research findings to summarize+ query: Follow-up query+ original_query: Original research query (optional)+ max_sentences: Maximum number of sentences+ purpose: Purpose of summary ("context" or "prompt")+ max_length: Maximum character length (optional)Returns:- Concise summary+ Generated summary"""if not findings:return ""- if len(findings) <= max_length:+ # If findings are already short enough, return as-is+ if max_length and len(findings) <= max_length:return findingsif not self.model:- return findings[:max_length] + "..."+ # Fallback without model+ if max_length:+ return findings[:max_length] + "..."+ return findings[:500] + "..."++ # Build prompt based on purpose+ if purpose == "context" and original_query:+ prompt = f"""+Create a brief summary of previous research findings that are relevant to this follow-up question:- prompt = f"""+Original research question: "{original_query}"+Follow-up question: "{query}"++Previous findings:+{findings[:3000]}++Provide a {max_sentences}-sentence summary focusing on aspects relevant to the follow-up question.+"""+ else:+ prompt = f"""Summarize these research findings in relation to the follow-up question:Follow-up question: "{query}"@@ -247,18 +333,24 @@ Follow-up question: "{query}"Findings:{findings[:4000]}-Create a summary of {max_length // 100} sentences that captures the most relevant information.+Create a summary of {max_sentences} sentences that captures the most relevant information."""try:response = self.model.invoke(prompt)summary = remove_think_tags(response.content).strip()- if len(summary) > max_length:++ # Apply length constraint if specified+ if max_length and len(summary) > max_length:summary = summary[:max_length] + "..."+return summaryexcept Exception as e:- logger.warning(f"Summarization failed: {e}")- return findings[:max_length] + "..."+ logger.warning(f"Summary generation failed: {e}")+ # Fallback to truncation+ if max_length:+ return findings[:max_length] + "..."+ return findings[:500] + "..."def identify_gaps(self, research_data: Dict, follow_up_query: str@@ -308,23 +400,21 @@ What specific information is missing or needs clarification? List up to 5 gaps,) -> Dict[str, Any]:"""Format context for inclusion in settings snapshot.+ Only includes essential metadata, not actual content.Args:context: Full context dictionaryReturns:- Formatted context for settings snapshot+ Minimal metadata for settings snapshot"""+ # Only include minimal metadata in settings snapshot+ # Settings snapshot should be for settings, not datareturn {- "followup_context": {+ "followup_metadata": {"parent_research_id": context.get("parent_research_id"),- "original_query": context.get("original_query"),- "follow_up_query": context.get("follow_up_query"),- "summary": context.get("summary"),- "key_entities": context.get("key_entities", []),- "past_sources_count": len(context.get("past_sources", [])),- "has_findings": bool(context.get("past_findings")),- "metadata": context.get("metadata", {}),+ "is_followup": True,+ "has_context": bool(context.get("past_findings")),}}diff --git a/src/local_deep_research/web/static/js/components/settings_sync.js b/src/local_deep_research/web/static/js/components/settings_sync.jsindex 5544d6c9bb..45d373e6aa 100644--- a/src/local_deep_research/web/static/js/components/settings_sync.js+++ b/src/local_deep_research/web/static/js/components/settings_sync.js@@ -80,8 +80,22 @@ function connectMenuSettings() {});}- // Iterations and questions are now only configured in Settings page- // No longer synced from research form+ // Handle iterations and questions per iteration+ const iterationsInput = document.getElementById('iterations');+ if (iterationsInput) {+ iterationsInput.addEventListener('change', function(e) {+ console.log('Iterations changed to:', this.value);+ saveMenuSettings('search.iterations', this.value);+ });+ }++ const questionsInput = document.getElementById('questions_per_iteration');+ if (questionsInput) {+ questionsInput.addEventListener('change', function(e) {+ console.log('Questions per iteration changed to:', this.value);+ saveMenuSettings('search.questions_per_iteration', this.value);+ });+ }console.log('Menu settings handlers initialized');}diff --git a/src/local_deep_research/web/static/js/followup.js b/src/local_deep_research/web/static/js/followup.jsindex 803a63e5a0..2b7b496843 100644--- a/src/local_deep_research/web/static/js/followup.js+++ b/src/local_deep_research/web/static/js/followup.js@@ -71,12 +71,27 @@ class FollowUpResearch {/*** Create modal for follow-up questions*/- createModal() {+ async createModal() {// Check if modal already existsif (document.getElementById('followUpModal')) {return;}+ // Try to load modal template from server+ try {+ const response = await fetch('/static/templates/followup_modal.html');+ if (response.ok) {+ const modalHtml = await response.text();+ document.body.insertAdjacentHTML('beforeend', modalHtml);+ this.modalElement = document.getElementById('followUpModal');+ this.attachModalEventHandlers();+ return;+ }+ } catch (e) {+ console.debug('Could not load modal template, using inline HTML');+ }++ // Fallback to inline HTML if template not availableconst modalHtml = `<div class="modal fade" id="followUpModal" tabindex="-1" aria-labelledby="followUpModalLabel" aria-hidden="true" style="z-index: 10000;"><div class="modal-dialog modal-lg modal-dialog-centered">@@ -130,7 +145,24 @@ class FollowUpResearch {// Add modal to pagedocument.body.insertAdjacentHTML('beforeend', modalHtml);this.modalElement = document.getElementById('followUpModal');+ this.attachModalEventHandlers();+ this.addModalStyles();+ }++ /**+ * Attach event handlers to modal elements+ */+ attachModalEventHandlers() {+ const startBtn = document.getElementById('startFollowUpBtn');+ if (startBtn) {+ startBtn.addEventListener('click', () => this.submitFollowUp());+ }+ }+ /**+ * Add modal styles if needed+ */+ addModalStyles() {// Add custom CSS if neededif (!document.getElementById('followup-modal-styles')) {const styles = `diff --git a/src/local_deep_research/web/templates/components/followup_modal.html b/src/local_deep_research/web/templates/components/followup_modal.htmlnew file mode 100644index 0000000000..bc3ccb7bcb--- /dev/null+++ b/src/local_deep_research/web/templates/components/followup_modal.html@@ -0,0 +1,42 @@+<!-- Follow-up Research Modal -->+<div class="modal fade" id="followUpModal" tabindex="-1" aria-labelledby="followUpModalLabel" aria-hidden="true" style="z-index: 10000;">+ <div class="modal-dialog modal-lg">+ <div class="modal-content">+ <div class="modal-header">+ <h5 class="modal-title" id="followUpModalLabel">Follow-up Research</h5>+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>+ </div>+ <div class="modal-body">+ <p class="mb-3">Ask a follow-up question based on your previous research. This will use the context and sources from your last research to provide more focused results.</p>++ <div class="mb-3">+ <strong>Examples of good follow-up questions:</strong>+ <ul class="mt-2">+ <li>"Can you provide more details about the implementation challenges?"</li>+ <li>"What are the specific costs mentioned in the findings?"</li>+ <li>"How does this compare to alternative approaches?"</li>+ <li>"What are the long-term implications of these results?"</li>+ </ul>+ </div>++ <form id="followUpForm">+ <div class="mb-3">+ <label for="followUpQuestion" class="form-label">Your follow-up question:</label>+ <textarea class="form-control" id="followUpQuestion" rows="3" placeholder="Enter your follow-up question..." required></textarea>+ </div>++ <div class="form-check mb-3">+ <input class="form-check-input" type="checkbox" id="reuseSourcesCheckbox" checked>+ <label class="form-check-label" for="reuseSourcesCheckbox">+ Use sources from previous research+ </label>+ </div>+ </form>+ </div>+ <div class="modal-footer">+ <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>+ <button type="button" class="btn btn-primary" id="startFollowUpBtn">Start Follow-up Research</button>+ </div>+ </div>+ </div>+</div>diff --git a/src/local_deep_research/web/utils/formatters.py b/src/local_deep_research/web/utils/formatters.pyindex a01608a94d..674ad11a68 100644--- a/src/local_deep_research/web/utils/formatters.py+++ b/src/local_deep_research/web/utils/formatters.py@@ -45,9 +45,6 @@ def convert_debug_to_markdown(raw_text, query):lines_after = len(content.split("\n"))logger.info(f"Removed {lines_before - lines_after} divider lines")- # Keep SEARCH QUESTIONS BY ITERATION section - it's useful information- # Previously this was being removed, but users want to see the iteration questions-logger.info(f"Final markdown length: {len(content.strip())}")return content.strip()except Exception as e: