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.

complete follow-up research feature (#659)

LearningCircuit2c2a5708ad67
diff --git a/.github/workflows/followup-research-tests.yml b/.github/workflows/followup-research-tests.yml
new file mode 100644
index 0000000000..cfaf0f5127
--- /dev/null
+++ b/.github/workflows/followup-research-tests.yml
@@ -0,0 +1,127 @@
+name: Follow-up Research Tests
+
+on:
+ push:
+ paths:
+ - 'src/local_deep_research/followup_research/**'
+ - 'src/local_deep_research/advanced_search_system/strategies/contextual_followup_strategy.py'
+ - 'src/local_deep_research/search_system.py'
+ - 'tests/test_followup_api.py'
+ - 'tests/ui_tests/test_followup_research.js'
+ - '.github/workflows/followup-research-tests.yml'
+ pull_request:
+ types: [opened, synchronize, reopened]
+ paths:
+ - 'src/local_deep_research/followup_research/**'
+ - 'src/local_deep_research/advanced_search_system/strategies/contextual_followup_strategy.py'
+ - 'tests/test_followup_api.py'
+ - 'tests/ui_tests/test_followup_research.js'
+
+jobs:
+ test-followup-research:
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: '3.11'
+
+ - name: Install PDM
+ uses: pdm-project/setup-pdm@v3
+ with:
+ python-version: '3.11'
+ cache: true
+
+ - name: Install Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: '18'
+
+ - name: Install dependencies
+ run: |
+ pdm sync -d
+ cd tests/ui_tests && npm install
+
+ - name: Install browser
+ run: |
+ npx playwright install chromium
+
+ - name: Create test directories
+ run: |
+ mkdir -p data
+ mkdir -p tests/ui_tests/screenshots/followup
+ mkdir -p tests/ui_tests/results/followup
+
+ - name: Start server
+ run: |
+ export LDR_USE_FALLBACK_LLM=true
+ export PYTHONPATH=$PWD/src:$PYTHONPATH
+ pdm run python -m local_deep_research.web.app 2>&1 | tee server.log &
+ echo $! > server.pid
+
+ # Wait for server
+ for i in {1..30}; do
+ if curl -f http://localhost:5000/api/v1/health 2>/dev/null; then
+ echo "Server ready after $i seconds"
+ break
+ fi
+ echo "Waiting for server... ($i/30)"
+ sleep 1
+ done
+
+ # Final check
+ curl -f http://localhost:5000/api/v1/health || (echo "Server failed to start" && cat server.log && exit 1)
+
+ - name: Run API tests
+ run: |
+ pdm run pytest tests/test_followup_api.py -v --tb=short
+
+ - name: Run UI tests
+ env:
+ HEADLESS: true
+ DISPLAY: ':99'
+ run: |
+ export DISPLAY=:99
+ cd tests/ui_tests
+
+ # Run follow-up research UI test
+ timeout 300 node test_followup_research.js || {
+ echo "Follow-up research test failed or timed out"
+ exit 1
+ }
+
+ - name: Upload screenshots
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: followup-test-screenshots
+ path: tests/ui_tests/screenshots/followup/
+
+ - name: Upload test results
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: followup-test-results
+ path: |
+ tests/ui_tests/results/followup/
+ server.log
+
+ - name: Stop server
+ if: always()
+ run: |
+ if [ -f server.pid ]; then
+ kill $(cat server.pid) || true
+ fi
+
+ - name: Test Summary
+ if: always()
+ run: |
+ echo "Follow-up Research Tests completed"
+ echo "API tests and UI tests have been executed"
+ if [ -f tests/ui_tests/results/followup/test_report.json ]; then
+ cat tests/ui_tests/results/followup/test_report.json
+ fi
diff --git a/.gitignore b/.gitignore
index e42c03dd10..4dc5042d24 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,8 +5,7 @@
# Allow directories (needed for git to traverse)
!*/
-# Allow specific source code files
-!*.py
+# Allow specific source code files (but not .py in root - see below)
!*.js
!*.html
!*.css
@@ -18,6 +17,13 @@
!*.ipynb
!*.template
+# Allow Python files everywhere except root
+!**/*.py
+/*.py
+
+# Explicitly allow specific Python files in root that are needed
+# (Comment out any you don't need)
+
# Allow specific project files
!LICENSE
!README
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.py
new file mode 100644
index 0000000000..b183430d27
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/filters/followup_relevance_filter.py
@@ -0,0 +1,165 @@
+"""
+Follow-up Relevance Filter
+
+Filters and ranks past research sources based on their relevance
+to follow-up questions.
+"""
+
+from typing import Dict, List
+from loguru import logger
+
+from .base_filter import BaseFilter
+from ...utilities.search_utilities import remove_think_tags
+
+
+class FollowUpRelevanceFilter(BaseFilter):
+ """
+ Filters past research sources by relevance to follow-up questions.
+
+ This filter analyzes sources from previous research and determines
+ which ones are most relevant to the new follow-up question.
+ """
+
+ def filter_results(
+ self, results: List[Dict], query: str, max_results: int = 10, **kwargs
+ ) -> List[Dict]:
+ """
+ Filter search results by relevance to the follow-up query.
+
+ Args:
+ results: List of source dictionaries from past research
+ query: The follow-up query
+ max_results: Maximum number of results to return (default: 10)
+ **kwargs: Additional parameters:
+ - past_findings: Summary of past findings for context
+ - original_query: The original research query
+
+ Returns:
+ Filtered list of relevant sources
+ """
+ if not results:
+ return []
+
+ past_findings = kwargs.get("past_findings", "")
+ original_query = kwargs.get("original_query", "")
+
+ # Use LLM to select relevant sources
+ relevant_indices = self._select_relevant_sources(
+ results, query, past_findings, max_results, original_query
+ )
+
+ # Return selected sources
+ filtered = [results[i] for i in relevant_indices if i < len(results)]
+
+ logger.info(
+ f"Filtered {len(results)} sources to {len(filtered)} relevant ones "
+ f"for follow-up query. Kept indices: {relevant_indices}"
+ )
+
+ return filtered
+
+ def _select_relevant_sources(
+ self,
+ sources: List[Dict],
+ query: str,
+ context: str,
+ max_results: int,
+ original_query: str = "",
+ ) -> List[int]:
+ """
+ Select relevant sources using LLM.
+
+ Args:
+ sources: List of source dictionaries
+ query: The follow-up query
+ context: Past findings context
+ max_results: Maximum number of sources to select
+ original_query: The original research query
+
+ Returns:
+ List of indices of relevant sources
+ """
+ if not self.model:
+ # If no model available, return first max_results
+ return list(range(min(max_results, len(sources))))
+
+ # Build source list for LLM
+ source_list = []
+ for i, source in enumerate(sources):
+ title = source.get("title") or "Unknown"
+ url = source.get("url") or ""
+ snippet = (
+ source.get("snippet") or source.get("content_preview") or ""
+ )[:150]
+ source_list.append(
+ f"{i}. {title}\n URL: {url}\n Content: {snippet}"
+ )
+
+ sources_text = "\n\n".join(source_list)
+
+ # Include context if available for better selection
+ context_section = ""
+ if context or original_query:
+ parts = []
+ if original_query:
+ parts.append(f"Original research question: {original_query}")
+ if context:
+ parts.append(f"Previous research findings:\n{context}")
+
+ context_section = f"""
+Previous Research Context:
+{chr(10).join(parts)}
+
+---
+"""
+
+ prompt = f"""
+Select the most relevant sources for answering this follow-up question based on the previous research context.
+{context_section}
+Follow-up question: "{query}"
+
+Available sources from previous research:
+{sources_text}
+
+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 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 as a JSON array:"""
+
+ try:
+ response = self.model.invoke(prompt)
+ content = remove_think_tags(response.content).strip()
+
+ # 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 indices
+ except Exception as e:
+ logger.debug(f"LLM source selection failed: {e}")
+ # Fallback to first max_results sources
+ return list(range(min(max_results, len(sources))))
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.py
new file mode 100644
index 0000000000..6e75ff22a5
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/knowledge/followup_context_manager.py
@@ -0,0 +1,415 @@
+"""
+Follow-up Context Manager
+
+Manages and processes past research context for follow-up questions.
+This is a standalone class that doesn't inherit from BaseKnowledgeGenerator
+to avoid implementing many abstract methods.
+"""
+
+from typing import Dict, List, Any, Optional
+from loguru import logger
+
+from langchain_core.language_models.chat_models import BaseChatModel
+from ...utilities.search_utilities import remove_think_tags
+
+
+class FollowUpContextHandler:
+ """
+ Manages past research context for follow-up research.
+
+ This class handles:
+ 1. Loading and structuring past research data
+ 2. Summarizing findings for follow-up context
+ 3. Extracting relevant information for new searches
+ 4. Building comprehensive context for strategies
+ """
+
+ 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
+ """
+ self.model = model
+ self.settings_snapshot = settings_snapshot or {}
+ self.past_research_cache = {}
+
+ def build_context(
+ self, research_data: Dict[str, Any], follow_up_query: str
+ ) -> Dict[str, Any]:
+ """
+ Build comprehensive context from past research.
+
+ Args:
+ research_data: Past research data including findings, sources, etc.
+ follow_up_query: The follow-up question being asked
+
+ Returns:
+ Structured context dictionary for follow-up research
+ """
+ logger.info(f"Building context for follow-up: {follow_up_query}")
+
+ # Extract all components
+ context = {
+ "parent_research_id": research_data.get("research_id", ""),
+ "original_query": research_data.get("query", ""),
+ "follow_up_query": follow_up_query,
+ "past_findings": self._extract_findings(research_data),
+ "past_sources": self._extract_sources(research_data),
+ "key_entities": self._extract_entities(research_data),
+ "summary": self._create_summary(research_data, follow_up_query),
+ "report_content": research_data.get("report_content", ""),
+ "formatted_findings": research_data.get("formatted_findings", ""),
+ "all_links_of_system": research_data.get("all_links_of_system", []),
+ "metadata": self._extract_metadata(research_data),
+ }
+
+ return context
+
+ def _extract_findings(self, research_data: Dict) -> str:
+ """
+ Extract and format findings from past research.
+
+ Args:
+ research_data: Past research data
+
+ Returns:
+ Formatted findings string
+ """
+ findings_parts = []
+
+ # Check various possible locations for findings
+ if formatted := research_data.get("formatted_findings"):
+ findings_parts.append(formatted)
+
+ if report := research_data.get("report_content"):
+ # Take first part of report if no formatted findings
+ if not findings_parts:
+ findings_parts.append(report[:2000])
+
+ if not findings_parts:
+ return "No previous findings available"
+
+ combined = "\n\n".join(findings_parts)
+ return combined
+
+ def _extract_sources(self, research_data: Dict) -> List[Dict]:
+ """
+ Extract and structure sources from past research.
+
+ Args:
+ research_data: Past research data
+
+ Returns:
+ List of source dictionaries
+ """
+ sources = []
+ seen_urls = set()
+
+ # Check all possible source fields
+ for field in ["resources", "all_links_of_system", "past_links"]:
+ if field_sources := research_data.get(field, []):
+ for source in field_sources:
+ url = source.get("url", "")
+ # Avoid duplicates by URL
+ if url and url not in seen_urls:
+ sources.append(source)
+ seen_urls.add(url)
+ elif not url:
+ # Include sources without URLs (shouldn't happen but be safe)
+ sources.append(source)
+
+ return sources
+
+ def _extract_entities(self, research_data: Dict) -> List[str]:
+ """
+ Extract key entities from past research.
+
+ Args:
+ research_data: Past research data
+
+ Returns:
+ List of key entities
+ """
+ findings = self._extract_findings(research_data)
+
+ if not findings or not self.model:
+ return []
+
+ prompt = f"""
+Extract key entities (names, places, organizations, concepts) from these research findings:
+
+{findings[:2000]}
+
+Return up to 10 most important entities, one per line.
+"""
+
+ try:
+ response = self.model.invoke(prompt)
+ entities = [
+ line.strip()
+ for line in remove_think_tags(response.content)
+ .strip()
+ .split("\n")
+ if line.strip()
+ ]
+ return entities[:10]
+ except Exception as e:
+ logger.warning(f"Failed to extract entities: {e}")
+ return []
+
+ def _create_summary(self, research_data: Dict, follow_up_query: str) -> str:
+ """
+ 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 data
+ follow_up_query: The follow-up question
+
+ Returns:
+ Targeted summary for context building
+ """
+ findings = self._extract_findings(research_data)
+ original_query = research_data.get("query", "")
+
+ # 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:
+ """
+ Extract metadata from past research.
+
+ Args:
+ research_data: Past research data
+
+ Returns:
+ Metadata dictionary
+ """
+ return {
+ "strategy": research_data.get("strategy", ""),
+ "mode": research_data.get("mode", ""),
+ "created_at": research_data.get("created_at", ""),
+ "research_meta": research_data.get("research_meta", {}),
+ }
+
+ def summarize_for_followup(
+ self, findings: str, query: str, max_length: int = 1000
+ ) -> str:
+ """
+ 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 findings
+ query: Follow-up query
+ 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:
+ Generated summary
+ """
+ if not findings:
+ return ""
+
+ # If findings are already short enough, return as-is
+ if max_length and len(findings) <= max_length:
+ return findings
+
+ if not self.model:
+ # 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:
+
+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}"
+
+Findings:
+{findings[:4000]}
+
+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()
+
+ # Apply length constraint if specified
+ if max_length and len(summary) > max_length:
+ summary = summary[:max_length] + "..."
+
+ return summary
+ except Exception as e:
+ 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
+ ) -> List[str]:
+ """
+ Identify information gaps that the follow-up should address.
+
+ Args:
+ research_data: Past research data
+ follow_up_query: Follow-up question
+
+ Returns:
+ List of identified gaps
+ """
+ findings = self._extract_findings(research_data)
+
+ if not findings or not self.model:
+ return []
+
+ prompt = f"""
+Based on the previous research and the follow-up question, identify information gaps:
+
+Previous research findings:
+{findings[:2000]}
+
+Follow-up question: "{follow_up_query}"
+
+What specific information is missing or needs clarification? List up to 5 gaps, one per line.
+"""
+
+ try:
+ response = self.model.invoke(prompt)
+ gaps = [
+ line.strip()
+ for line in remove_think_tags(response.content)
+ .strip()
+ .split("\n")
+ if line.strip()
+ ]
+ return gaps[:5]
+ except Exception as e:
+ logger.warning(f"Failed to identify gaps: {e}")
+ return []
+
+ def format_for_settings_snapshot(
+ self, context: Dict[str, Any]
+ ) -> Dict[str, Any]:
+ """
+ Format context for inclusion in settings snapshot.
+ Only includes essential metadata, not actual content.
+
+ Args:
+ context: Full context dictionary
+
+ Returns:
+ Minimal metadata for settings snapshot
+ """
+ # Only include minimal metadata in settings snapshot
+ # Settings snapshot should be for settings, not data
+ return {
+ "followup_metadata": {
+ "parent_research_id": context.get("parent_research_id"),
+ "is_followup": True,
+ "has_context": bool(context.get("past_findings")),
+ }
+ }
+
+ def get_relevant_context_for_llm(
+ self, context: Dict[str, Any], max_tokens: int = 2000
+ ) -> str:
+ """
+ Get a concise version of context for LLM prompts.
+
+ Args:
+ context: Full context dictionary
+ max_tokens: Approximate maximum tokens
+
+ Returns:
+ Concise context string
+ """
+ parts = []
+
+ # Add original and follow-up queries
+ parts.append(f"Original research: {context.get('original_query', '')}")
+ parts.append(
+ f"Follow-up question: {context.get('follow_up_query', '')}"
+ )
+
+ # Add summary
+ if summary := context.get("summary"):
+ parts.append(f"\nPrevious findings summary:\n{summary}")
+
+ # Add key entities
+ if entities := context.get("key_entities"):
+ parts.append(f"\nKey entities: {', '.join(entities[:5])}")
+
+ # Add source count
+ if sources := context.get("past_sources"):
+ parts.append(f"\nAvailable sources: {len(sources)}")
+
+ result = "\n".join(parts)
+
+ # Truncate if needed (rough approximation: 4 chars per token)
+ max_chars = max_tokens * 4
+ if len(result) > max_chars:
+ result = result[:max_chars] + "..."
+
+ return result
diff --git a/src/local_deep_research/advanced_search_system/questions/followup/__init__.py b/src/local_deep_research/advanced_search_system/questions/followup/__init__.py
new file mode 100644
index 0000000000..e29c8f3e90
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/questions/followup/__init__.py
@@ -0,0 +1,14 @@
+"""
+Follow-up Question Generators Package
+
+This package contains specialized question generators for follow-up research
+that builds upon previous research context.
+"""
+
+from .base_followup_question import BaseFollowUpQuestionGenerator
+from .simple_followup_question import SimpleFollowUpQuestionGenerator
+
+__all__ = [
+ "BaseFollowUpQuestionGenerator",
+ "SimpleFollowUpQuestionGenerator",
+]
diff --git a/src/local_deep_research/advanced_search_system/questions/followup/base_followup_question.py b/src/local_deep_research/advanced_search_system/questions/followup/base_followup_question.py
new file mode 100644
index 0000000000..da4717849b
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/questions/followup/base_followup_question.py
@@ -0,0 +1,91 @@
+"""
+Base class for follow-up question generators.
+
+This extends the standard question generator interface to handle
+follow-up research that includes previous research context.
+"""
+
+from abc import abstractmethod
+from typing import Dict, List
+from ..base_question import BaseQuestionGenerator
+
+
+class BaseFollowUpQuestionGenerator(BaseQuestionGenerator):
+ """
+ Abstract base class for follow-up question generators.
+
+ These generators create contextualized queries that incorporate
+ previous research findings and context.
+ """
+
+ def __init__(self, model):
+ """
+ Initialize the follow-up question generator.
+
+ Args:
+ model: The language model to use for question generation
+ """
+ super().__init__(model)
+ self.follow_up_context = {}
+
+ def set_follow_up_context(self, context: Dict):
+ """
+ Set the follow-up research context.
+
+ Args:
+ context: Dictionary containing:
+ - past_findings: Previous research findings
+ - original_query: The original research query
+ - follow_up_query: The follow-up question from user
+ - past_sources: Sources from previous research
+ - key_entities: Key entities identified
+ """
+ self.follow_up_context = context
+
+ @abstractmethod
+ def generate_contextualized_query(
+ self,
+ follow_up_query: str,
+ original_query: str,
+ past_findings: str,
+ **kwargs,
+ ) -> str:
+ """
+ Generate a contextualized query for follow-up research.
+
+ Args:
+ follow_up_query: The user's follow-up question
+ original_query: The original research query
+ past_findings: The findings from previous research
+ **kwargs: Additional context parameters
+
+ Returns:
+ str: A contextualized query that includes previous context
+ """
+ pass
+
+ def generate_questions(
+ self,
+ current_knowledge: str,
+ query: str,
+ questions_per_iteration: int,
+ questions_by_iteration: Dict[int, List[str]],
+ ) -> List[str]:
+ """
+ Generate questions for follow-up research.
+
+ For follow-up research, we typically return a single contextualized
+ query rather than multiple questions, as the context is already rich.
+
+ Args:
+ current_knowledge: The accumulated knowledge so far
+ query: The research query (already contextualized)
+ questions_per_iteration: Number of questions to generate
+ questions_by_iteration: Previous questions
+
+ Returns:
+ List[str]: List containing the contextualized query
+ """
+ # For follow-up research, the query is already contextualized
+ # Just return it as a single-item list
+ return [query]
diff --git a/src/local_deep_research/advanced_search_system/questions/followup/llm_followup_question.py b/src/local_deep_research/advanced_search_system/questions/followup/llm_followup_question.py
new file mode 100644
index 0000000000..46ec68c7c6
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/questions/followup/llm_followup_question.py
@@ -0,0 +1,93 @@
+"""
+LLM-based follow-up question generator.
+
+This implementation uses an LLM to intelligently reformulate follow-up
+questions based on the previous research context.
+"""
+
+from typing import Dict, List
+from loguru import logger
+from .base_followup_question import BaseFollowUpQuestionGenerator
+
+
+class LLMFollowUpQuestionGenerator(BaseFollowUpQuestionGenerator):
+ """
+ LLM-based follow-up question generator.
+
+ This generator uses an LLM to reformulate follow-up questions
+ based on the previous research context, creating more targeted
+ and effective search queries.
+
+ NOTE: This is a placeholder for future implementation.
+ Currently falls back to simple concatenation.
+ """
+
+ def generate_contextualized_query(
+ self,
+ follow_up_query: str,
+ original_query: str,
+ past_findings: str,
+ **kwargs,
+ ) -> str:
+ """
+ Generate a contextualized query using LLM reformulation.
+
+ Future implementation will:
+ 1. Analyze the follow-up query in context of past findings
+ 2. Identify information gaps
+ 3. Reformulate for more effective searching
+ 4. Generate multiple targeted search questions
+
+ Args:
+ follow_up_query: The user's follow-up question
+ original_query: The original research query
+ past_findings: The findings from previous research
+ **kwargs: Additional context parameters
+
+ Returns:
+ str: An LLM-reformulated contextualized query
+ """
+ # TODO: Implement LLM-based reformulation
+ # For now, fall back to simple concatenation
+ logger.warning(
+ "LLM-based follow-up question generation not yet implemented, "
+ "falling back to simple concatenation"
+ )
+
+ from .simple_followup_question import SimpleFollowUpQuestionGenerator
+
+ simple_generator = SimpleFollowUpQuestionGenerator(self.model)
+ return simple_generator.generate_contextualized_query(
+ follow_up_query, original_query, past_findings, **kwargs
+ )
+
+ def generate_questions(
+ self,
+ current_knowledge: str,
+ query: str,
+ questions_per_iteration: int,
+ questions_by_iteration: Dict[int, List[str]],
+ ) -> List[str]:
+ """
+ Generate multiple targeted questions for follow-up research.
+
+ Future implementation will generate multiple specific questions
+ based on the follow-up query and context.
+
+ Args:
+ current_knowledge: The accumulated knowledge so far
+ query: The research query
+ questions_per_iteration: Number of questions to generate
+ questions_by_iteration: Previous questions
+
+ Returns:
+ List[str]: List of targeted follow-up questions
+ """
+ # TODO: Implement multi-question generation
+ # For now, return single contextualized query
+ return super().generate_questions(
+ current_knowledge,
+ query,
+ questions_per_iteration,
+ questions_by_iteration,
+ )
diff --git a/src/local_deep_research/advanced_search_system/questions/followup/simple_followup_question.py b/src/local_deep_research/advanced_search_system/questions/followup/simple_followup_question.py
new file mode 100644
index 0000000000..c3e2e9319a
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/questions/followup/simple_followup_question.py
@@ -0,0 +1,65 @@
+"""
+Simple concatenation-based follow-up question generator.
+
+This implementation preserves the current behavior of concatenating
+the previous research context with the follow-up query without using
+an LLM to reformulate.
+"""
+
+from loguru import logger
+from .base_followup_question import BaseFollowUpQuestionGenerator
+
+
+class SimpleFollowUpQuestionGenerator(BaseFollowUpQuestionGenerator):
+ """
+ Simple follow-up question generator that concatenates context.
+
+ This generator creates a contextualized query by directly concatenating
+ the previous research findings with the follow-up question, without
+ any LLM-based reformulation. This ensures the follow-up query is
+ understood in the context of previous research.
+ """
+
+ def generate_contextualized_query(
+ self,
+ follow_up_query: str,
+ original_query: str,
+ past_findings: str,
+ **kwargs,
+ ) -> str:
+ """
+ Generate a contextualized query by simple concatenation.
+
+ This method preserves the exact user query while providing full
+ context from previous research. This ensures queries like
+ "provide data in a table" are understood as referring to the
+ previous findings, not as new searches.
+
+ Args:
+ follow_up_query: The user's follow-up question
+ original_query: The original research query
+ past_findings: The findings from previous research
+ **kwargs: Additional context parameters (unused)
+
+ Returns:
+ str: A contextualized query with previous research embedded
+ """
+ # Simply concatenate the context with the query - no LLM interpretation needed
+ # Highlight importance at top, actual request at bottom
+ contextualized = f"""IMPORTANT: This is a follow-up request. Focus on addressing the specific user request at the bottom of this prompt using the previous research context provided below.
+
+Previous research query: {original_query}
+
+Previous findings:
+{past_findings}
+
+---
+USER'S FOLLOW-UP REQUEST: {follow_up_query}
+Please address this specific request using the context and findings above.
+---"""
+
+ logger.info(
+ f"Created contextualized query with {len(past_findings)} chars of context"
+ )
+
+ return contextualized
diff --git a/src/local_deep_research/advanced_search_system/strategies/followup/__init__.py b/src/local_deep_research/advanced_search_system/strategies/followup/__init__.py
new file mode 100644
index 0000000000..b98d869906
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/strategies/followup/__init__.py
@@ -0,0 +1,10 @@
+"""
+Follow-up Research Strategies
+
+This package contains specialized strategies for handling follow-up research
+that builds upon previous research results.
+"""
+
+from .enhanced_contextual_followup import EnhancedContextualFollowUpStrategy
+
+__all__ = ["EnhancedContextualFollowUpStrategy"]
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.py
new file mode 100644
index 0000000000..00cffdec47
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/strategies/followup/enhanced_contextual_followup.py
@@ -0,0 +1,387 @@
+"""
+Enhanced Contextual Follow-Up Strategy
+
+An improved version of the contextual follow-up strategy that better leverages
+past research context, reformulates questions, and reuses sources effectively.
+"""
+
+from typing import Dict, List, Optional, Any
+from loguru import logger
+
+from ..base_strategy import BaseSearchStrategy
+from ...filters.followup_relevance_filter import FollowUpRelevanceFilter
+from ...knowledge.followup_context_manager import FollowUpContextHandler
+from ...questions.followup.simple_followup_question import (
+ SimpleFollowUpQuestionGenerator,
+)
+
+
+class EnhancedContextualFollowUpStrategy(BaseSearchStrategy):
+ """
+ Enhanced strategy for follow-up research that intelligently uses past context.
+
+ This strategy:
+ 1. Reformulates follow-up questions based on past findings
+ 2. Filters and reuses relevant sources from previous research
+ 3. Passes complete context to the delegate strategy
+ 4. Optimizes search to avoid redundancy
+ """
+
+ def __init__(
+ self,
+ model,
+ search,
+ delegate_strategy: BaseSearchStrategy,
+ all_links_of_system=None,
+ settings_snapshot=None,
+ research_context: Optional[Dict] = None,
+ **kwargs,
+ ):
+ """
+ Initialize the enhanced contextual follow-up strategy.
+
+ Args:
+ model: The LLM model to use
+ search: The search engine
+ delegate_strategy: The strategy to delegate actual search to
+ all_links_of_system: Accumulated links from past searches
+ settings_snapshot: Settings configuration
+ research_context: Context from previous research
+ """
+ super().__init__(all_links_of_system, settings_snapshot)
+
+ self.model = model
+ self.search = search
+ self.delegate_strategy = delegate_strategy
+ self.research_context = research_context or {}
+
+ # Initialize components
+ self.relevance_filter = FollowUpRelevanceFilter(model)
+ self.context_manager = FollowUpContextHandler(model)
+
+ # Initialize question generator for creating contextualized queries
+ self.question_generator = SimpleFollowUpQuestionGenerator(model)
+
+ # For follow-up research, we ALWAYS want to combine sources
+ # This is the whole point of follow-up - building on previous research
+ self.combine_sources = True
+
+ # Build comprehensive context
+ self.full_context = self._build_full_context()
+
+ logger.info(
+ f"EnhancedContextualFollowUpStrategy initialized with "
+ f"{len(self.full_context.get('past_sources', []))} past sources"
+ )
+
+ def _build_full_context(self) -> Dict[str, Any]:
+ """
+ Build comprehensive context from research data.
+
+ Returns:
+ Full context dictionary
+ """
+ # Use context manager to build structured context
+ if self.research_context:
+ # The follow-up query will be passed to analyze_topic later
+ # For now, use empty string since we're just building initial context
+ follow_up_query = ""
+ context = self.context_manager.build_context(
+ self.research_context, follow_up_query
+ )
+
+ # Also ensure we get the sources from the research context
+ if "past_sources" not in context or not context["past_sources"]:
+ # Try to get from various fields in research_context
+ sources = []
+ for field in ["resources", "all_links_of_system", "past_links"]:
+ if (
+ field in self.research_context
+ and self.research_context[field]
+ ):
+ sources.extend(self.research_context[field])
+ context["past_sources"] = sources
+
+ # Ensure we have the findings
+ if "past_findings" not in context or not context["past_findings"]:
+ context["past_findings"] = self.research_context.get(
+ "past_findings", ""
+ )
+
+ # Ensure we have the original query
+ context["original_query"] = self.research_context.get(
+ "original_query", ""
+ )
+ else:
+ context = {
+ "past_sources": [],
+ "past_findings": "",
+ "summary": "",
+ "key_entities": [],
+ "all_links_of_system": [],
+ "original_query": "",
+ }
+
+ return context
+
+ def analyze_topic(self, query: str) -> Dict:
+ """
+ Analyze a follow-up topic with enhanced context processing.
+
+ This strategy:
+ 1. Reformulates the question based on past findings
+ 2. Filters relevant past sources to reuse
+ 3. Hands over to the delegate strategy with enhanced context
+
+ Args:
+ query: The follow-up question to research
+
+ Returns:
+ Research findings with context enhancement
+ """
+ logger.info(f"Starting enhanced follow-up search for: {query}")
+
+ # Update the context with the actual follow-up query
+ self.full_context["follow_up_query"] = query
+
+ # Log what context we have
+ logger.info(
+ f"Context summary: {len(self.full_context.get('past_sources', []))} past sources, "
+ f"findings length: {len(self.full_context.get('past_findings', ''))}, "
+ f"original query: {self.full_context.get('original_query', 'N/A')}"
+ )
+
+ self._update_progress(
+ "Analyzing past research context", 10, {"phase": "context_analysis"}
+ )
+
+ # Step 1: Skip reformulation - we'll use the original query with full context
+ # This avoids LLM misinterpretation of queries like "provide data in a table"
+ # The context will make it clear what the query refers to
+
+ self._update_progress(
+ "Preparing contextualized query",
+ 20,
+ {"phase": "context_preparation", "original_query": query},
+ )
+
+ # Step 2: Filter relevant sources from past research using original query
+ relevant_sources = self._filter_relevant_sources(query)
+
+ self._update_progress(
+ f"Identified {len(relevant_sources)} relevant past sources",
+ 30,
+ {
+ "phase": "source_filtering",
+ "relevant_sources": len(relevant_sources),
+ "total_past_sources": len(
+ self.full_context.get("past_sources", [])
+ ),
+ },
+ )
+
+ # Step 3: Inject the relevant sources into delegate strategy
+ # This gives the delegate strategy a head start with pre-filtered sources
+ self._inject_context_into_delegate(relevant_sources, query)
+
+ self._update_progress(
+ "Handing over to research strategy",
+ 40,
+ {"phase": "delegate_handover"},
+ )
+
+ # Step 4: Create a query that includes FULL context from previous research
+ # Use question generator to create contextualized query
+ past_findings = self.full_context.get("past_findings", "")
+ original_research_query = self.full_context.get("original_query", "")
+
+ contextualized_query = (
+ self.question_generator.generate_contextualized_query(
+ follow_up_query=query,
+ original_query=original_research_query,
+ past_findings=past_findings,
+ )
+ )
+
+ # Let the delegate strategy (from user's settings) do the actual research
+ # with the contextualized query and pre-injected sources
+ result = self.delegate_strategy.analyze_topic(contextualized_query)
+
+ # Step 5: Get past sources for metadata (always needed)
+ all_past_sources = self.full_context.get("past_sources", [])
+
+ # Step 6: Optionally combine old sources with new ones
+ # Only do this if the setting is enabled to avoid breaking existing reports
+ if self.combine_sources:
+ logger.info(
+ f"Combining sources: self.combine_sources={self.combine_sources}"
+ )
+
+ # Ensure we have all sources from both researches
+ if "all_links_of_system" not in result:
+ result["all_links_of_system"] = []
+
+ # Log initial state
+ new_sources_count = len(result.get("all_links_of_system", []))
+ logger.info(
+ f"Initial state: {new_sources_count} new sources, {len(all_past_sources)} past sources to combine"
+ )
+
+ # Create a set of URLs already in the result to avoid duplicates
+ existing_urls = {
+ link.get("url")
+ for link in result.get("all_links_of_system", [])
+ }
+
+ # Add all past sources that aren't already in the result
+ added_count = 0
+ for source in all_past_sources:
+ url = source.get("url")
+ if url and url not in existing_urls:
+ # Mark it as from previous research
+ enhanced_source = source.copy()
+ enhanced_source["from_past_research"] = True
+ result["all_links_of_system"].append(enhanced_source)
+ existing_urls.add(url)
+ added_count += 1
+
+ logger.info(
+ f"Source combination complete: Added {added_count} past sources, total now {len(result['all_links_of_system'])} sources"
+ )
+ else:
+ logger.info(
+ f"Source combination skipped: self.combine_sources={self.combine_sources}"
+ )
+
+ # Step 7: Add metadata about the follow-up enhancement
+ if "metadata" not in result:
+ result["metadata"] = {}
+
+ result["metadata"]["follow_up_enhancement"] = {
+ "original_query": query,
+ "contextualized": True,
+ "sources_reused": len(relevant_sources),
+ "total_past_sources": len(all_past_sources),
+ "parent_research_id": self.full_context.get(
+ "parent_research_id", ""
+ ),
+ }
+
+ self._update_progress(
+ "Enhanced follow-up search complete",
+ 100,
+ {
+ "phase": "complete",
+ "sources_reused": len(relevant_sources),
+ "total_sources": len(result.get("all_links_of_system", [])),
+ },
+ )
+
+ logger.info(
+ f"Enhanced results: {len(relevant_sources)} past sources reused, "
+ f"{len(result.get('all_links_of_system', []))} total sources found"
+ )
+
+ return result
+
+ def _filter_relevant_sources(self, query: str) -> List[Dict]:
+ """
+ Filter past sources for relevance to the follow-up query.
+
+ Args:
+ query: The reformulated follow-up query
+
+ Returns:
+ List of relevant sources
+ """
+ past_sources = self.full_context.get("past_sources", [])
+
+ if not past_sources:
+ return []
+
+ # Filter sources using the relevance filter
+ # Get max sources from settings or use default
+ max_followup_sources = self.settings_snapshot.get(
+ "search.max_followup_sources", {}
+ ).get("value", 15)
+
+ relevant = self.relevance_filter.filter_results(
+ results=past_sources,
+ query=query,
+ max_results=max_followup_sources,
+ threshold=0.3,
+ past_findings=self.full_context.get("past_findings", ""),
+ original_query=self.full_context.get("original_query", ""),
+ )
+
+ logger.info(
+ f"Filtered {len(past_sources)} past sources to "
+ f"{len(relevant)} relevant ones"
+ )
+
+ return relevant
+
+ def _inject_context_into_delegate(
+ self, relevant_sources: List[Dict], reformulated_query: str
+ ):
+ """
+ Inject context and sources into the delegate strategy.
+
+ Args:
+ relevant_sources: Filtered relevant sources
+ reformulated_query: The reformulated query
+ """
+ # Initialize delegate's all_links_of_system if needed
+ if not self.delegate_strategy.all_links_of_system:
+ self.delegate_strategy.all_links_of_system = []
+
+ # Add relevant sources to the beginning (high priority)
+ existing_urls = {
+ link.get("url")
+ for link in self.delegate_strategy.all_links_of_system
+ }
+
+ injected_count = 0
+ for source in relevant_sources:
+ url = source.get("url")
+ if url and url not in existing_urls:
+ # Add source with enhanced metadata
+ enhanced_source = source.copy()
+ enhanced_source["from_past_research"] = True
+ enhanced_source["follow_up_relevance"] = source.get(
+ "relevance_score", 1.0
+ )
+
+ self.delegate_strategy.all_links_of_system.insert(
+ 0, enhanced_source
+ )
+ existing_urls.add(url)
+ injected_count += 1
+
+ logger.info(
+ f"Injected {injected_count} relevant past sources into delegate strategy"
+ )
+
+ # Pass context to delegate if it supports it
+ if hasattr(self.delegate_strategy, "set_followup_context"):
+ self.delegate_strategy.set_followup_context(
+ {
+ "reformulated_query": reformulated_query,
+ "past_findings_summary": self.full_context.get(
+ "summary", ""
+ ),
+ "key_entities": self.full_context.get("key_entities", []),
+ "sources_injected": injected_count,
+ }
+ )
+
+ def set_progress_callback(self, callback):
+ """
+ Set progress callback for both wrapper and delegate.
+
+ Args:
+ callback: Progress callback function
+ """
+ super().set_progress_callback(callback)
+ if self.delegate_strategy:
+ self.delegate_strategy.set_progress_callback(callback)
diff --git a/src/local_deep_research/followup_research/__init__.py b/src/local_deep_research/followup_research/__init__.py
new file mode 100644
index 0000000000..0e875318fe
--- /dev/null
+++ b/src/local_deep_research/followup_research/__init__.py
@@ -0,0 +1,15 @@
+"""
+Follow-up Research Package
+
+This package provides functionality for asking follow-up questions on existing research,
+reusing previous findings and sources to provide contextual answers.
+"""
+
+from .service import FollowUpResearchService
+from .models import FollowUpRequest, FollowUpResponse
+
+__all__ = [
+ "FollowUpResearchService",
+ "FollowUpRequest",
+ "FollowUpResponse",
+]
diff --git a/src/local_deep_research/followup_research/models.py b/src/local_deep_research/followup_research/models.py
new file mode 100644
index 0000000000..0baa6b7e22
--- /dev/null
+++ b/src/local_deep_research/followup_research/models.py
@@ -0,0 +1,52 @@
+"""
+Data models for follow-up research functionality.
+"""
+
+from dataclasses import dataclass
+from typing import List, Dict, Any
+
+
+@dataclass
+class FollowUpRequest:
+ """Request model for follow-up research."""
+
+ parent_research_id: str
+ question: str
+ strategy: str = "source-based" # Default delegate strategy
+ max_iterations: int = 1 # Quick summary by default
+ questions_per_iteration: int = 3
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert to dictionary for API/service use."""
+ return {
+ "parent_research_id": self.parent_research_id,
+ "question": self.question,
+ "strategy": self.strategy,
+ "max_iterations": self.max_iterations,
+ "questions_per_iteration": self.questions_per_iteration,
+ }
+
+
+@dataclass
+class FollowUpResponse:
+ """Response model for follow-up research."""
+
+ research_id: str
+ question: str
+ answer: str
+ sources_used: List[Dict[str, str]]
+ parent_context_used: bool
+ reused_links_count: int
+ new_links_count: int
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert to dictionary for API response."""
+ return {
+ "research_id": self.research_id,
+ "question": self.question,
+ "answer": self.answer,
+ "sources_used": self.sources_used,
+ "parent_context_used": self.parent_context_used,
+ "reused_links_count": self.reused_links_count,
+ "new_links_count": self.new_links_count,
+ }
diff --git a/src/local_deep_research/followup_research/routes.py b/src/local_deep_research/followup_research/routes.py
new file mode 100644
index 0000000000..3966b0fbb2
--- /dev/null
+++ b/src/local_deep_research/followup_research/routes.py
@@ -0,0 +1,316 @@
+"""
+Flask routes for follow-up research functionality.
+"""
+
+from flask import Blueprint, request, jsonify, session, g
+from loguru import logger
+
+from .service import FollowUpResearchService
+from .models import FollowUpRequest
+from ..web.auth.decorators import login_required
+
+# Create blueprint
+followup_bp = Blueprint("followup", __name__, url_prefix="/api/followup")
+
+
+@followup_bp.route("/prepare", methods=["POST"])
+@login_required
+def prepare_followup():
+ """
+ Prepare a follow-up research by loading parent context.
+
+ Request body:
+ {
+ "parent_research_id": "uuid",
+ "question": "follow-up question"
+ }
+
+ Returns:
+ {
+ "success": true,
+ "parent_summary": "...",
+ "available_sources": 10,
+ "suggested_strategy": "source-based"
+ }
+ """
+ try:
+ data = request.get_json()
+ parent_id = data.get("parent_research_id")
+ question = data.get("question")
+
+ if not parent_id or not question:
+ return jsonify(
+ {
+ "success": False,
+ "error": "Missing parent_research_id or question",
+ }
+ ), 400
+
+ # Get username from session
+ username = session.get("username")
+
+ # Get settings snapshot to use for suggested strategy
+ from ..web.services.settings_manager import SettingsManager
+ from ..database.session_context import get_user_db_session
+
+ with get_user_db_session(username) as db_session:
+ settings_manager = SettingsManager(db_session=db_session)
+ settings_snapshot = settings_manager.get_all_settings()
+
+ # Get strategy from settings
+ strategy_from_settings = settings_snapshot.get(
+ "search.search_strategy", {}
+ ).get("value", "source-based")
+
+ # Initialize service
+ service = FollowUpResearchService(username=username)
+
+ # Load parent context
+ parent_data = service.load_parent_research(parent_id)
+
+ if not parent_data:
+ # For now, return success with empty data to allow testing
+ logger.warning(
+ f"Parent research {parent_id} not found, returning empty context"
+ )
+ return jsonify(
+ {
+ "success": True,
+ "parent_summary": "Previous research context",
+ "available_sources": 0,
+ "suggested_strategy": strategy_from_settings, # Use strategy from settings
+ "parent_research": {
+ "id": parent_id,
+ "query": "Previous query",
+ "sources_count": 0,
+ },
+ }
+ )
+
+ # Prepare response with parent context summary
+ response = {
+ "success": True,
+ "parent_summary": parent_data.get("query", ""),
+ "available_sources": len(parent_data.get("resources", [])),
+ "suggested_strategy": strategy_from_settings, # Use strategy from settings
+ "parent_research": {
+ "id": parent_id,
+ "query": parent_data.get("query", ""),
+ "sources_count": len(parent_data.get("resources", [])),
+ },
+ }
+
+ return jsonify(response)
+
+ except Exception:
+ logger.exception("Error preparing follow-up")
+ return jsonify(
+ {"success": False, "error": "An internal error has occurred."}
+ ), 500
+
+
+@followup_bp.route("/start", methods=["POST"])
+@login_required
+def start_followup():
+ """
+ Start a follow-up research.
+
+ Request body:
+ {
+ "parent_research_id": "uuid",
+ "question": "follow-up question",
+ "strategy": "source-based", # optional
+ "max_iterations": 1, # optional
+ "questions_per_iteration": 3 # optional
+ }
+
+ Returns:
+ {
+ "success": true,
+ "research_id": "new-uuid",
+ "message": "Follow-up research started"
+ }
+ """
+ try:
+ from ..web.services.research_service import (
+ start_research_process,
+ run_research_process,
+ )
+ from ..web.routes.globals import active_research, termination_flags
+ import uuid
+
+ data = request.get_json()
+
+ # Get username from session
+ username = session.get("username")
+
+ # Get settings snapshot first to use database values
+ from ..web.services.settings_manager import SettingsManager
+ from ..database.session_context import get_user_db_session
+
+ with get_user_db_session(username) as db_session:
+ settings_manager = SettingsManager(db_session=db_session)
+ settings_snapshot = settings_manager.get_all_settings()
+
+ # Get strategy from settings snapshot, fallback to source-based if not set
+ strategy_from_settings = settings_snapshot.get(
+ "search.search_strategy", {}
+ ).get("value", "source-based")
+
+ # Get iterations and questions from settings snapshot
+ iterations_from_settings = settings_snapshot.get(
+ "search.iterations", {}
+ ).get("value", 1)
+ questions_from_settings = settings_snapshot.get(
+ "search.questions_per_iteration", {}
+ ).get("value", 3)
+
+ # Create follow-up request using settings values
+ followup_request = FollowUpRequest(
+ parent_research_id=data.get("parent_research_id"),
+ question=data.get("question"),
+ strategy=strategy_from_settings, # Use strategy from settings
+ max_iterations=iterations_from_settings, # Use iterations from settings
+ questions_per_iteration=questions_from_settings, # Use questions from settings
+ )
+
+ # Initialize service
+ service = FollowUpResearchService(username=username)
+
+ # Prepare research parameters
+ research_params = service.perform_followup(followup_request)
+
+ logger.info(f"Research params type: {type(research_params)}")
+ logger.info(
+ f"Research params keys: {research_params.keys() if isinstance(research_params, dict) else 'Not a dict'}"
+ )
+ logger.info(
+ f"Query value: {research_params.get('query') if isinstance(research_params, dict) else 'N/A'}"
+ )
+ logger.info(
+ f"Query type: {type(research_params.get('query')) if isinstance(research_params, dict) else 'N/A'}"
+ )
+
+ # Generate new research ID
+ research_id = str(uuid.uuid4())
+
+ # Create database entry (settings_snapshot already captured above)
+ from ..database.models import ResearchHistory
+ from datetime import datetime, UTC
+
+ created_at = datetime.now(UTC).isoformat()
+
+ with get_user_db_session(username) as db_session:
+ # Create the database entry (required for tracking)
+ research_meta = {
+ "submission": {
+ "parent_research_id": data.get("parent_research_id"),
+ "question": data.get("question"),
+ "strategy": "contextual-followup",
+ },
+ }
+
+ research = ResearchHistory(
+ id=research_id,
+ query=research_params["query"],
+ mode="quick", # Use 'quick' not 'quick_summary'
+ status="in_progress",
+ created_at=created_at,
+ progress_log=[{"time": created_at, "progress": 0}],
+ research_meta=research_meta,
+ )
+ db_session.add(research)
+ db_session.commit()
+ logger.info(
+ f"Created follow-up research entry with ID: {research_id}"
+ )
+
+ # Start the research process using the existing infrastructure
+ # Use quick_summary mode for follow-ups by default
+ logger.info(
+ f"Starting follow-up research for query of type: {type(research_params.get('query'))}"
+ )
+
+ # Get user password for metrics database access
+ user_password = None
+ session_id = session.get("session_id")
+ if session_id:
+ from ..database.session_passwords import session_password_store
+
+ user_password = session_password_store.retrieve(
+ username, session_id
+ )
+
+ # Fallback to g.user_password (set by middleware if temp_auth was used)
+ if not user_password:
+ user_password = getattr(g, "user_password", None)
+
+ # Last resort: try temp_auth_store
+ if not user_password:
+ from ..database.temp_auth import temp_auth_store
+
+ auth_token = session.get("temp_auth_token")
+ if auth_token:
+ # Use peek_auth to avoid consuming the token
+ auth_data = temp_auth_store.peek_auth(auth_token)
+ if auth_data and auth_data[0] == username:
+ user_password = auth_data[1]
+
+ if not user_password:
+ logger.warning(
+ f"No password available for metrics access for user {username}"
+ )
+
+ # Get model and search settings from user's settings
+ model_provider = settings_snapshot.get("llm.provider", {}).get(
+ "value", "OLLAMA"
+ )
+ model = settings_snapshot.get("llm.model", {}).get(
+ "value", "gemma3:12b"
+ )
+ search_engine = settings_snapshot.get("search.tool", {}).get(
+ "value", "searxng"
+ )
+ custom_endpoint = settings_snapshot.get(
+ "llm.openai_endpoint.url", {}
+ ).get("value")
+
+ start_research_process(
+ research_id,
+ research_params["query"],
+ "quick", # Use 'quick' for quick summary mode
+ active_research,
+ termination_flags,
+ run_research_process,
+ username=username,
+ user_password=user_password, # Pass password for metrics database access
+ model_provider=model_provider, # Pass model provider
+ model=model, # Pass model name
+ search_engine=search_engine, # Pass search engine
+ custom_endpoint=custom_endpoint, # Pass custom endpoint if any
+ strategy="enhanced-contextual-followup", # Use enhanced contextual follow-up strategy
+ iterations=research_params["max_iterations"],
+ questions_per_iteration=research_params["questions_per_iteration"],
+ delegate_strategy=research_params.get(
+ "delegate_strategy", "source-based"
+ ),
+ research_context=research_params["research_context"],
+ parent_research_id=research_params[
+ "parent_research_id"
+ ], # Pass parent research ID
+ settings_snapshot=settings_snapshot,
+ )
+
+ return jsonify(
+ {
+ "success": True,
+ "research_id": research_id,
+ "message": "Follow-up research started",
+ }
+ )
+
+ except Exception:
+ logger.exception("Error starting follow-up")
+ return jsonify(
+ {"success": False, "error": "An internal error has occurred."}
+ ), 500
diff --git a/src/local_deep_research/followup_research/service.py b/src/local_deep_research/followup_research/service.py
new file mode 100644
index 0000000000..fb9183498d
--- /dev/null
+++ b/src/local_deep_research/followup_research/service.py
@@ -0,0 +1,214 @@
+"""
+Service layer for follow-up research functionality.
+
+This service handles the business logic for follow-up research,
+including loading parent research context and orchestrating the search.
+"""
+
+from typing import Dict, Any
+from loguru import logger
+
+from ..database.models import ResearchHistory
+from ..database.session_context import get_user_db_session
+from ..web.services.research_sources_service import ResearchSourcesService
+from .models import FollowUpRequest
+
+
+class FollowUpResearchService:
+ """Service for handling follow-up research operations."""
+
+ def __init__(self, username: str = None):
+ """
+ Initialize the follow-up research service.
+
+ Args:
+ username: Username for database access
+ """
+ self.username = username
+
+ def load_parent_research(self, parent_research_id: str) -> Dict[str, Any]:
+ """
+ Load parent research data from the database.
+
+ Args:
+ parent_research_id: ID of the parent research
+
+ Returns:
+ Dictionary containing parent research data including:
+ - report_content: The generated report
+ - resources: List of research resources/links
+ - query: Original research query
+ - strategy: Strategy used
+ """
+ try:
+ with get_user_db_session(self.username) as session:
+ # Load research history
+ research = (
+ session.query(ResearchHistory)
+ .filter_by(id=parent_research_id)
+ .first()
+ )
+
+ if not research:
+ logger.warning(
+ f"Parent research not found: {parent_research_id}"
+ )
+ return {}
+
+ logger.info(
+ f"Found research: {research.id}, has meta: {research.research_meta is not None}"
+ )
+
+ # Use the ResearchSourcesService to get sources properly from database
+ sources_service = ResearchSourcesService()
+ resource_list = sources_service.get_research_sources(
+ parent_research_id, username=self.username
+ )
+
+ logger.info(
+ f"Found {len(resource_list)} sources from ResearchResource table"
+ )
+
+ # If no sources in database, try to get from research_meta as fallback
+ if not resource_list and research.research_meta:
+ logger.info(
+ "No sources in database, checking research_meta"
+ )
+ logger.info(
+ f"Research meta keys: {list(research.research_meta.keys()) if isinstance(research.research_meta, dict) else 'Not a dict'}"
+ )
+
+ # Try different possible locations for sources in research_meta
+ meta_sources = (
+ research.research_meta.get("all_links_of_system", [])
+ or research.research_meta.get("sources", [])
+ or research.research_meta.get("links", [])
+ or []
+ )
+
+ if meta_sources:
+ logger.info(
+ f"Found {len(meta_sources)} sources in research_meta, saving to database"
+ )
+ # Save them to the database for future use
+ saved = sources_service.save_research_sources(
+ parent_research_id,
+ meta_sources,
+ username=self.username,
+ )
+ logger.info(f"Saved {saved} sources to database")
+
+ # Now retrieve them properly formatted
+ resource_list = sources_service.get_research_sources(
+ parent_research_id, username=self.username
+ )
+
+ # Convert to dictionary format
+ parent_data = {
+ "research_id": research.id,
+ "query": research.query,
+ "report_content": research.report_content,
+ "formatted_findings": research.research_meta.get(
+ "formatted_findings", ""
+ )
+ if research.research_meta
+ else "",
+ "strategy": research.research_meta.get("strategy_name", "")
+ if research.research_meta
+ else "",
+ "resources": resource_list,
+ "all_links_of_system": resource_list,
+ }
+
+ logger.info(
+ f"Loaded parent research {parent_research_id} with "
+ f"{len(resource_list)} sources"
+ )
+
+ return parent_data
+
+ except Exception:
+ logger.exception("Error loading parent research")
+ return {}
+
+ def prepare_research_context(
+ self, parent_research_id: str
+ ) -> Dict[str, Any]:
+ """
+ Prepare the research context for the contextual follow-up strategy.
+
+ Args:
+ parent_research_id: ID of the parent research
+
+ Returns:
+ Research context dictionary for the strategy
+ """
+ parent_data = self.load_parent_research(parent_research_id)
+
+ if not parent_data:
+ logger.warning("No parent data found, returning empty context")
+ return {}
+
+ # Format context for the strategy
+ research_context = {
+ "parent_research_id": parent_research_id,
+ "past_links": parent_data.get("all_links_of_system", []),
+ "past_findings": parent_data.get("formatted_findings", ""),
+ "report_content": parent_data.get("report_content", ""),
+ "resources": parent_data.get("resources", []),
+ "all_links_of_system": parent_data.get("all_links_of_system", []),
+ "original_query": parent_data.get("query", ""),
+ }
+
+ return research_context
+
+ def perform_followup(self, request: FollowUpRequest) -> Dict[str, Any]:
+ """
+ Perform a follow-up research based on parent research.
+
+ This method prepares the context and parameters for the research system
+ to use the contextual follow-up strategy.
+
+ Args:
+ request: FollowUpRequest with question and parent research ID
+
+ Returns:
+ Dictionary with research parameters for the research system
+ """
+ # Prepare the research context from parent
+ research_context = self.prepare_research_context(
+ request.parent_research_id
+ )
+
+ if not research_context:
+ logger.warning(
+ f"Parent research not found: {request.parent_research_id}, using empty context"
+ )
+ # Use empty context to allow follow-up without parent
+ research_context = {
+ "parent_research_id": request.parent_research_id,
+ "past_links": [],
+ "past_findings": "",
+ "report_content": "",
+ "resources": [],
+ "all_links_of_system": [],
+ "original_query": "",
+ }
+
+ # Prepare parameters for the research system
+ research_params = {
+ "query": request.question,
+ "strategy": "contextual-followup",
+ "delegate_strategy": request.strategy,
+ "max_iterations": request.max_iterations,
+ "questions_per_iteration": request.questions_per_iteration,
+ "research_context": research_context,
+ "parent_research_id": request.parent_research_id,
+ }
+
+ logger.info(
+ f"Prepared follow-up research for question: '{request.question}' "
+ f"based on parent: {request.parent_research_id}"
+ )
+
+ return research_params
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index 849f9f08f1..05fdeb1bc3 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -8,47 +8,8 @@ from .advanced_search_system.findings.repository import FindingsRepository
from .advanced_search_system.questions.standard_question import (
StandardQuestionGenerator,
)
-from .advanced_search_system.strategies.adaptive_decomposition_strategy import (
- AdaptiveDecompositionStrategy,
-)
-from .advanced_search_system.strategies.browsecomp_optimized_strategy import (
- BrowseCompOptimizedStrategy,
-)
-from .advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
-)
-from .advanced_search_system.strategies.early_stop_constrained_strategy import (
- EarlyStopConstrainedStrategy,
-)
-from .advanced_search_system.strategies.evidence_based_strategy_v2 import (
- EnhancedEvidenceBasedStrategy,
-)
-from .advanced_search_system.strategies.iterative_reasoning_strategy import (
- IterativeReasoningStrategy,
-)
-from .advanced_search_system.strategies.iterdrag_strategy import (
- IterDRAGStrategy,
-)
-from .advanced_search_system.strategies.parallel_constrained_strategy import (
- ParallelConstrainedStrategy,
-)
-from .advanced_search_system.strategies.parallel_search_strategy import (
- ParallelSearchStrategy,
-)
-from .advanced_search_system.strategies.rapid_search_strategy import (
- RapidSearchStrategy,
-)
-from .advanced_search_system.strategies.recursive_decomposition_strategy import (
- RecursiveDecompositionStrategy,
-)
-from .advanced_search_system.strategies.smart_decomposition_strategy import (
- SmartDecompositionStrategy,
-)
-from .advanced_search_system.strategies.source_based_strategy import (
- SourceBasedSearchStrategy,
-)
-from .advanced_search_system.strategies.news_strategy import (
- NewsAggregationStrategy,
+from .advanced_search_system.strategies.followup.enhanced_contextual_followup import (
+ EnhancedContextualFollowUpStrategy,
)
# StandardSearchStrategy imported lazily to avoid database access during module import
@@ -178,391 +139,68 @@ class AdvancedSearchSystem:
self.progress_callback = lambda _1, _2, _3: None
self.all_links_of_system = list()
- # Initialize strategy based on name
- if strategy_name.lower() == "iterdrag":
- logger.info("Creating IterDRAGStrategy instance")
- self.strategy = IterDRAGStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- settings_snapshot=self.settings_snapshot,
- )
- elif strategy_name.lower() in ["source-based", "source_based"]:
- logger.info("Creating SourceBasedSearchStrategy instance")
- self.strategy = SourceBasedSearchStrategy(
- model=self.model,
- search=self.search,
- include_text_content=include_text_content,
- use_cross_engine_filter=use_cross_engine_filter,
- all_links_of_system=self.all_links_of_system,
- use_atomic_facts=use_atomic_facts,
- settings_snapshot=self.settings_snapshot,
- )
- elif strategy_name.lower() == "parallel":
- logger.info("Creating ParallelSearchStrategy instance")
- self.strategy = ParallelSearchStrategy(
- model=self.model,
- search=self.search,
- include_text_content=include_text_content,
- use_cross_engine_filter=use_cross_engine_filter,
- all_links_of_system=self.all_links_of_system,
- settings_snapshot=self.settings_snapshot,
- )
- elif strategy_name.lower() == "rapid":
- logger.info("Creating RapidSearchStrategy instance")
- self.strategy = RapidSearchStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- settings_snapshot=self.settings_snapshot,
- )
- elif (
- strategy_name.lower() == "recursive"
- or strategy_name.lower() == "recursive-decomposition"
- ):
- logger.info("Creating RecursiveDecompositionStrategy instance")
- self.strategy = RecursiveDecompositionStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- settings_snapshot=self.settings_snapshot,
- )
- elif strategy_name.lower() == "iterative":
- logger.info("Creating IterativeReasoningStrategy instance")
- # For iterative reasoning, use more iterations to allow thorough exploration
- # while keeping search iterations separate
- self.strategy = IterativeReasoningStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- max_iterations=20, # Increased reasoning iterations
- confidence_threshold=0.95, # Increased from 0.85 to require very high confidence
- search_iterations_per_round=self.max_iterations
- or 1, # Search iterations from settings
- questions_per_search=self.questions_per_iteration,
- settings_snapshot=self.settings_snapshot,
- )
- elif strategy_name.lower() == "adaptive":
- logger.info("Creating AdaptiveDecompositionStrategy instance")
- self.strategy = AdaptiveDecompositionStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- max_steps=self.max_iterations,
- min_confidence=0.8,
- source_search_iterations=2,
- source_questions_per_iteration=self.questions_per_iteration,
- settings_snapshot=self.settings_snapshot,
- )
- elif strategy_name.lower() == "smart":
- logger.info("Creating SmartDecompositionStrategy instance")
- self.strategy = SmartDecompositionStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- max_iterations=self.max_iterations,
- source_search_iterations=2,
- source_questions_per_iteration=self.questions_per_iteration,
- settings_snapshot=self.settings_snapshot,
- )
- elif strategy_name.lower() == "browsecomp":
- logger.info("Creating BrowseCompOptimizedStrategy instance")
- self.strategy = BrowseCompOptimizedStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- max_browsecomp_iterations=15, # BrowseComp strategy main iterations
- confidence_threshold=0.9,
- max_iterations=self.max_iterations, # Source-based sub-searches
- questions_per_iteration=self.questions_per_iteration, # Source-based sub-searches
- settings_snapshot=self.settings_snapshot,
- )
- elif strategy_name.lower() == "evidence":
- logger.info("Creating EnhancedEvidenceBasedStrategy instance")
- self.strategy = EnhancedEvidenceBasedStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- max_iterations=20, # Main evidence-gathering iterations
- confidence_threshold=0.95, # Increased from 0.85 to require very high confidence
- candidate_limit=20, # Increased from 10
- evidence_threshold=0.9, # Increased from 0.6 to require strong evidence
- max_search_iterations=self.max_iterations, # Source-based sub-searches
- questions_per_iteration=self.questions_per_iteration,
- min_candidates_threshold=10, # Increased from 3
- enable_pattern_learning=True,
- settings_snapshot=self.settings_snapshot,
- )
- elif strategy_name.lower() == "constrained":
- logger.info("Creating ConstrainedSearchStrategy instance")
- self.strategy = ConstrainedSearchStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- max_iterations=20,
- confidence_threshold=0.95, # Increased from 0.85 to require very high confidence
- candidate_limit=100, # Increased from 30
- evidence_threshold=0.9, # Increased from 0.6 to require strong evidence
- max_search_iterations=self.max_iterations,
- questions_per_iteration=self.questions_per_iteration,
- min_candidates_per_stage=20, # Increased from 5
- settings_snapshot=self.settings_snapshot,
- )
- elif strategy_name.lower() in [
- "parallel-constrained",
- "parallel_constrained",
- ]:
- logger.info("Creating ParallelConstrainedStrategy instance")
- self.strategy = ParallelConstrainedStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- max_iterations=20,
- confidence_threshold=0.95, # Increased from 0.85 to require very high confidence
- candidate_limit=100,
- evidence_threshold=0.9, # Increased from 0.6 to require strong evidence
- max_search_iterations=self.max_iterations,
- questions_per_iteration=self.questions_per_iteration,
- min_candidates_per_stage=20, # Correct parameter name for parent class
- parallel_workers=100, # Run up to 100 searches in parallel
- settings_snapshot=self.settings_snapshot,
- )
- elif strategy_name.lower() in [
- "early-stop-constrained",
- "early_stop_constrained",
- ]:
- logger.info("Creating EarlyStopConstrainedStrategy instance")
- self.strategy = EarlyStopConstrainedStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- max_iterations=20,
- confidence_threshold=0.95,
- candidate_limit=100,
- evidence_threshold=0.9,
- max_search_iterations=self.max_iterations,
- questions_per_iteration=self.questions_per_iteration,
- min_candidates_per_stage=20,
- parallel_workers=100, # Increased parallelism as requested
- early_stop_threshold=0.99, # Stop when we find 99%+ confidence
- concurrent_evaluation=True, # Evaluate candidates as we find them
- settings_snapshot=self.settings_snapshot,
- )
- elif strategy_name.lower() in ["smart-query", "smart_query"]:
- from .advanced_search_system.strategies.smart_query_strategy import (
- SmartQueryStrategy,
- )
-
- logger.info("Creating SmartQueryStrategy instance")
- self.strategy = SmartQueryStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- max_iterations=20,
- confidence_threshold=0.95,
- candidate_limit=100,
- evidence_threshold=0.9,
- max_search_iterations=self.max_iterations,
- questions_per_iteration=self.questions_per_iteration,
- min_candidates_per_stage=20,
- parallel_workers=100, # High parallelism
- early_stop_threshold=0.99, # Stop when we find 99%+ confidence
- concurrent_evaluation=True, # Evaluate candidates as we find them
- use_llm_query_generation=True, # Use smart query generation
- queries_per_combination=3, # Generate multiple queries
- settings_snapshot=self.settings_snapshot,
- )
- elif strategy_name.lower() in ["dual-confidence", "dual_confidence"]:
- from .advanced_search_system.strategies.dual_confidence_strategy import (
- DualConfidenceStrategy,
- )
-
- logger.info("Creating DualConfidenceStrategy instance")
- self.strategy = DualConfidenceStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- max_iterations=20,
- confidence_threshold=0.95,
- candidate_limit=100,
- evidence_threshold=0.9,
- max_search_iterations=self.max_iterations,
- questions_per_iteration=self.questions_per_iteration,
- min_candidates_per_stage=20,
- parallel_workers=100,
- early_stop_threshold=0.95, # Lower threshold since dual confidence is more accurate
- concurrent_evaluation=True,
- use_llm_query_generation=True,
- queries_per_combination=3,
- use_entity_seeding=True,
- use_direct_property_search=True,
- uncertainty_penalty=0.2, # Penalty for uncertain evidence
- negative_weight=0.5, # How much negative evidence counts against
- settings_snapshot=self.settings_snapshot,
- )
- elif strategy_name.lower() in [
- "dual-confidence-with-rejection",
- "dual_confidence_with_rejection",
- ]:
- from .advanced_search_system.strategies.dual_confidence_with_rejection import (
- DualConfidenceWithRejectionStrategy,
- )
+ # Initialize strategy using factory
+ from .search_system_factory import create_strategy
- logger.info("Creating DualConfidenceWithRejectionStrategy instance")
- self.strategy = DualConfidenceWithRejectionStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- max_iterations=20,
- confidence_threshold=0.95,
- candidate_limit=100,
- evidence_threshold=0.9,
- max_search_iterations=self.max_iterations,
- questions_per_iteration=self.questions_per_iteration,
- min_candidates_per_stage=20,
- parallel_workers=100,
- early_stop_threshold=0.95,
- concurrent_evaluation=True,
- use_llm_query_generation=True,
- queries_per_combination=3,
- use_entity_seeding=True,
- use_direct_property_search=True,
- uncertainty_penalty=0.2,
- negative_weight=0.5,
- rejection_threshold=0.3, # Reject if negative confidence > 30%
- positive_threshold=0.2, # Unless positive confidence > 20%
- critical_constraint_rejection=0.2, # Stricter for critical constraints
- settings_snapshot=self.settings_snapshot,
- )
- elif strategy_name.lower() in [
- "concurrent-dual-confidence",
- "concurrent_dual_confidence",
+ # Special handling for follow-up strategy which needs different logic
+ if strategy_name.lower() in [
+ "enhanced-contextual-followup",
+ "enhanced_contextual_followup",
+ "contextual-followup",
+ "contextual_followup",
]:
- from .advanced_search_system.strategies.concurrent_dual_confidence_strategy import (
- ConcurrentDualConfidenceStrategy,
+ logger.info("Creating EnhancedContextualFollowUpStrategy instance")
+ # Get delegate strategy from research context
+ # This should be the user's preferred strategy from settings
+ delegate_strategy_name = (
+ self.research_context.get("delegate_strategy", "source-based")
+ if self.research_context
+ else "source-based"
)
- logger.info("Creating ConcurrentDualConfidenceStrategy instance")
- self.strategy = ConcurrentDualConfidenceStrategy(
+ delegate = create_strategy(
+ strategy_name=delegate_strategy_name,
model=self.model,
search=self.search,
- all_links_of_system=self.all_links_of_system,
- max_iterations=20,
- confidence_threshold=0.95,
- candidate_limit=100,
- evidence_threshold=0.9,
- max_search_iterations=self.max_iterations,
- questions_per_iteration=self.questions_per_iteration,
- min_candidates_per_stage=20,
- parallel_workers=10, # Concurrent evaluation threads
- early_stop_threshold=0.95,
- concurrent_evaluation=True,
- use_llm_query_generation=True,
- queries_per_combination=3,
- use_entity_seeding=True,
- use_direct_property_search=True,
- uncertainty_penalty=0.2,
- negative_weight=0.5,
- rejection_threshold=0.3,
- positive_threshold=0.2,
- critical_constraint_rejection=0.2,
- # Concurrent-specific parameters
- min_good_candidates=3,
- target_candidates=5,
- max_candidates=10,
- min_score_threshold=0.65,
- exceptional_score=0.95,
- quality_plateau_threshold=0.1,
- max_search_time=30.0,
- max_evaluations=30,
+ all_links_of_system=[],
settings_snapshot=self.settings_snapshot,
- )
- elif strategy_name.lower() in ["modular", "modular-strategy"]:
- from .advanced_search_system.strategies.modular_strategy import (
- ModularStrategy,
+ knowledge_accumulation_mode=True,
)
- logger.info("Creating ModularStrategy instance")
- self.strategy = ModularStrategy(
+ # Create the contextual follow-up strategy with the delegate
+ self.strategy = EnhancedContextualFollowUpStrategy(
model=self.model,
search=self.search,
+ delegate_strategy=delegate,
all_links_of_system=self.all_links_of_system,
- constraint_checker_type="dual_confidence", # dual_confidence, strict, threshold
- exploration_strategy="adaptive", # parallel, adaptive, constraint_guided, diversity
- early_rejection=True, # Enable fast pre-screening
- early_stopping=True, # Enable early stopping
- llm_constraint_processing=True, # Enable LLM-driven constraint processing
- immediate_evaluation=True, # Enable immediate candidate evaluation
settings_snapshot=self.settings_snapshot,
+ research_context=self.research_context,
)
- elif strategy_name.lower() in ["modular-parallel", "modular_parallel"]:
- from .advanced_search_system.strategies.modular_strategy import (
- ModularStrategy,
- )
-
- logger.info(
- "Creating ModularStrategy with parallel exploration and dual confidence"
- )
- self.strategy = ModularStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- constraint_checker_type="dual_confidence", # Concurrent evaluation with +/-/? scoring
- exploration_strategy="parallel", # Parallel constraint searches
- settings_snapshot=self.settings_snapshot,
- )
- elif strategy_name.lower() in [
- "focused-iteration",
- "focused_iteration",
- ]:
- from .advanced_search_system.strategies.focused_iteration_strategy import (
- FocusedIterationStrategy,
- )
-
- logger.info("Creating FocusedIterationStrategy instance")
- # Use database settings for iterations and questions_per_iteration
- self.strategy = FocusedIterationStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- max_iterations=self.max_iterations, # Use database setting
- questions_per_iteration=self.questions_per_iteration, # Use database setting
- use_browsecomp_optimization=True, # Enable BrowseComp optimizations for 95% accuracy
- settings_snapshot=self.settings_snapshot,
- )
- elif strategy_name.lower() in [
- "browsecomp-entity",
- "browsecomp_entity",
- ]:
- from .advanced_search_system.strategies.browsecomp_entity_strategy import (
- BrowseCompEntityStrategy,
- )
-
- logger.info("Creating BrowseCompEntityStrategy instance")
- self.strategy = BrowseCompEntityStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- )
- elif strategy_name.lower() in [
- "news",
- "news_aggregation",
- "news-aggregation",
- ]:
- logger.info("Creating NewsAggregationStrategy instance")
- self.strategy = NewsAggregationStrategy()
else:
- logger.info("Creating StandardSearchStrategy instance")
- # Import lazily to avoid database access during module import
- from .advanced_search_system.strategies.standard_strategy import (
- StandardSearchStrategy,
- )
-
- self.strategy = StandardSearchStrategy(
+ # Use factory for all other strategies
+ logger.info(f"Creating {strategy_name} strategy using factory")
+ self.strategy = create_strategy(
+ strategy_name=strategy_name,
model=self.model,
search=self.search,
all_links_of_system=self.all_links_of_system,
settings_snapshot=self.settings_snapshot,
+ # Pass strategy-specific parameters
+ include_text_content=include_text_content,
+ use_cross_engine_filter=use_cross_engine_filter,
+ use_atomic_facts=use_atomic_facts,
+ max_iterations=self.max_iterations,
+ questions_per_iteration=self.questions_per_iteration,
+ # Special parameters for iterative strategy
+ search_iterations_per_round=self.max_iterations or 1,
+ questions_per_search=self.questions_per_iteration,
+ # Special parameters for adaptive strategy
+ max_steps=self.max_iterations,
+ source_questions_per_iteration=self.questions_per_iteration,
+ # Special parameters for evidence and constrained strategies
+ max_search_iterations=self.max_iterations,
+ # Special parameters for focused iteration
+ use_browsecomp_optimization=True,
)
# Log the actual strategy class
diff --git a/src/local_deep_research/search_system_factory.py b/src/local_deep_research/search_system_factory.py
new file mode 100644
index 0000000000..bd9b25d21b
--- /dev/null
+++ b/src/local_deep_research/search_system_factory.py
@@ -0,0 +1,646 @@
+"""
+Factory for creating search strategies.
+This module provides a centralized way to create search strategies
+to avoid code duplication.
+"""
+
+from loguru import logger
+from typing import Optional, Dict, Any, List
+from langchain_core.language_models import BaseChatModel
+
+
+def create_strategy(
+ strategy_name: str,
+ model: BaseChatModel,
+ search: Any,
+ all_links_of_system: Optional[List[Dict]] = None,
+ settings_snapshot: Optional[Dict] = None,
+ research_context: Optional[Dict] = None,
+ **kwargs,
+):
+ """
+ Create a search strategy by name.
+
+ Args:
+ strategy_name: Name of the strategy to create
+ model: Language model to use
+ search: Search engine instance
+ all_links_of_system: List of existing links
+ settings_snapshot: Settings snapshot
+ research_context: Research context for special strategies
+ **kwargs: Additional strategy-specific parameters
+
+ Returns:
+ Strategy instance
+ """
+ if all_links_of_system is None:
+ all_links_of_system = []
+
+ strategy_name_lower = strategy_name.lower()
+
+ # Source-based strategy
+ if strategy_name_lower in [
+ "source-based",
+ "source_based",
+ "source_based_search",
+ ]:
+ from .advanced_search_system.strategies.source_based_strategy import (
+ SourceBasedSearchStrategy,
+ )
+
+ return SourceBasedSearchStrategy(
+ model=model,
+ search=search,
+ include_text_content=kwargs.get("include_text_content", True),
+ use_cross_engine_filter=kwargs.get("use_cross_engine_filter", True),
+ all_links_of_system=all_links_of_system,
+ use_atomic_facts=kwargs.get("use_atomic_facts", False),
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Focused iteration strategy
+ elif strategy_name_lower in ["focused-iteration", "focused_iteration"]:
+ from .advanced_search_system.strategies.focused_iteration_strategy import (
+ FocusedIterationStrategy,
+ )
+
+ return FocusedIterationStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ knowledge_accumulation_mode=kwargs.get(
+ "knowledge_accumulation_mode", True
+ ),
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Multi-source strategy
+ elif strategy_name_lower in [
+ "multi-source",
+ "multi_source",
+ "multi-source_cross_reference",
+ ]:
+ from .advanced_search_system.strategies.multi_source_strategy import (
+ MultiSourceCrossReferenceStrategy,
+ )
+
+ return MultiSourceCrossReferenceStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ knowledge_accumulation_mode=kwargs.get(
+ "knowledge_accumulation_mode", True
+ ),
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Academic strategy
+ elif strategy_name_lower in ["academic", "academic_deep_dive"]:
+ from .advanced_search_system.strategies.academic_strategy import (
+ AcademicDeepDiveStrategy,
+ )
+
+ return AcademicDeepDiveStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ knowledge_accumulation_mode=kwargs.get(
+ "knowledge_accumulation_mode", True
+ ),
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Investigative strategy
+ elif strategy_name_lower in ["investigative", "investigative_journalism"]:
+ from .advanced_search_system.strategies.investigative_strategy import (
+ InvestigativeJournalismStrategy,
+ )
+
+ return InvestigativeJournalismStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Comprehensive strategy
+ elif strategy_name_lower in ["comprehensive", "comprehensive_analysis"]:
+ from .advanced_search_system.strategies.comprehensive_strategy import (
+ ComprehensiveAnalysisStrategy,
+ )
+
+ return ComprehensiveAnalysisStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Adaptive strategy
+ elif strategy_name_lower in ["adaptive", "adaptive_research"]:
+ from .advanced_search_system.strategies.adaptive_strategy import (
+ AdaptiveResearchStrategy,
+ )
+
+ return AdaptiveResearchStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ knowledge_accumulation_mode=kwargs.get(
+ "knowledge_accumulation_mode", True
+ ),
+ initial_strategy=kwargs.get("initial_strategy", "source-based"),
+ max_strategy_switches=kwargs.get("max_strategy_switches", 2),
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Iterative reasoning strategy
+ elif strategy_name_lower in [
+ "iterative-reasoning",
+ "iterative_reasoning",
+ "iterative_reasoning_depth",
+ ]:
+ from .advanced_search_system.strategies.iterative_reasoning_strategy import (
+ IterativeReasoningDepthStrategy,
+ )
+
+ return IterativeReasoningDepthStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ use_atomic_facts=kwargs.get("use_atomic_facts", True),
+ settings_snapshot=settings_snapshot,
+ )
+
+ # News aggregation strategy
+ elif strategy_name_lower in [
+ "news",
+ "news_aggregation",
+ "news-aggregation",
+ ]:
+ from .advanced_search_system.strategies.news_strategy import (
+ NewsAggregationStrategy,
+ )
+
+ return NewsAggregationStrategy()
+
+ # IterDRAG strategy
+ elif strategy_name_lower == "iterdrag":
+ from .advanced_search_system.strategies.iterdrag_strategy import (
+ IterDRAGStrategy,
+ )
+
+ return IterDRAGStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Parallel strategy
+ elif strategy_name_lower == "parallel":
+ from .advanced_search_system.strategies.parallel_search_strategy import (
+ ParallelSearchStrategy,
+ )
+
+ return ParallelSearchStrategy(
+ model=model,
+ search=search,
+ include_text_content=kwargs.get("include_text_content", True),
+ use_cross_engine_filter=kwargs.get("use_cross_engine_filter", True),
+ all_links_of_system=all_links_of_system,
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Rapid strategy
+ elif strategy_name_lower == "rapid":
+ from .advanced_search_system.strategies.rapid_search_strategy import (
+ RapidSearchStrategy,
+ )
+
+ return RapidSearchStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Recursive decomposition strategy
+ elif strategy_name_lower in ["recursive", "recursive-decomposition"]:
+ from .advanced_search_system.strategies.recursive_decomposition_strategy import (
+ RecursiveDecompositionStrategy,
+ )
+
+ return RecursiveDecompositionStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Iterative reasoning strategy (different from iterative_reasoning_depth)
+ elif strategy_name_lower == "iterative":
+ from .advanced_search_system.strategies.iterative_reasoning_strategy import (
+ IterativeReasoningStrategy,
+ )
+
+ # Get iteration settings from kwargs or use defaults
+ max_iterations = kwargs.get("max_iterations", 20)
+ questions_per_iteration = kwargs.get("questions_per_iteration", 3)
+ search_iterations_per_round = kwargs.get(
+ "search_iterations_per_round", 1
+ )
+
+ return IterativeReasoningStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ max_iterations=max_iterations,
+ confidence_threshold=kwargs.get("confidence_threshold", 0.95),
+ search_iterations_per_round=search_iterations_per_round,
+ questions_per_search=questions_per_iteration,
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Adaptive decomposition strategy (different from adaptive_research)
+ elif strategy_name_lower == "adaptive":
+ from .advanced_search_system.strategies.adaptive_decomposition_strategy import (
+ AdaptiveDecompositionStrategy,
+ )
+
+ return AdaptiveDecompositionStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ max_steps=kwargs.get("max_steps", kwargs.get("max_iterations", 5)),
+ min_confidence=kwargs.get("min_confidence", 0.8),
+ source_search_iterations=kwargs.get("source_search_iterations", 2),
+ source_questions_per_iteration=kwargs.get(
+ "source_questions_per_iteration",
+ kwargs.get("questions_per_iteration", 3),
+ ),
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Smart decomposition strategy
+ elif strategy_name_lower == "smart":
+ from .advanced_search_system.strategies.smart_decomposition_strategy import (
+ SmartDecompositionStrategy,
+ )
+
+ return SmartDecompositionStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ max_iterations=kwargs.get("max_iterations", 5),
+ source_search_iterations=kwargs.get("source_search_iterations", 2),
+ source_questions_per_iteration=kwargs.get(
+ "source_questions_per_iteration",
+ kwargs.get("questions_per_iteration", 3),
+ ),
+ settings_snapshot=settings_snapshot,
+ )
+
+ # BrowseComp optimized strategy
+ elif strategy_name_lower == "browsecomp":
+ from .advanced_search_system.strategies.browsecomp_optimized_strategy import (
+ BrowseCompOptimizedStrategy,
+ )
+
+ return BrowseCompOptimizedStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ max_browsecomp_iterations=kwargs.get(
+ "max_browsecomp_iterations", 15
+ ),
+ confidence_threshold=kwargs.get("confidence_threshold", 0.9),
+ max_iterations=kwargs.get("max_iterations", 5),
+ questions_per_iteration=kwargs.get("questions_per_iteration", 3),
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Enhanced evidence-based strategy
+ elif strategy_name_lower == "evidence":
+ from .advanced_search_system.strategies.evidence_based_strategy_v2 import (
+ EnhancedEvidenceBasedStrategy,
+ )
+
+ return EnhancedEvidenceBasedStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ max_iterations=kwargs.get("max_iterations", 20),
+ confidence_threshold=kwargs.get("confidence_threshold", 0.95),
+ candidate_limit=kwargs.get("candidate_limit", 20),
+ evidence_threshold=kwargs.get("evidence_threshold", 0.9),
+ max_search_iterations=kwargs.get("max_search_iterations", 5),
+ questions_per_iteration=kwargs.get("questions_per_iteration", 3),
+ min_candidates_threshold=kwargs.get("min_candidates_threshold", 10),
+ enable_pattern_learning=kwargs.get("enable_pattern_learning", True),
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Constrained search strategy
+ elif strategy_name_lower == "constrained":
+ from .advanced_search_system.strategies.constrained_search_strategy import (
+ ConstrainedSearchStrategy,
+ )
+
+ return ConstrainedSearchStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ max_iterations=kwargs.get("max_iterations", 20),
+ confidence_threshold=kwargs.get("confidence_threshold", 0.95),
+ candidate_limit=kwargs.get("candidate_limit", 100),
+ evidence_threshold=kwargs.get("evidence_threshold", 0.9),
+ max_search_iterations=kwargs.get("max_search_iterations", 5),
+ questions_per_iteration=kwargs.get("questions_per_iteration", 3),
+ min_candidates_per_stage=kwargs.get("min_candidates_per_stage", 20),
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Parallel constrained strategy
+ elif strategy_name_lower in [
+ "parallel-constrained",
+ "parallel_constrained",
+ ]:
+ from .advanced_search_system.strategies.parallel_constrained_strategy import (
+ ParallelConstrainedStrategy,
+ )
+
+ return ParallelConstrainedStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ max_iterations=kwargs.get("max_iterations", 20),
+ confidence_threshold=kwargs.get("confidence_threshold", 0.95),
+ candidate_limit=kwargs.get("candidate_limit", 100),
+ evidence_threshold=kwargs.get("evidence_threshold", 0.9),
+ max_search_iterations=kwargs.get("max_search_iterations", 5),
+ questions_per_iteration=kwargs.get("questions_per_iteration", 3),
+ min_candidates_per_stage=kwargs.get("min_candidates_per_stage", 20),
+ parallel_workers=kwargs.get("parallel_workers", 100),
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Early stop constrained strategy
+ elif strategy_name_lower in [
+ "early-stop-constrained",
+ "early_stop_constrained",
+ ]:
+ from .advanced_search_system.strategies.early_stop_constrained_strategy import (
+ EarlyStopConstrainedStrategy,
+ )
+
+ return EarlyStopConstrainedStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ max_iterations=kwargs.get("max_iterations", 20),
+ confidence_threshold=kwargs.get("confidence_threshold", 0.95),
+ candidate_limit=kwargs.get("candidate_limit", 100),
+ evidence_threshold=kwargs.get("evidence_threshold", 0.9),
+ max_search_iterations=kwargs.get("max_search_iterations", 5),
+ questions_per_iteration=kwargs.get("questions_per_iteration", 3),
+ min_candidates_per_stage=kwargs.get("min_candidates_per_stage", 20),
+ parallel_workers=kwargs.get("parallel_workers", 100),
+ early_stop_threshold=kwargs.get("early_stop_threshold", 0.99),
+ concurrent_evaluation=kwargs.get("concurrent_evaluation", True),
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Smart query strategy
+ elif strategy_name_lower in ["smart-query", "smart_query"]:
+ from .advanced_search_system.strategies.smart_query_strategy import (
+ SmartQueryStrategy,
+ )
+
+ return SmartQueryStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ max_iterations=kwargs.get("max_iterations", 20),
+ confidence_threshold=kwargs.get("confidence_threshold", 0.95),
+ candidate_limit=kwargs.get("candidate_limit", 100),
+ evidence_threshold=kwargs.get("evidence_threshold", 0.9),
+ max_search_iterations=kwargs.get("max_search_iterations", 5),
+ questions_per_iteration=kwargs.get("questions_per_iteration", 3),
+ min_candidates_per_stage=kwargs.get("min_candidates_per_stage", 20),
+ parallel_workers=kwargs.get("parallel_workers", 100),
+ early_stop_threshold=kwargs.get("early_stop_threshold", 0.99),
+ concurrent_evaluation=kwargs.get("concurrent_evaluation", True),
+ use_llm_query_generation=kwargs.get(
+ "use_llm_query_generation", True
+ ),
+ queries_per_combination=kwargs.get("queries_per_combination", 3),
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Dual confidence strategy
+ elif strategy_name_lower in ["dual-confidence", "dual_confidence"]:
+ from .advanced_search_system.strategies.dual_confidence_strategy import (
+ DualConfidenceStrategy,
+ )
+
+ return DualConfidenceStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ max_iterations=kwargs.get("max_iterations", 20),
+ confidence_threshold=kwargs.get("confidence_threshold", 0.95),
+ candidate_limit=kwargs.get("candidate_limit", 100),
+ evidence_threshold=kwargs.get("evidence_threshold", 0.9),
+ max_search_iterations=kwargs.get("max_search_iterations", 5),
+ questions_per_iteration=kwargs.get("questions_per_iteration", 3),
+ min_candidates_per_stage=kwargs.get("min_candidates_per_stage", 20),
+ parallel_workers=kwargs.get("parallel_workers", 100),
+ early_stop_threshold=kwargs.get("early_stop_threshold", 0.95),
+ concurrent_evaluation=kwargs.get("concurrent_evaluation", True),
+ use_llm_query_generation=kwargs.get(
+ "use_llm_query_generation", True
+ ),
+ queries_per_combination=kwargs.get("queries_per_combination", 3),
+ use_entity_seeding=kwargs.get("use_entity_seeding", True),
+ use_direct_property_search=kwargs.get(
+ "use_direct_property_search", True
+ ),
+ uncertainty_penalty=kwargs.get("uncertainty_penalty", 0.2),
+ negative_weight=kwargs.get("negative_weight", 0.5),
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Dual confidence with rejection strategy
+ elif strategy_name_lower in [
+ "dual-confidence-with-rejection",
+ "dual_confidence_with_rejection",
+ ]:
+ from .advanced_search_system.strategies.dual_confidence_with_rejection import (
+ DualConfidenceWithRejectionStrategy,
+ )
+
+ return DualConfidenceWithRejectionStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ max_iterations=kwargs.get("max_iterations", 20),
+ confidence_threshold=kwargs.get("confidence_threshold", 0.95),
+ candidate_limit=kwargs.get("candidate_limit", 100),
+ evidence_threshold=kwargs.get("evidence_threshold", 0.9),
+ max_search_iterations=kwargs.get("max_search_iterations", 5),
+ questions_per_iteration=kwargs.get("questions_per_iteration", 3),
+ min_candidates_per_stage=kwargs.get("min_candidates_per_stage", 20),
+ parallel_workers=kwargs.get("parallel_workers", 100),
+ early_stop_threshold=kwargs.get("early_stop_threshold", 0.95),
+ concurrent_evaluation=kwargs.get("concurrent_evaluation", True),
+ use_llm_query_generation=kwargs.get(
+ "use_llm_query_generation", True
+ ),
+ queries_per_combination=kwargs.get("queries_per_combination", 3),
+ use_entity_seeding=kwargs.get("use_entity_seeding", True),
+ use_direct_property_search=kwargs.get(
+ "use_direct_property_search", True
+ ),
+ uncertainty_penalty=kwargs.get("uncertainty_penalty", 0.2),
+ negative_weight=kwargs.get("negative_weight", 0.5),
+ rejection_threshold=kwargs.get("rejection_threshold", 0.3),
+ positive_threshold=kwargs.get("positive_threshold", 0.2),
+ critical_constraint_rejection=kwargs.get(
+ "critical_constraint_rejection", 0.2
+ ),
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Concurrent dual confidence strategy
+ elif strategy_name_lower in [
+ "concurrent-dual-confidence",
+ "concurrent_dual_confidence",
+ ]:
+ from .advanced_search_system.strategies.concurrent_dual_confidence_strategy import (
+ ConcurrentDualConfidenceStrategy,
+ )
+
+ return ConcurrentDualConfidenceStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ max_iterations=kwargs.get("max_iterations", 20),
+ confidence_threshold=kwargs.get("confidence_threshold", 0.95),
+ candidate_limit=kwargs.get("candidate_limit", 100),
+ evidence_threshold=kwargs.get("evidence_threshold", 0.9),
+ max_search_iterations=kwargs.get("max_search_iterations", 5),
+ questions_per_iteration=kwargs.get("questions_per_iteration", 3),
+ min_candidates_per_stage=kwargs.get("min_candidates_per_stage", 20),
+ parallel_workers=kwargs.get("parallel_workers", 10),
+ early_stop_threshold=kwargs.get("early_stop_threshold", 0.95),
+ concurrent_evaluation=kwargs.get("concurrent_evaluation", True),
+ use_llm_query_generation=kwargs.get(
+ "use_llm_query_generation", True
+ ),
+ queries_per_combination=kwargs.get("queries_per_combination", 3),
+ use_entity_seeding=kwargs.get("use_entity_seeding", True),
+ use_direct_property_search=kwargs.get(
+ "use_direct_property_search", True
+ ),
+ uncertainty_penalty=kwargs.get("uncertainty_penalty", 0.2),
+ negative_weight=kwargs.get("negative_weight", 0.5),
+ rejection_threshold=kwargs.get("rejection_threshold", 0.3),
+ positive_threshold=kwargs.get("positive_threshold", 0.2),
+ critical_constraint_rejection=kwargs.get(
+ "critical_constraint_rejection", 0.2
+ ),
+ min_good_candidates=kwargs.get("min_good_candidates", 3),
+ target_candidates=kwargs.get("target_candidates", 5),
+ max_candidates=kwargs.get("max_candidates", 10),
+ min_score_threshold=kwargs.get("min_score_threshold", 0.65),
+ exceptional_score=kwargs.get("exceptional_score", 0.95),
+ quality_plateau_threshold=kwargs.get(
+ "quality_plateau_threshold", 0.1
+ ),
+ max_search_time=kwargs.get("max_search_time", 30.0),
+ max_evaluations=kwargs.get("max_evaluations", 30),
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Modular strategy
+ elif strategy_name_lower in ["modular", "modular-strategy"]:
+ from .advanced_search_system.strategies.modular_strategy import (
+ ModularStrategy,
+ )
+
+ return ModularStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ constraint_checker_type=kwargs.get(
+ "constraint_checker_type", "dual_confidence"
+ ),
+ exploration_strategy=kwargs.get("exploration_strategy", "adaptive"),
+ early_rejection=kwargs.get("early_rejection", True),
+ early_stopping=kwargs.get("early_stopping", True),
+ llm_constraint_processing=kwargs.get(
+ "llm_constraint_processing", True
+ ),
+ immediate_evaluation=kwargs.get("immediate_evaluation", True),
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Modular parallel strategy
+ elif strategy_name_lower in ["modular-parallel", "modular_parallel"]:
+ from .advanced_search_system.strategies.modular_strategy import (
+ ModularStrategy,
+ )
+
+ return ModularStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ constraint_checker_type="dual_confidence",
+ exploration_strategy="parallel",
+ settings_snapshot=settings_snapshot,
+ )
+
+ # BrowseComp entity strategy
+ elif strategy_name_lower in ["browsecomp-entity", "browsecomp_entity"]:
+ from .advanced_search_system.strategies.browsecomp_entity_strategy import (
+ BrowseCompEntityStrategy,
+ )
+
+ return BrowseCompEntityStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ )
+
+ # Standard strategy
+ elif strategy_name_lower == "standard":
+ from .advanced_search_system.strategies.standard_strategy import (
+ StandardSearchStrategy,
+ )
+
+ return StandardSearchStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ settings_snapshot=settings_snapshot,
+ )
+
+ else:
+ # Default to source-based if unknown
+ logger.warning(
+ f"Unknown strategy: {strategy_name}, defaulting to source-based"
+ )
+ from .advanced_search_system.strategies.source_based_strategy import (
+ SourceBasedSearchStrategy,
+ )
+
+ return SourceBasedSearchStrategy(
+ model=model,
+ search=search,
+ include_text_content=True,
+ use_cross_engine_filter=True,
+ all_links_of_system=all_links_of_system,
+ use_atomic_facts=False,
+ settings_snapshot=settings_snapshot,
+ )
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index 9275bcf38c..88ac13ce1c 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -411,6 +411,12 @@ def register_blueprints(app):
app.register_blueprint(news_routes.bp)
logger.info("News API routes registered successfully")
+ # Register follow-up research routes
+ from ..followup_research.routes import followup_bp
+
+ app.register_blueprint(followup_bp)
+ logger.info("Follow-up research routes registered successfully")
+
# Register news page blueprint
from ..news.web import create_news_blueprint
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 7202623506..ebb1911b34 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -272,6 +272,7 @@ def run_research_process(
**kwargs: Additional parameters for the research (model_provider, model, search_engine, etc.)
MUST include 'username' for database access
"""
+
# Extract username - required for database access
username = kwargs.get("username")
logger.info(
@@ -387,6 +388,13 @@ def run_research_process(
"user_password": user_password, # Add password for metrics access
}
+ # If this is a follow-up research, include the parent context
+ if "research_context" in kwargs and kwargs["research_context"]:
+ logger.info(
+ f"Adding parent research context with {len(kwargs['research_context'].get('past_findings', ''))} chars of findings"
+ )
+ shared_research_context.update(kwargs["research_context"])
+
logger.info(
f"Created shared_research_context with username: {username}, all keys: {list(shared_research_context.keys())}"
)
@@ -869,6 +877,23 @@ def run_research_process(
- Generated at: {datetime.now(UTC).isoformat()}
"""
+ # Save sources to database
+ from .research_sources_service import ResearchSourcesService
+
+ sources_service = ResearchSourcesService()
+ if all_links:
+ logger.info(
+ f"Quick summary: Saving {len(all_links)} sources to database"
+ )
+ sources_saved = sources_service.save_research_sources(
+ research_id=research_id,
+ sources=all_links,
+ username=username,
+ )
+ logger.info(
+ f"Quick summary: Saved {sources_saved} sources for research {research_id}"
+ )
+
# Save report using storage abstraction
from ...storage import get_report_storage
@@ -1133,6 +1158,26 @@ def run_research_process(
final_report["content"]
)
+ # Save sources to database
+ from .research_sources_service import ResearchSourcesService
+
+ sources_service = ResearchSourcesService()
+ if (
+ hasattr(search_system, "all_links_of_system")
+ and search_system.all_links_of_system
+ ):
+ logger.info(
+ f"Saving {len(search_system.all_links_of_system)} sources to database"
+ )
+ sources_saved = sources_service.save_research_sources(
+ research_id=research_id,
+ sources=search_system.all_links_of_system,
+ username=username,
+ )
+ logger.info(
+ f"Saved {sources_saved} sources for research {research_id}"
+ )
+
# Save report using cached service
from ...memory_cache.cached_services import CachedResearchService
diff --git a/src/local_deep_research/web/services/research_sources_service.py b/src/local_deep_research/web/services/research_sources_service.py
new file mode 100644
index 0000000000..f658a22641
--- /dev/null
+++ b/src/local_deep_research/web/services/research_sources_service.py
@@ -0,0 +1,280 @@
+"""
+Service for managing research sources/resources in the database.
+
+This service handles saving and retrieving sources from research
+in a proper relational way using the ResearchResource table.
+"""
+
+from typing import List, Dict, Any, Optional
+from datetime import datetime, UTC
+from loguru import logger
+
+from ...database.models import ResearchResource, ResearchHistory
+from ...database.session_context import get_user_db_session
+
+
+class ResearchSourcesService:
+ """Service for managing research sources in the database."""
+
+ @staticmethod
+ def save_research_sources(
+ research_id: str,
+ sources: List[Dict[str, Any]],
+ username: Optional[str] = None,
+ ) -> int:
+ """
+ Save sources from research to the ResearchResource table.
+
+ Args:
+ research_id: The UUID of the research
+ sources: List of source dictionaries with url, title, snippet, etc.
+ username: Username for database access
+
+ Returns:
+ Number of sources saved
+ """
+ if not sources:
+ logger.info(f"No sources to save for research {research_id}")
+ return 0
+
+ saved_count = 0
+
+ try:
+ with get_user_db_session(username) as db_session:
+ # First check if resources already exist for this research
+ existing = (
+ db_session.query(ResearchResource)
+ .filter_by(research_id=research_id)
+ .count()
+ )
+
+ if existing > 0:
+ logger.info(
+ f"Research {research_id} already has {existing} resources, skipping save"
+ )
+ return existing
+
+ # Save each source as a ResearchResource
+ for source in sources:
+ try:
+ # Extract fields from various possible formats
+ url = source.get("url", "") or source.get("link", "")
+ title = source.get("title", "") or source.get(
+ "name", ""
+ )
+ snippet = (
+ source.get("snippet", "")
+ or source.get("content_preview", "")
+ or source.get("description", "")
+ )
+ source_type = source.get("source_type", "web")
+
+ # Skip if no URL
+ if not url:
+ continue
+
+ # Create resource record
+ resource = ResearchResource(
+ research_id=research_id,
+ title=title or "Untitled",
+ url=url,
+ content_preview=snippet[:1000]
+ if snippet
+ else None, # Limit preview length
+ source_type=source_type,
+ resource_metadata={
+ "added_at": datetime.now(UTC).isoformat(),
+ "original_data": source, # Keep original data for reference
+ },
+ created_at=datetime.now(UTC).isoformat(),
+ )
+
+ db_session.add(resource)
+ saved_count += 1
+
+ except Exception as e:
+ logger.warning(
+ f"Failed to save source {source.get('url', 'unknown')}: {e}"
+ )
+ continue
+
+ # Commit all resources
+ if saved_count > 0:
+ db_session.commit()
+ logger.info(
+ f"Saved {saved_count} sources for research {research_id}"
+ )
+
+ except Exception:
+ logger.exception("Error saving research sources")
+ raise
+
+ return saved_count
+
+ @staticmethod
+ def get_research_sources(
+ research_id: str, username: Optional[str] = None
+ ) -> List[Dict[str, Any]]:
+ """
+ Get all sources for a research from the database.
+
+ Args:
+ research_id: The UUID of the research
+ username: Username for database access
+
+ Returns:
+ List of source dictionaries
+ """
+ sources = []
+
+ try:
+ with get_user_db_session(username) as db_session:
+ resources = (
+ db_session.query(ResearchResource)
+ .filter_by(research_id=research_id)
+ .order_by(ResearchResource.id.asc())
+ .all()
+ )
+
+ for resource in resources:
+ sources.append(
+ {
+ "id": resource.id,
+ "url": resource.url,
+ "title": resource.title,
+ "snippet": resource.content_preview,
+ "content_preview": resource.content_preview,
+ "source_type": resource.source_type,
+ "metadata": resource.resource_metadata or {},
+ "created_at": resource.created_at,
+ }
+ )
+
+ logger.info(
+ f"Retrieved {len(sources)} sources for research {research_id}"
+ )
+
+ except Exception:
+ logger.exception("Error retrieving research sources")
+ raise
+
+ return sources
+
+ @staticmethod
+ def copy_sources_to_new_research(
+ from_research_id: str,
+ to_research_id: str,
+ source_ids: Optional[List[int]] = None,
+ username: Optional[str] = None,
+ ) -> int:
+ """
+ Copy sources from one research to another (useful for follow-ups).
+
+ Args:
+ from_research_id: Source research ID
+ to_research_id: Destination research ID
+ source_ids: Optional list of specific source IDs to copy
+ username: Username for database access
+
+ Returns:
+ Number of sources copied
+ """
+ copied_count = 0
+
+ try:
+ with get_user_db_session(username) as db_session:
+ # Get sources to copy
+ query = db_session.query(ResearchResource).filter_by(
+ research_id=from_research_id
+ )
+
+ if source_ids:
+ query = query.filter(ResearchResource.id.in_(source_ids))
+
+ sources_to_copy = query.all()
+
+ # Copy each source
+ for source in sources_to_copy:
+ new_resource = ResearchResource(
+ research_id=to_research_id,
+ title=source.title,
+ url=source.url,
+ content_preview=source.content_preview,
+ source_type=source.source_type,
+ resource_metadata={
+ **(source.resource_metadata or {}),
+ "copied_from": from_research_id,
+ "copied_at": datetime.now(UTC).isoformat(),
+ },
+ created_at=datetime.now(UTC).isoformat(),
+ )
+
+ db_session.add(new_resource)
+ copied_count += 1
+
+ if copied_count > 0:
+ db_session.commit()
+ logger.info(
+ f"Copied {copied_count} sources from {from_research_id} to {to_research_id}"
+ )
+
+ except Exception:
+ logger.exception("Error copying research sources")
+ raise
+
+ return copied_count
+
+ @staticmethod
+ def update_research_with_sources(
+ research_id: str,
+ all_links_of_system: List[Dict[str, Any]],
+ username: Optional[str] = None,
+ ) -> bool:
+ """
+ Update a completed research with its sources.
+ This should be called when research completes.
+
+ Args:
+ research_id: The UUID of the research
+ all_links_of_system: List of all sources found during research
+ username: Username for database access
+
+ Returns:
+ True if successful
+ """
+ try:
+ # Save sources to ResearchResource table
+ saved_count = ResearchSourcesService.save_research_sources(
+ research_id, all_links_of_system, username
+ )
+
+ # Also update the research metadata to include source count
+ with get_user_db_session(username) as db_session:
+ research = (
+ db_session.query(ResearchHistory)
+ .filter_by(id=research_id)
+ .first()
+ )
+
+ if research:
+ if not research.research_meta:
+ research.research_meta = {}
+
+ # Update metadata with source information
+ research.research_meta["sources_count"] = saved_count
+ research.research_meta["has_sources"] = saved_count > 0
+
+ db_session.commit()
+ logger.info(
+ f"Updated research {research_id} with {saved_count} sources"
+ )
+ return True
+ else:
+ logger.warning(
+ f"Research {research_id} not found for source update"
+ )
+ return False
+
+ except Exception:
+ logger.exception("Error updating research with sources")
+ return False
diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.js
index 23a4360963..ebe62c69f1 100644
--- a/src/local_deep_research/web/static/js/components/research.js
+++ b/src/local_deep_research/web/static/js/components/research.js
@@ -20,8 +20,6 @@
let searchEngineDropdown = null;
let searchEngineDropdownList = null;
let searchEngineRefreshBtn = null;
- let iterationsInput = null;
- let questionsPerIterationInput = null;
let advancedToggle = null;
let advancedPanel = null;
@@ -134,8 +132,6 @@
searchEngineRefreshBtn = document.getElementById('search_engine-refresh');
// Other form elements
- iterationsInput = document.getElementById('iterations');
- questionsPerIterationInput = document.getElementById('questions_per_iteration');
advancedToggle = document.querySelector('.advanced-options-toggle');
advancedPanel = document.querySelector('.advanced-options-panel');
@@ -670,6 +666,7 @@
}
// Iterations change - save to settings manager
+ const iterationsInput = document.getElementById('iterations');
if (iterationsInput) {
iterationsInput.addEventListener('change', function() {
const iterations = parseInt(this.value);
@@ -679,8 +676,9 @@
}
// Questions per iteration change - save to settings manager
- if (questionsPerIterationInput) {
- questionsPerIterationInput.addEventListener('change', function() {
+ const questionsInput = document.getElementById('questions_per_iteration');
+ if (questionsInput) {
+ questionsInput.addEventListener('change', function() {
const questions = parseInt(this.value);
console.log('Questions per iteration changed to:', questions);
saveSearchSetting('search.questions_per_iteration', questions);
@@ -2072,15 +2070,18 @@
// Get other form values
const customEndpoint = customEndpointInput ? customEndpointInput.value : '';
- const iterations = iterationsInput ? parseInt(iterationsInput.value, 10) : 2;
- const questionsPerIteration = questionsPerIterationInput ?
- parseInt(questionsPerIterationInput.value, 10) : 3;
const enableNotifications = notificationToggle ? notificationToggle.checked : true;
// Get strategy value
const strategySelect = document.getElementById('strategy');
const strategy = strategySelect ? strategySelect.value : 'source-based';
+ // Get iterations and questions per iteration
+ const iterationsInput = document.getElementById('iterations');
+ const iterations = iterationsInput ? parseInt(iterationsInput.value) : 2;
+ const questionsInput = document.getElementById('questions_per_iteration');
+ const questionsPerIteration = questionsInput ? parseInt(questionsInput.value) : 3;
+
// Validate the query
if (!query) {
// Show error if query is empty
@@ -2105,9 +2106,9 @@
model: model,
custom_endpoint: customEndpoint,
search_engine: searchEngine,
+ strategy: strategy,
iterations: iterations,
- questions_per_iteration: questionsPerIteration,
- strategy: strategy
+ questions_per_iteration: questionsPerIteration
};
console.log('Submitting research with data:', formData);
diff --git a/src/local_deep_research/web/static/js/followup.js b/src/local_deep_research/web/static/js/followup.js
new file mode 100644
index 0000000000..a134e6acee
--- /dev/null
+++ b/src/local_deep_research/web/static/js/followup.js
@@ -0,0 +1,366 @@
+/**
+ * Follow-up Research JavaScript Module
+ *
+ * Handles UI interactions for asking follow-up questions on existing research.
+ */
+
+class FollowUpResearch {
+ constructor() {
+ this.parentResearchId = null;
+ this.modalElement = null;
+ }
+
+ /**
+ * Initialize follow-up button on research results
+ */
+ init() {
+ // Get research ID from page
+ this.parentResearchId = this.getResearchIdFromPage();
+
+ console.log('Follow-up Research: Parent research ID:', this.parentResearchId);
+
+ // Set up the follow-up button if it exists
+ const followUpBtn = document.getElementById('ask-followup-btn');
+ if (followUpBtn) {
+ if (this.parentResearchId) {
+ followUpBtn.onclick = () => this.showFollowUpModal();
+ } else {
+ console.warn('Follow-up Research: No research ID found, disabling button');
+ followUpBtn.disabled = true;
+ followUpBtn.title = 'No research ID available';
+ }
+ }
+
+ // Create modal for follow-up questions
+ this.createModal();
+ }
+
+ /**
+ * Get research ID from current page
+ */
+ getResearchIdFromPage() {
+ // Try multiple ways to get research ID
+
+ // 1. From URL path (e.g., /results/abc-123-def)
+ const pathMatch = window.location.pathname.match(/\/results\/([a-zA-Z0-9-]+)/);
+ if (pathMatch) {
+ return pathMatch[1];
+ }
+
+ // 2. From URL params
+ const urlParams = new URLSearchParams(window.location.search);
+ const paramId = urlParams.get('research_id');
+ if (paramId) {
+ return paramId;
+ }
+
+ // 3. From data attribute
+ const dataId = document.querySelector('[data-research-id]')?.dataset.researchId;
+ if (dataId) {
+ return dataId;
+ }
+
+ // 4. From window variable (set by results.js)
+ if (window.currentResearchId) {
+ return window.currentResearchId;
+ }
+
+ return null;
+ }
+
+ /**
+ * Create modal for follow-up questions
+ */
+ async createModal() {
+ // Check if modal already exists
+ if (document.getElementById('followUpModal')) {
+ return;
+ }
+
+ // Load modal template from server
+ try {
+ const response = await fetch('/static/templates/followup_modal.html');
+ if (!response.ok) {
+ throw new Error(`Failed to load modal template: ${response.status}`);
+ }
+
+ const modalHtml = await response.text();
+ document.body.insertAdjacentHTML('beforeend', modalHtml);
+ this.modalElement = document.getElementById('followUpModal');
+ this.attachModalEventHandlers();
+ this.addModalStyles();
+ } catch (e) {
+ console.error('Error loading follow-up modal template:', e);
+ // Show error message to user
+ this.showModalLoadError();
+ }
+ }
+
+ /**
+ * 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 needed
+ if (!document.getElementById('followup-modal-styles')) {
+ const styles = `
+ <style id="followup-modal-styles">
+ .modal-backdrop {
+ position: fixed;
+ top: 0;
+ left: 0;
+ z-index: 1040;
+ width: 100vw;
+ height: 100vh;
+ background-color: #000;
+ opacity: 0.5;
+ }
+ #followUpModal {
+ position: fixed;
+ top: 0;
+ left: 0;
+ z-index: 1050;
+ width: 100%;
+ height: 100%;
+ overflow-x: hidden;
+ overflow-y: auto;
+ outline: 0;
+ display: none;
+ }
+ #followUpModal.show {
+ display: flex !important;
+ align-items: center;
+ justify-content: center;
+ }
+ #followUpModal .modal-dialog {
+ position: relative;
+ margin: 1.75rem auto;
+ max-width: 800px;
+ }
+ #followUpModal .modal-content {
+ background: #1a1a1a;
+ color: #e0e0e0;
+ border-radius: 0.5rem;
+ box-shadow: 0 10px 25px rgba(0,0,0,0.5);
+ border: 1px solid #333;
+ }
+ #followUpModal .modal-header {
+ border-bottom: 1px solid #333;
+ }
+ #followUpModal .modal-footer {
+ border-top: 1px solid #333;
+ }
+ #followUpModal .btn-close {
+ filter: invert(1);
+ }
+ #followUpModal .form-control,
+ #followUpModal .form-select {
+ background-color: #2a2a2a;
+ color: #e0e0e0;
+ border: 1px solid #444;
+ }
+ #followUpModal .form-control:focus,
+ #followUpModal .form-select:focus {
+ background-color: #2a2a2a;
+ color: #e0e0e0;
+ border-color: #007bff;
+ box-shadow: 0 0 0 0.2rem rgba(0,123,255,0.25);
+ }
+ #followUpModal .bg-light {
+ background-color: #2a2a2a !important;
+ }
+ #followUpModal .text-muted {
+ color: #999 !important;
+ }
+ #followUpModal .alert-info {
+ background-color: #1e3a5f;
+ border-color: #2d5a8f;
+ color: #9ec5fe;
+ }
+ </style>
+ `;
+ document.head.insertAdjacentHTML('beforeend', styles);
+ }
+ }
+
+ /**
+ * Show follow-up modal and load parent context
+ */
+ async showFollowUpModal() {
+ if (!this.modalElement) {
+ await this.createModal();
+ }
+
+ // Only proceed if modal was successfully created
+ if (!this.modalElement) {
+ return;
+ }
+
+ // Load parent context
+ await this.loadParentContext();
+
+ // Show modal
+ const modal = new bootstrap.Modal(this.modalElement);
+ modal.show();
+ }
+
+ /**
+ * Show error message when modal template fails to load
+ */
+ showModalLoadError() {
+ const followUpBtn = document.getElementById('ask-followup-btn');
+ if (followUpBtn) {
+ followUpBtn.disabled = true;
+ followUpBtn.title = 'Failed to load follow-up modal template';
+ }
+
+ // Show user-friendly error
+ alert('Unable to load follow-up interface. Please refresh the page and try again.');
+ }
+
+ /**
+ * Load parent research context
+ */
+ async loadParentContext() {
+ try {
+ // Get CSRF token from meta tag or cookie
+ let csrfToken = '';
+ const csrfMeta = document.querySelector('meta[name="csrf-token"]');
+ if (csrfMeta) {
+ csrfToken = csrfMeta.content;
+ } else {
+ // Try to get from cookie
+ const cookies = document.cookie.split(';');
+ for (let cookie of cookies) {
+ const [name, value] = cookie.trim().split('=');
+ if (name === 'csrf_token') {
+ csrfToken = decodeURIComponent(value);
+ break;
+ }
+ }
+ }
+
+ const response = await fetch('/api/followup/prepare', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({
+ parent_research_id: this.parentResearchId,
+ question: 'test' // Needs a non-empty question
+ })
+ });
+
+ const data = await response.json();
+
+ if (data.success) {
+ // Display parent context
+ document.getElementById('parentContext').style.display = 'block';
+ document.getElementById('parentSummary').textContent = data.parent_summary;
+ document.getElementById('parentSources').textContent = data.available_sources;
+ }
+ } catch (error) {
+ console.error('Error loading parent context:', error);
+ }
+ }
+
+ /**
+ * Submit follow-up research
+ */
+ async submitFollowUp() {
+ const question = document.getElementById('followUpQuestion').value.trim();
+ if (!question) {
+ alert('Please enter a follow-up question');
+ return;
+ }
+
+ if (!this.parentResearchId) {
+ alert('No parent research ID available');
+ return;
+ }
+
+ console.log('Submitting follow-up research:', {
+ parent_research_id: this.parentResearchId,
+ question: question
+ });
+
+ try {
+ // Get CSRF token from meta tag or cookie
+ let csrfToken = '';
+ const csrfMeta = document.querySelector('meta[name="csrf-token"]');
+ if (csrfMeta) {
+ csrfToken = csrfMeta.content;
+ } else {
+ // Try to get from cookie
+ const cookies = document.cookie.split(';');
+ for (let cookie of cookies) {
+ const [name, value] = cookie.trim().split('=');
+ if (name === 'csrf_token') {
+ csrfToken = decodeURIComponent(value);
+ break;
+ }
+ }
+ }
+
+ // Start follow-up research
+ const response = await fetch('/api/followup/start', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({
+ parent_research_id: this.parentResearchId,
+ question: question
+ // Strategy now comes from database settings
+ })
+ });
+
+ if (!response.ok) {
+ console.error('Follow-up API error:', response.status, response.statusText);
+ const text = await response.text();
+ console.error('Response body:', text);
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+
+ const data = await response.json();
+ console.log('Follow-up API response:', data);
+
+ if (data.success) {
+ // Close modal
+ bootstrap.Modal.getInstance(this.modalElement).hide();
+
+ // Redirect to progress page to show the research is running
+ window.location.href = `/progress/${data.research_id}`;
+ } else {
+ alert('Error starting follow-up research: ' + (data.error || 'Unknown error'));
+ }
+ } catch (error) {
+ console.error('Error submitting follow-up:', error);
+ alert('Failed to start follow-up research: ' + error.message);
+ }
+ }
+}
+
+// Initialize on page load
+const followUpResearch = new FollowUpResearch();
+document.addEventListener('DOMContentLoaded', () => {
+ followUpResearch.init();
+});
+
+// Helper function for toggling advanced options
+function toggleAdvancedOptions(event) {
+ event.preventDefault();
+ const panel = document.getElementById('advancedOptionsPanel');
+ panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
+}
diff --git a/src/local_deep_research/web/static/js/research_form.js b/src/local_deep_research/web/static/js/research_form.js
index 6a9c8f6273..dac4e8e865 100644
--- a/src/local_deep_research/web/static/js/research_form.js
+++ b/src/local_deep_research/web/static/js/research_form.js
@@ -37,11 +37,11 @@ function initResearchForm() {
// Look for the iterations setting
for (const key in settings) {
const setting = settings[key];
- if (key === 'search.iterations') {
+ if (key === 'search.iterations' && iterationsInput) {
iterationsInput.value = setting.value;
}
- if (key === 'search.questions_per_iteration') {
+ if (key === 'search.questions_per_iteration' && questionsInput) {
questionsInput.value = setting.value;
}
}
@@ -79,12 +79,24 @@ function patchFormSubmitHandler() {
* Save research settings to the database
*/
function saveResearchSettings() {
- const iterations = document.getElementById('iterations').value;
- const questions = document.getElementById('questions_per_iteration').value;
+ const iterationsInput = document.getElementById('iterations');
+ const questionsInput = document.getElementById('questions_per_iteration');
+
+ // Only save if the elements exist (not on follow-up modal)
+ if (!iterationsInput || !questionsInput) {
+ return;
+ }
+ const iterations = iterationsInput.value;
+ const questions = questionsInput.value;
// Get CSRF token
- const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+
+ if (!csrfToken) {
+ console.warn('CSRF token not found, skipping settings save');
+ return;
+ }
// Save settings
fetch(URLS.SETTINGS_API.SAVE_ALL_SETTINGS, {
@@ -100,8 +112,10 @@ function saveResearchSettings() {
})
.then(response => response.json())
.then(data => {
+ console.log('Research settings saved');
})
.catch(error => {
+ console.error('Error saving research settings:', error);
});
}
diff --git a/src/local_deep_research/web/static/templates/followup_modal.html b/src/local_deep_research/web/static/templates/followup_modal.html
new file mode 100644
index 0000000000..f6f7942a64
--- /dev/null
+++ b/src/local_deep_research/web/static/templates/followup_modal.html
@@ -0,0 +1,47 @@
+<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">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h5 class="modal-title">Ask a Follow-up Question</h5>
+ <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
+ </div>
+ <div class="modal-body">
+ <div class="alert alert-info">
+ <i class="fas fa-info-circle"></i>
+ <strong>What you can do with follow-up:</strong>
+ <ul class="mb-0 mt-2">
+ <li>Ask deeper questions about the research findings</li>
+ <li>Request different formatting (e.g., "provide this data in a table")</li>
+ <li>Explore specific aspects in more detail</li>
+ <li>Get clarification on complex topics</li>
+ </ul>
+ <small class="d-block mt-2">Your follow-up will build on the previous research context and sources.</small>
+ </div>
+
+ <div id="parentContext" class="mb-3 p-3 bg-light rounded" style="display: none;">
+ <h6>Previous Research:</h6>
+ <p id="parentSummary" class="text-muted"></p>
+ <small><span id="parentSources"></span> sources available for reuse</small>
+ </div>
+
+ <div class="mb-3">
+ <label for="followUpQuestion" class="form-label">Your Follow-up Question:</label>
+ <textarea
+ id="followUpQuestion"
+ class="form-control"
+ rows="3"
+ placeholder="Examples: 'Can you explain the timeline in more detail?' or 'Format the key findings as a comparison table' or 'What are the long-term implications?'"
+ required
+ ></textarea>
+ </div>
+
+ </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" onclick="followUpResearch.submitFollowUp()">
+ <i class="fas fa-search"></i> Start Follow-up Research
+ </button>
+ </div>
+ </div>
+ </div>
+</div>
diff --git a/src/local_deep_research/web/templates/components/followup_modal.html b/src/local_deep_research/web/templates/components/followup_modal.html
new file mode 100644
index 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/templates/pages/results.html b/src/local_deep_research/web/templates/pages/results.html
index ff2dbe8a0b..6840e3e4e1 100644
--- a/src/local_deep_research/web/templates/pages/results.html
+++ b/src/local_deep_research/web/templates/pages/results.html
@@ -8,6 +8,7 @@
<div class="results-header">
<h1 class="page-title">Research Results</h1>
<div class="results-actions">
+ <button class="btn btn-primary" id="ask-followup-btn" onclick="window.followUpResearch ? followUpResearch.showFollowUpModal() : alert('Follow-up feature loading...')"><i class="fas fa-question-circle"></i> Ask Follow-up Question</button>
<button class="btn btn-outline" id="view-metrics-btn"><i class="fas fa-chart-bar"></i> View Metrics</button>
<button class="btn btn-outline" id="download-pdf-btn"><i class="fas fa-file-pdf"></i> Download PDF</button>
<button class="btn btn-outline" id="export-markdown-btn"><i class="fas fa-file-alt"></i> Export Markdown</button>
@@ -57,7 +58,16 @@
</div>
{% endblock %}
+{% block styles %}
+{{ super() }}
+<!-- Bootstrap CSS for modal -->
+<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
+{% endblock %}
+
{% block page_scripts %}
+<!-- Bootstrap JS for modal functionality -->
+<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
+
<!-- Fallback utilities in case main services are not available -->
<script src="{{ url_for('research.serve_static', path='js/components/fallback/ui.js') }}"></script>
<script src="{{ url_for('research.serve_static', path='js/components/fallback/formatting.js') }}"></script>
@@ -70,4 +80,7 @@
<!-- Results component -->
<script src="{{ url_for('research.serve_static', path='js/components/results.js') }}"></script>
+
+<!-- Follow-up Research component -->
+<script src="{{ url_for('research.serve_static', path='js/followup.js') }}"></script>
{% endblock %}
diff --git a/src/local_deep_research/web/utils/formatters.py b/src/local_deep_research/web/utils/formatters.py
index d65e9ca33e..674ad11a68 100644
--- a/src/local_deep_research/web/utils/formatters.py
+++ b/src/local_deep_research/web/utils/formatters.py
@@ -45,30 +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")
- # Remove SEARCH QUESTIONS BY ITERATION section
- 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()
except Exception as e:
diff --git a/tests/run_followup_tests.sh b/tests/run_followup_tests.sh
new file mode 100755
index 0000000000..28afb3fbbb
--- /dev/null
+++ b/tests/run_followup_tests.sh
@@ -0,0 +1,120 @@
+#!/bin/bash
+# Script to run follow-up research tests locally
+
+echo "🚀 Running Follow-up Research Tests"
+echo "===================================="
+
+# Colors for output
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+NC='\033[0m' # No Color
+
+# Check if server is running
+check_server() {
+ curl -s -f http://127.0.0.1:5000 > /dev/null 2>&1
+ return $?
+}
+
+# Start server if not running
+if ! check_server; then
+ echo -e "${YELLOW}Starting local server...${NC}"
+ cd src
+ nohup python -m local_deep_research.web.app --port 5000 > ../server_test.log 2>&1 &
+ SERVER_PID=$!
+ cd ..
+
+ # Wait for server to start
+ for i in {1..30}; do
+ if check_server; then
+ echo -e "${GREEN}Server started successfully${NC}"
+ break
+ fi
+ sleep 1
+ done
+
+ if ! check_server; then
+ echo -e "${RED}Failed to start server${NC}"
+ cat server_test.log
+ exit 1
+ fi
+else
+ echo -e "${GREEN}Server already running${NC}"
+ SERVER_PID=""
+fi
+
+# Create test directories
+mkdir -p tests/ui_tests/screenshots/followup
+mkdir -p tests/ui_tests/results/followup
+
+# Run API tests
+echo ""
+echo "📝 Running API Tests..."
+echo "----------------------"
+pdm run pytest tests/test_followup_api.py -v --tb=short
+API_EXIT_CODE=$?
+
+if [ $API_EXIT_CODE -eq 0 ]; then
+ echo -e "${GREEN}✓ API tests passed${NC}"
+else
+ echo -e "${RED}✗ API tests failed${NC}"
+fi
+
+# Run UI tests
+echo ""
+echo "🖥️ Running UI Tests..."
+echo "---------------------"
+cd tests/ui_tests
+
+# Install npm dependencies if needed
+if [ ! -d "node_modules" ]; then
+ echo "Installing npm dependencies..."
+ npm install
+fi
+
+# Run the follow-up research test
+HEADLESS=false timeout 300 node test_followup_research.js
+UI_EXIT_CODE=$?
+
+cd ../..
+
+if [ $UI_EXIT_CODE -eq 0 ]; then
+ echo -e "${GREEN}✓ UI tests passed${NC}"
+else
+ echo -e "${RED}✗ UI tests failed or timed out${NC}"
+fi
+
+# Stop server if we started it
+if [ ! -z "$SERVER_PID" ]; then
+ echo ""
+ echo "Stopping test server..."
+ kill $SERVER_PID 2>/dev/null
+fi
+
+# Summary
+echo ""
+echo "===================================="
+echo "Test Summary:"
+echo "===================================="
+if [ $API_EXIT_CODE -eq 0 ]; then
+ echo -e "${GREEN}✓ API Tests: PASSED${NC}"
+else
+ echo -e "${RED}✗ API Tests: FAILED${NC}"
+fi
+
+if [ $UI_EXIT_CODE -eq 0 ]; then
+ echo -e "${GREEN}✓ UI Tests: PASSED${NC}"
+else
+ echo -e "${RED}✗ UI Tests: FAILED${NC}"
+fi
+
+# Exit with error if any test failed
+if [ $API_EXIT_CODE -ne 0 ] || [ $UI_EXIT_CODE -ne 0 ]; then
+ echo ""
+ echo -e "${RED}Some tests failed. Please check the output above.${NC}"
+ exit 1
+else
+ echo ""
+ echo -e "${GREEN}All tests passed successfully! 🎉${NC}"
+ exit 0
+fi
diff --git a/tests/test_followup_api.py b/tests/test_followup_api.py
new file mode 100644
index 0000000000..8138d7c027
--- /dev/null
+++ b/tests/test_followup_api.py
@@ -0,0 +1,411 @@
+"""
+API tests for the Follow-up Research feature.
+
+Tests the API endpoints for preparing and starting follow-up research.
+"""
+
+import json
+import uuid
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from local_deep_research.database.models import (
+ ResearchHistory,
+ ResearchResource,
+)
+from local_deep_research.followup_research.models import FollowUpRequest
+from local_deep_research.followup_research.service import (
+ FollowUpResearchService,
+)
+
+
+class TestFollowUpAPI:
+ """Test suite for follow-up research API endpoints."""
+
+ @pytest.fixture(autouse=True)
+ def mock_db_manager(self):
+ """Mock the database manager for all tests."""
+ with patch(
+ "local_deep_research.web.auth.decorators.db_manager"
+ ) as mock_db:
+ # Mock the database connection check
+ mock_db.connections = {"testuser": MagicMock()}
+ yield mock_db
+
+ @pytest.fixture
+ def app(self):
+ """Create test Flask app."""
+ from local_deep_research.web.app_factory import create_app
+
+ app, _ = create_app() # create_app returns (app, socketio)
+ app.config["TESTING"] = True
+ app.config["WTF_CSRF_ENABLED"] = False
+ return app
+
+ @pytest.fixture
+ def client(self, app):
+ """Create test client."""
+ return app.test_client()
+
+ @pytest.fixture
+ def authenticated_client(self, client, app):
+ """Create authenticated test client."""
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+ sess["authenticated"] = True
+ return client
+
+ @pytest.fixture
+ def mock_research_data(self):
+ """Mock parent research data."""
+ research_id = str(uuid.uuid4())
+ return {
+ "research_id": research_id,
+ "research": ResearchHistory(
+ id=research_id,
+ query="What is quantum computing?",
+ mode="quick_summary",
+ status="completed",
+ created_at="2024-01-01 10:00:00",
+ report_content="Quantum computing uses quantum bits...",
+ ),
+ "resources": [
+ ResearchResource(
+ research_id=research_id,
+ title="Introduction to Quantum Computing",
+ url="https://example.com/quantum",
+ content_preview="Quantum computing is a revolutionary...",
+ source_type="web",
+ ),
+ ResearchResource(
+ research_id=research_id,
+ title="Quantum Gates Explained",
+ url="https://example.com/gates",
+ content_preview="Quantum gates are the building blocks...",
+ source_type="web",
+ ),
+ ],
+ }
+
+ def test_prepare_followup_success(
+ self, authenticated_client, mock_research_data
+ ):
+ """Test successful preparation of follow-up research."""
+ with (
+ patch(
+ "local_deep_research.followup_research.routes.FollowUpResearchService"
+ ) as MockService,
+ patch(
+ "local_deep_research.web.services.settings_manager.SettingsManager"
+ ) as MockSettings,
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as mock_db_session,
+ ):
+ # Setup settings mock
+ mock_settings_mgr = MockSettings.return_value
+ mock_settings_mgr.get_all_settings.return_value = {
+ "search.search_strategy": {"value": "source-based"},
+ }
+
+ # Setup DB session mock
+ mock_db = MagicMock()
+ mock_db_session.return_value.__enter__.return_value = mock_db
+
+ # Setup service mock
+ mock_service = MockService.return_value
+ mock_service.load_parent_research.return_value = {
+ "query": mock_research_data["research"].query,
+ "resources": [
+ {
+ "url": r.url,
+ "title": r.title,
+ "content_preview": r.content_preview,
+ "source_type": r.source_type,
+ }
+ for r in mock_research_data["resources"]
+ ],
+ }
+
+ # Make request
+ response = authenticated_client.post(
+ "/api/followup/prepare",
+ json={
+ "parent_research_id": mock_research_data["research_id"],
+ "question": "How do quantum gates work?",
+ },
+ )
+
+ # Verify response
+ assert response.status_code == 200
+ data = json.loads(response.data)
+ assert data["success"] is True
+ assert data["parent_summary"] == "What is quantum computing?"
+ assert data["available_sources"] == 2
+ assert data["suggested_strategy"] == "source-based"
+
+ def test_prepare_followup_missing_params(self, authenticated_client):
+ """Test prepare endpoint with missing parameters."""
+ # Add mocks for settings manager which is always called
+ with (
+ patch(
+ "local_deep_research.web.services.settings_manager.SettingsManager"
+ ) as MockSettings,
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as mock_db_session,
+ ):
+ # Setup settings mock
+ mock_settings_mgr = MockSettings.return_value
+ mock_settings_mgr.get_all_settings.return_value = {}
+
+ # Setup DB session mock
+ mock_db = MagicMock()
+ mock_db_session.return_value.__enter__.return_value = mock_db
+
+ response = authenticated_client.post(
+ "/api/followup/prepare", json={"question": "Test question"}
+ )
+
+ # Could be 400 (bad request) or 401 (unauthorized) depending on decorator order
+ assert response.status_code in [400, 401]
+ if response.status_code == 400:
+ data = json.loads(response.data)
+ assert data["success"] is False
+ assert "Missing parent_research_id" in data["error"]
+
+ def test_prepare_followup_not_found(self, authenticated_client):
+ """Test prepare endpoint with non-existent parent research."""
+ with (
+ patch(
+ "local_deep_research.followup_research.routes.FollowUpResearchService"
+ ) as MockService,
+ patch(
+ "local_deep_research.web.services.settings_manager.SettingsManager"
+ ) as MockSettings,
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as mock_db_session,
+ ):
+ # Setup settings mock
+ mock_settings_mgr = MockSettings.return_value
+ mock_settings_mgr.get_all_settings.return_value = {
+ "search.search_strategy": {"value": "source-based"},
+ }
+
+ # Setup DB session mock
+ mock_db = MagicMock()
+ mock_db_session.return_value.__enter__.return_value = mock_db
+
+ # Setup service mock
+ mock_service = MockService.return_value
+ mock_service.load_parent_research.return_value = (
+ None # Return None for not found
+ )
+
+ response = authenticated_client.post(
+ "/api/followup/prepare",
+ json={
+ "parent_research_id": "non-existent-id",
+ "question": "Test question",
+ },
+ )
+
+ # The route returns success with empty data when parent is not found
+ assert response.status_code == 200
+ data = json.loads(response.data)
+ assert data["success"] is True
+ assert data["available_sources"] == 0
+ assert data["parent_summary"] == "Previous research context"
+
+ def test_start_followup_success(
+ self, authenticated_client, mock_research_data
+ ):
+ """Test successful start of follow-up research."""
+ with (
+ patch(
+ "local_deep_research.followup_research.routes.FollowUpResearchService"
+ ) as MockService,
+ patch(
+ "local_deep_research.web.services.research_service.start_research_process"
+ ) as mock_start,
+ patch(
+ "local_deep_research.web.services.settings_manager.SettingsManager"
+ ) as MockSettings,
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as mock_db_session,
+ ):
+ # Setup mocks
+ mock_settings_mgr = MockSettings.return_value
+ mock_settings_mgr.get_all_settings.return_value = {
+ "search.search_strategy": {"value": "source-based"},
+ "search.iterations": {"value": 1},
+ "search.questions_per_iteration": {"value": 3},
+ "llm.provider": {"value": "OLLAMA"},
+ "llm.model": {"value": "gemma3:12b"},
+ "search.tool": {"value": "searxng"},
+ }
+
+ # Setup DB session mock
+ mock_db = MagicMock()
+ mock_db_session.return_value.__enter__.return_value = mock_db
+
+ # Setup service mock
+ mock_service = MockService.return_value
+ mock_service.perform_followup.return_value = {
+ "query": "How do quantum gates work?",
+ "strategy": "contextual-followup",
+ "delegate_strategy": "source-based",
+ "max_iterations": 1,
+ "questions_per_iteration": 3,
+ "parent_research_id": mock_research_data["research_id"],
+ "research_context": {
+ "parent_research_id": mock_research_data["research_id"],
+ "past_links": [],
+ "past_findings": "",
+ },
+ }
+
+ # Make request
+ response = authenticated_client.post(
+ "/api/followup/start",
+ json={
+ "parent_research_id": mock_research_data["research_id"],
+ "question": "How do quantum gates work?",
+ "strategy": "source-based",
+ "max_iterations": 1,
+ "questions_per_iteration": 3,
+ },
+ )
+
+ # Verify response
+ assert response.status_code == 200
+ data = json.loads(response.data)
+ assert data["success"] is True
+ assert "research_id" in data
+ assert data["message"] == "Follow-up research started"
+
+ # Verify start_research_process was called
+ mock_start.assert_called_once()
+
+ def test_start_followup_unauthorized(self, client):
+ """Test start endpoint without authentication."""
+ response = client.post(
+ "/api/followup/start",
+ json={"parent_research_id": "test-id", "question": "Test question"},
+ )
+
+ # Should redirect to login or return 401
+ assert response.status_code in [302, 401]
+
+ def test_followup_service_load_parent(self, mock_research_data):
+ """Test FollowUpResearchService.load_parent_research method."""
+ with (
+ patch(
+ "local_deep_research.followup_research.service.get_user_db_session"
+ ) as mock_session,
+ patch(
+ "local_deep_research.followup_research.service.ResearchSourcesService"
+ ) as MockSourcesService,
+ ):
+ # Setup mock database session
+ mock_db = MagicMock()
+ mock_session.return_value.__enter__.return_value = mock_db
+
+ # Setup mock research with research_meta
+ mock_research = mock_research_data["research"]
+ mock_research.research_meta = {"strategy_name": "source-based"}
+
+ # Setup query results
+ mock_db.query.return_value.filter_by.return_value.first.return_value = mock_research
+
+ # Setup sources service mock
+ mock_sources_service = MockSourcesService.return_value
+ mock_sources_service.get_research_sources.return_value = [
+ {
+ "url": r.url,
+ "title": r.title,
+ "content_preview": r.content_preview,
+ "source_type": r.source_type,
+ }
+ for r in mock_research_data["resources"]
+ ]
+
+ # Test service
+ service = FollowUpResearchService(username="testuser")
+ result = service.load_parent_research(
+ mock_research_data["research_id"]
+ )
+
+ # Verify result
+ assert result["research_id"] == mock_research_data["research_id"]
+ assert result["query"] == "What is quantum computing?"
+ assert len(result["resources"]) == 2
+ assert len(result["all_links_of_system"]) == 2
+
+ def test_followup_service_prepare_context(self, mock_research_data):
+ """Test FollowUpResearchService.prepare_research_context method."""
+ with patch.object(
+ FollowUpResearchService, "load_parent_research"
+ ) as mock_load:
+ # Setup mock
+ mock_load.return_value = {
+ "query": mock_research_data["research"].query,
+ "formatted_findings": "Key findings about quantum computing...", # Mock formatted findings
+ "report_content": mock_research_data["research"].report_content,
+ "resources": [
+ {
+ "url": r.url,
+ "title": r.title,
+ "content_preview": r.content_preview,
+ "source_type": r.source_type,
+ }
+ for r in mock_research_data["resources"]
+ ],
+ "all_links_of_system": [
+ {
+ "url": r.url,
+ "title": r.title,
+ "snippet": r.content_preview,
+ }
+ for r in mock_research_data["resources"]
+ ],
+ }
+
+ # Test service
+ service = FollowUpResearchService(username="testuser")
+ context = service.prepare_research_context(
+ mock_research_data["research_id"]
+ )
+
+ # Verify context
+ assert (
+ context["parent_research_id"]
+ == mock_research_data["research_id"]
+ )
+ assert len(context["past_links"]) == 2
+ assert (
+ context["past_findings"]
+ == "Key findings about quantum computing..." # Expected mock value
+ )
+ assert context["original_query"] == "What is quantum computing?"
+
+ def test_followup_request_model(self):
+ """Test FollowUpRequest model."""
+ request = FollowUpRequest(
+ parent_research_id="test-id",
+ question="How does it work?",
+ strategy="source-based",
+ max_iterations=2,
+ questions_per_iteration=5,
+ )
+
+ # Test to_dict
+ data = request.to_dict()
+ assert data["parent_research_id"] == "test-id"
+ assert data["question"] == "How does it work?"
+ assert data["strategy"] == "source-based"
+ assert data["max_iterations"] == 2
+ assert data["questions_per_iteration"] == 5
diff --git a/tests/ui_tests/test_followup_api.js b/tests/ui_tests/test_followup_api.js
new file mode 100644
index 0000000000..4619a52211
--- /dev/null
+++ b/tests/ui_tests/test_followup_api.js
@@ -0,0 +1,62 @@
+const axios = require('axios');
+
+async function testFollowupAPI() {
+ try {
+ console.log('Testing follow-up API directly...');
+
+ // First login
+ const loginRes = await axios.post('http://127.0.0.1:5000/auth/login', {
+ username: 'testuser',
+ password: 'testpass'
+ }, {
+ headers: { 'Content-Type': 'application/json' },
+ withCredentials: true
+ });
+
+ const cookies = loginRes.headers['set-cookie'];
+ console.log('Login successful, got cookies');
+
+ // Test follow-up prepare endpoint
+ console.log('Testing prepare endpoint...');
+ const prepareRes = await axios.post('http://127.0.0.1:5000/api/followup/prepare', {
+ parent_research_id: '175a78a1-a1ce-4a65-8507-167575babedf',
+ question: 'test question'
+ }, {
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Cookie': cookies.join('; ')
+ }
+ });
+
+ console.log('Prepare response:', prepareRes.data);
+
+ // Test follow-up start endpoint
+ console.log('Testing start endpoint...');
+ const startRes = await axios.post('http://127.0.0.1:5000/api/followup/start', {
+ parent_research_id: '175a78a1-a1ce-4a65-8507-167575babedf',
+ question: 'test question',
+ strategy: 'source-based',
+ max_iterations: 1,
+ questions_per_iteration: 3
+ }, {
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Cookie': cookies.join('; ')
+ }
+ });
+
+ console.log('Start response:', startRes.data);
+ console.log('Test completed successfully');
+
+ } catch (error) {
+ console.error('Test failed:', error.message);
+ if (error.response) {
+ console.error('Response data:', error.response.data);
+ console.error('Response status:', error.response.status);
+ }
+ process.exit(1);
+ }
+}
+
+// Run the test
+testFollowupAPI().catch(console.error);
diff --git a/tests/ui_tests/test_followup_research.js b/tests/ui_tests/test_followup_research.js
new file mode 100644
index 0000000000..59b675c28b
--- /dev/null
+++ b/tests/ui_tests/test_followup_research.js
@@ -0,0 +1,318 @@
+/**
+ * UI Test for Follow-up Research Feature
+ * Tests the complete flow of asking follow-up questions on research results
+ */
+
+const puppeteer = require('puppeteer');
+const AuthHelper = require('./auth_helper');
+const { getPuppeteerLaunchOptions } = require('./puppeteer_config');
+
+// Test configuration
+const BASE_URL = 'http://127.0.0.1:5000';
+const TIMEOUT = 60000; // 60 seconds for research operations
+
+// Colors for console output
+const colors = {
+ reset: '\x1b[0m',
+ bright: '\x1b[1m',
+ green: '\x1b[32m',
+ red: '\x1b[31m',
+ yellow: '\x1b[33m',
+ blue: '\x1b[34m',
+ cyan: '\x1b[36m'
+};
+
+function log(message, type = 'info') {
+ const timestamp = new Date().toISOString().split('T')[1].split('.')[0];
+ const typeColors = {
+ 'info': colors.cyan,
+ 'success': colors.green,
+ 'error': colors.red,
+ 'warning': colors.yellow,
+ 'section': colors.blue
+ };
+ const color = typeColors[type] || colors.reset;
+ console.log(`${color}[${timestamp}] ${message}${colors.reset}`);
+}
+
+async function delay(ms) {
+ return new Promise(resolve => setTimeout(resolve, ms));
+}
+
+/**
+ * Create a research and wait for it to complete
+ */
+async function createAndCompleteResearch(page, query) {
+ log(`🔬 Creating research: "${query}"`, 'info');
+
+ // Navigate to home page
+ await page.goto(BASE_URL, { waitUntil: 'networkidle2' });
+
+ // Wait for and fill the query input
+ await page.waitForSelector('#query', { timeout: 10000 });
+ await page.click('#query', { clickCount: 3 });
+ await page.type('#query', query);
+
+ // Select quick summary mode for faster testing
+ const modeSelect = await page.$('#mode');
+ if (modeSelect) {
+ await page.select('#mode', 'quick_summary');
+ }
+
+ // Submit the research
+ log('📤 Submitting research...', 'info');
+ await Promise.all([
+ page.waitForNavigation({ waitUntil: 'networkidle2', timeout: TIMEOUT }),
+ page.click('button[type="submit"]')
+ ]);
+
+ // Wait for research to complete
+ log('⏳ Waiting for research to complete...', 'info');
+ const startTime = Date.now();
+
+ while (Date.now() - startTime < TIMEOUT) {
+ const url = page.url();
+
+ // Check if we're on the results page
+ if (url.includes('/results/')) {
+ log('✅ Research completed, on results page', 'success');
+
+ // Extract research ID from URL
+ const match = url.match(/\/results\/([a-zA-Z0-9-]+)/);
+ if (match) {
+ return match[1];
+ }
+ break;
+ }
+
+ // Check if we're on progress page and research is complete
+ if (url.includes('/progress/')) {
+ const isComplete = await page.evaluate(() => {
+ const statusEl = document.querySelector('.progress-status, .status-text');
+ if (statusEl) {
+ const text = statusEl.textContent.toLowerCase();
+ return text.includes('completed') || text.includes('100%');
+ }
+ return false;
+ });
+
+ if (isComplete) {
+ // Click view results button if available
+ const viewResultsBtn = await page.$('a[href*="/results/"], button:has-text("View Results")');
+ if (viewResultsBtn) {
+ await Promise.all([
+ page.waitForNavigation({ waitUntil: 'networkidle2', timeout: TIMEOUT }),
+ viewResultsBtn.click()
+ ]);
+ }
+ }
+ }
+
+ await delay(2000);
+ }
+
+ // Try to extract research ID from current URL
+ const finalUrl = page.url();
+ const match = finalUrl.match(/\/(results|progress)\/([a-zA-Z0-9-]+)/);
+ return match ? match[2] : null;
+}
+
+/**
+ * Test the follow-up research feature
+ */
+async function testFollowUpResearch() {
+ let browser;
+ let exitCode = 0;
+
+ try {
+ log('🚀 Starting Follow-up Research UI Test', 'section');
+
+ // Launch browser
+ browser = await puppeteer.launch(getPuppeteerLaunchOptions());
+ const page = await browser.newPage();
+
+ // Set viewport
+ await page.setViewport({ width: 1280, height: 800 });
+
+ // Initialize auth helper
+ const auth = new AuthHelper(page, BASE_URL);
+
+ // Ensure authenticated
+ log('🔐 Authenticating...', 'info');
+ await auth.ensureAuthenticated();
+
+ // Step 1: Create initial research
+ log('\n📝 Step 1: Creating initial research', 'section');
+ const initialQuery = 'What is quantum computing?';
+ const researchId = await createAndCompleteResearch(page, initialQuery);
+
+ if (!researchId) {
+ throw new Error('Failed to create initial research or get research ID');
+ }
+ log(`✅ Initial research created with ID: ${researchId}`, 'success');
+
+ // Step 2: Navigate to results page if not already there
+ const currentUrl = page.url();
+ if (!currentUrl.includes(`/results/${researchId}`)) {
+ log('📍 Navigating to results page...', 'info');
+ await page.goto(`${BASE_URL}/results/${researchId}`, { waitUntil: 'networkidle2' });
+ }
+
+ // Wait for results to load
+ await page.waitForSelector('#results-content, .results-content', { timeout: 10000 });
+
+ // Step 3: Test follow-up button presence
+ log('\n🔍 Step 2: Testing follow-up button', 'section');
+ const followUpBtn = await page.$('#ask-followup-btn');
+
+ if (!followUpBtn) {
+ throw new Error('Follow-up button not found on results page');
+ }
+ log('✅ Follow-up button found', 'success');
+
+ // Step 4: Click follow-up button and test modal
+ log('\n🖱️ Step 3: Opening follow-up modal', 'section');
+ await followUpBtn.click();
+ await delay(1000); // Wait for modal animation
+
+ // Check if modal opened
+ const modal = await page.$('#followUpModal');
+ if (!modal) {
+ throw new Error('Follow-up modal did not open');
+ }
+
+ // Check if modal is visible
+ const modalVisible = await page.evaluate(() => {
+ const modal = document.getElementById('followUpModal');
+ if (!modal) return false;
+
+ // Check Bootstrap modal classes or inline styles
+ const hasShowClass = modal.classList.contains('show');
+ const displayStyle = window.getComputedStyle(modal).display;
+
+ return hasShowClass || displayStyle !== 'none';
+ });
+
+ if (!modalVisible) {
+ log('⚠️ Modal exists but may not be visible, continuing...', 'warning');
+ }
+
+ log('✅ Follow-up modal opened', 'success');
+
+ // Step 5: Check parent context is loaded
+ log('\n📊 Step 4: Checking parent context', 'section');
+
+ // Wait a bit for context to load
+ await delay(2000);
+
+ const parentContextVisible = await page.evaluate(() => {
+ const contextDiv = document.getElementById('parentContext');
+ return contextDiv && contextDiv.style.display !== 'none';
+ });
+
+ if (parentContextVisible) {
+ const parentSummary = await page.$eval('#parentSummary', el => el.textContent);
+ const parentSources = await page.$eval('#parentSources', el => el.textContent);
+
+ log(`✅ Parent context loaded:`, 'success');
+ log(` Summary: ${parentSummary.substring(0, 50)}...`, 'info');
+ log(` Sources: ${parentSources} available`, 'info');
+ } else {
+ log('⚠️ Parent context not visible (may be due to async loading)', 'warning');
+ }
+
+ // Step 6: Enter follow-up question
+ log('\n✍️ Step 5: Entering follow-up question', 'section');
+ const followUpQuestion = 'How do quantum gates work?';
+
+ await page.waitForSelector('#followUpQuestion', { timeout: 5000 });
+ await page.type('#followUpQuestion', followUpQuestion);
+ log(`✅ Entered follow-up question: "${followUpQuestion}"`, 'success');
+
+ // Step 7: Test advanced options
+ log('\n⚙️ Step 6: Testing advanced options', 'section');
+
+ // Try to expand advanced options
+ const advancedLink = await page.$('a[onclick*="toggleAdvancedOptions"]');
+ if (advancedLink) {
+ await advancedLink.click();
+ await delay(500);
+
+ const advancedVisible = await page.evaluate(() => {
+ const panel = document.getElementById('advancedOptionsPanel');
+ return panel && panel.style.display !== 'none';
+ });
+
+ if (advancedVisible) {
+ // Set to quick summary (1 iteration)
+ await page.select('#followUpIterations', '1');
+ log('✅ Advanced options configured for quick summary', 'success');
+ }
+ }
+
+ // Step 8: Submit follow-up research
+ log('\n🚀 Step 7: Submitting follow-up research', 'section');
+
+ // Find and click submit button in modal
+ const submitBtn = await page.$('#followUpModal button.btn-primary');
+ if (!submitBtn) {
+ throw new Error('Submit button not found in follow-up modal');
+ }
+
+ // Click submit and wait for navigation
+ await Promise.all([
+ page.waitForNavigation({ waitUntil: 'networkidle2', timeout: TIMEOUT }).catch(e => {
+ log('⚠️ Navigation timeout, checking URL...', 'warning');
+ }),
+ submitBtn.click()
+ ]);
+
+ await delay(2000);
+
+ // Step 9: Verify follow-up research started
+ log('\n✔️ Step 8: Verifying follow-up research', 'section');
+
+ const newUrl = page.url();
+
+ // Check if we're on a new research page
+ if (newUrl.includes('/progress/') || newUrl.includes('/results/')) {
+ const newResearchId = newUrl.match(/\/(progress|results)\/([a-zA-Z0-9-]+)/)?.[2];
+
+ if (newResearchId && newResearchId !== researchId) {
+ log(`✅ Follow-up research started with ID: ${newResearchId}`, 'success');
+
+ // Check for follow-up indicator in URL params
+ if (newUrl.includes('followup=true')) {
+ log('✅ Follow-up flag detected in URL', 'success');
+ }
+ } else {
+ log('⚠️ May be on same research page, checking content...', 'warning');
+ }
+ } else {
+ log(`⚠️ Unexpected URL after submission: ${newUrl}`, 'warning');
+ }
+
+ // Final success
+ log('\n🎉 Follow-up Research Test Completed Successfully!', 'section');
+
+ } catch (error) {
+ log(`\n❌ Test Failed: ${error.message}`, 'error');
+ console.error(error);
+ exitCode = 1;
+ } finally {
+ if (browser) {
+ await browser.close();
+ }
+ process.exit(exitCode);
+ }
+}
+
+// Run the test
+(async () => {
+ try {
+ await testFollowUpResearch();
+ } catch (error) {
+ console.error('Test execution failed:', error);
+ process.exit(1);
+ }
+})();
diff --git a/tests/ui_tests/test_followup_simple.js b/tests/ui_tests/test_followup_simple.js
new file mode 100755
index 0000000000..e0f75d454d
--- /dev/null
+++ b/tests/ui_tests/test_followup_simple.js
@@ -0,0 +1,161 @@
+#!/usr/bin/env node
+
+/**
+ * Simple test for follow-up research using existing testuser
+ */
+
+const puppeteer = require('puppeteer');
+
+const BASE_URL = 'http://127.0.0.1:5000';
+const PARENT_RESEARCH_ID = '6fe358f9-82de-43b1-8cae-0b673e61fe4d';
+const TEST_USER = 'testuser';
+const TEST_PASSWORD = 'testpass';
+
+async function testFollowupResearch() {
+ let browser;
+ let page;
+
+ try {
+ console.log('🚀 Starting Simple Follow-up Research Test');
+ console.log(` Parent Research: ${PARENT_RESEARCH_ID}`);
+ console.log(` User: ${TEST_USER}`);
+
+ // Launch browser
+ browser = await puppeteer.launch({
+ headless: process.env.HEADLESS === 'true',
+ args: ['--no-sandbox', '--disable-setuid-sandbox']
+ });
+
+ page = await browser.newPage();
+
+ // Set viewport
+ await page.setViewport({ width: 1280, height: 800 });
+
+ // Enable console logging
+ page.on('console', msg => {
+ if (msg.type() === 'error') {
+ console.log('Browser console error:', msg.text());
+ }
+ });
+
+ // Step 1: Login
+ console.log('\n1️⃣ Logging in as testuser...');
+ await page.goto(`${BASE_URL}/auth/login`, { waitUntil: 'networkidle2' });
+
+ await page.type('input[name="username"]', TEST_USER);
+ await page.type('input[name="password"]', TEST_PASSWORD);
+
+ await Promise.all([
+ page.waitForNavigation({ waitUntil: 'networkidle2' }),
+ page.click('button[type="submit"]')
+ ]);
+
+ console.log('✅ Logged in successfully');
+
+ // Step 2: Navigate to parent research
+ console.log(`\n2️⃣ Navigating to parent research...`);
+ await page.goto(`${BASE_URL}/results/${PARENT_RESEARCH_ID}`, {
+ waitUntil: 'networkidle2',
+ timeout: 30000
+ });
+
+ // Wait for page to load
+ await new Promise(resolve => setTimeout(resolve, 2000));
+
+ // Step 3: Test direct API call for follow-up
+ console.log('\n3️⃣ Testing follow-up API directly...');
+
+ const apiResponse = await page.evaluate(async (parentId) => {
+ try {
+ const response = await fetch('/api/followup/start', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ credentials: 'include',
+ body: JSON.stringify({
+ parent_research_id: parentId,
+ question: 'What are the key points from this research?'
+ })
+ });
+
+ const data = await response.json();
+ return {
+ status: response.status,
+ data: data
+ };
+ } catch (error) {
+ return {
+ error: error.message
+ };
+ }
+ }, PARENT_RESEARCH_ID);
+
+ console.log('API Response:', JSON.stringify(apiResponse, null, 2));
+
+ if (apiResponse.status === 200 && apiResponse.data.success) {
+ console.log(`\n✅ Follow-up research started successfully!`);
+ console.log(` Research ID: ${apiResponse.data.research_id}`);
+
+ // Navigate to the new research
+ const newResearchId = apiResponse.data.research_id;
+ console.log(`\n4️⃣ Navigating to follow-up research: ${newResearchId}`);
+
+ await page.goto(`${BASE_URL}/results/${newResearchId}`, {
+ waitUntil: 'networkidle2',
+ timeout: 30000
+ });
+
+ // Wait a bit to see the page
+ await new Promise(resolve => setTimeout(resolve, 3000));
+
+ // Check if we're on the results page
+ const currentUrl = page.url();
+ if (currentUrl.includes(`/results/${newResearchId}`) || currentUrl.includes(`/progress/${newResearchId}`)) {
+ console.log('✅ Successfully navigated to follow-up research page');
+ }
+
+ } else {
+ console.log(`\n❌ Follow-up failed:`);
+ console.log(` Status: ${apiResponse.status}`);
+ console.log(` Error: ${apiResponse.data?.error || 'Unknown error'}`);
+
+ // Try to get more error details from server logs
+ const serverLogs = await page.evaluate(() => {
+ return document.body.innerText;
+ });
+
+ if (serverLogs.includes('Error') || serverLogs.includes('error')) {
+ console.log('\nPage content (may contain error details):');
+ console.log(serverLogs.substring(0, 500));
+ }
+ }
+
+ console.log('\n✅ Test completed!');
+
+ } catch (error) {
+ console.error('\n❌ Test failed:', error.message);
+ console.error(error.stack);
+
+ // Take screenshot on error
+ if (page) {
+ await page.screenshot({
+ path: '/tmp/followup_test_error.png',
+ fullPage: true
+ });
+ console.log('Screenshot saved to /tmp/followup_test_error.png');
+ }
+
+ process.exit(1);
+ } finally {
+ if (browser) {
+ await browser.close();
+ }
+ }
+}
+
+// Run the test
+testFollowupResearch().catch(error => {
+ console.error('Fatal error:', error);
+ process.exit(1);
+});