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.

feat: Implement follow-up research with context preservation

LearningCircuite2f9318a4e0b
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..3238e60a24
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/filters/followup_relevance_filter.py
@@ -0,0 +1,294 @@
+"""
+Follow-up Relevance Filter
+
+Filters and ranks past research sources based on their relevance
+to follow-up questions.
+"""
+
+from typing import Dict, List, Optional, Tuple
+from loguru import logger
+import re
+
+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, **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
+ **kwargs: Additional parameters:
+ - max_results: Maximum number of results to return
+ - threshold: Minimum relevance score (0-1)
+ - past_findings: Summary of past findings for context
+
+ Returns:
+ Filtered and ranked list of relevant sources
+ """
+ if not results:
+ return []
+
+ max_results = kwargs.get("max_results", 10)
+ threshold = kwargs.get("threshold", 0.3)
+ past_findings = kwargs.get("past_findings", "")
+
+ # Score each source for relevance
+ scored_results = []
+ for source in results:
+ score = self._calculate_relevance_score(
+ source, query, past_findings
+ )
+ if score >= threshold:
+ source_copy = source.copy()
+ source_copy["relevance_score"] = score
+ scored_results.append(source_copy)
+
+ # Sort by relevance score
+ scored_results.sort(key=lambda x: x["relevance_score"], reverse=True)
+
+ # Return top results
+ filtered = scored_results[:max_results]
+
+ logger.info(
+ f"Filtered {len(results)} sources to {len(filtered)} relevant ones "
+ f"for follow-up query"
+ )
+
+ return filtered
+
+ def _calculate_relevance_score(
+ self, source: Dict, query: str, context: str
+ ) -> float:
+ """
+ Calculate relevance score for a source.
+
+ Args:
+ source: Source dictionary with url, title, snippet
+ query: The follow-up query
+ context: Additional context (past findings)
+
+ Returns:
+ Relevance score between 0 and 1
+ """
+ # Quick keyword matching for initial score
+ keyword_score = self._keyword_relevance(source, query)
+
+ # If keyword score is very low, skip expensive LLM call
+ if keyword_score < 0.1:
+ return keyword_score
+
+ # Use LLM for semantic relevance if model is available
+ if self.model:
+ semantic_score = self._semantic_relevance(source, query, context)
+ # Weighted combination
+ return 0.4 * keyword_score + 0.6 * semantic_score
+
+ return keyword_score
+
+ def _keyword_relevance(self, source: Dict, query: str) -> float:
+ """
+ Calculate keyword-based relevance score.
+
+ Args:
+ source: Source dictionary
+ query: Follow-up query
+
+ Returns:
+ Score between 0 and 1
+ """
+ # Extract text from source
+ source_text = " ".join(
+ [
+ source.get("title") or "",
+ source.get("snippet") or "",
+ source.get("content_preview") or "",
+ ]
+ ).lower()
+
+ # Extract keywords from query
+ query_words = set(re.findall(r"\w+", query.lower()))
+
+ # Count matching keywords
+ matches = sum(1 for word in query_words if word in source_text)
+
+ # Calculate score
+ if len(query_words) > 0:
+ return min(1.0, matches / len(query_words))
+ return 0.0
+
+ def _semantic_relevance(
+ self, source: Dict, query: str, context: str
+ ) -> float:
+ """
+ Calculate semantic relevance using LLM.
+
+ Args:
+ source: Source dictionary
+ query: Follow-up query
+ context: Past findings context
+
+ Returns:
+ Score between 0 and 1
+ """
+ source_preview = f"""
+Title: {source.get("title") or "Unknown"}
+URL: {source.get("url") or ""}
+Content: {(source.get("snippet") or "")[:200]}
+"""
+
+ prompt = f"""
+Rate the relevance of this source to the follow-up question on a scale of 0-10.
+
+Follow-up question: "{query}"
+
+Source:
+{source_preview}
+
+Consider:
+1. Does the source directly address the question?
+2. Does it provide useful context or background?
+3. Does it contain specific information requested?
+
+Return only a number from 0 to 10.
+"""
+
+ try:
+ response = self.model.invoke(prompt)
+ content = remove_think_tags(response.content).strip()
+
+ # Extract number from response
+ import re
+
+ numbers = re.findall(r"\d+\.?\d*", content)
+ if numbers:
+ score = float(numbers[0])
+ return min(1.0, score / 10.0)
+ except Exception as e:
+ logger.debug(f"Semantic relevance calculation failed: {e}")
+
+ # Fallback to keyword score
+ return self._keyword_relevance(source, query)
+
+ def rank_by_relevance(
+ self, sources: List[Dict], query: str, context: Optional[str] = None
+ ) -> List[Tuple[Dict, float]]:
+ """
+ Rank sources by relevance and return with scores.
+
+ Args:
+ sources: List of source documents
+ query: Follow-up query
+ context: Optional context for better ranking
+
+ Returns:
+ List of (source, score) tuples sorted by relevance
+ """
+ ranked = []
+ for source in sources:
+ score = self._calculate_relevance_score(
+ source, query, context or ""
+ )
+ ranked.append((source, score))
+
+ # Sort by score descending
+ ranked.sort(key=lambda x: x[1], reverse=True)
+ return ranked
+
+ def extract_key_sources(
+ self, sources: List[Dict], max_count: int = 5
+ ) -> List[Dict]:
+ """
+ Extract the most important sources for follow-up research.
+
+ Args:
+ sources: List of all sources
+ max_count: Maximum number of key sources to extract
+
+ Returns:
+ List of key sources
+ """
+ if not sources:
+ return []
+
+ # Prioritize sources with certain characteristics
+ prioritized = []
+
+ for source in sources:
+ priority_score = 0
+
+ # Prefer sources with content
+ if source.get("content_preview") or source.get("snippet"):
+ priority_score += 2
+
+ # Prefer sources with clear titles
+ if source.get("title") and len(source.get("title", "")) > 10:
+ priority_score += 1
+
+ # Prefer certain source types if specified
+ if source.get("source_type") in ["academic", "official", "primary"]:
+ priority_score += 3
+
+ source_copy = source.copy()
+ source_copy["priority_score"] = priority_score
+ prioritized.append(source_copy)
+
+ # Sort by priority
+ prioritized.sort(key=lambda x: x["priority_score"], reverse=True)
+
+ # Return top sources
+ return prioritized[:max_count]
+
+ def filter_by_type(
+ self, sources: List[Dict], source_types: List[str]
+ ) -> List[Dict]:
+ """
+ Filter sources by their type.
+
+ Args:
+ sources: List of sources
+ source_types: Types to include (e.g., ["academic", "news"])
+
+ Returns:
+ Filtered sources
+ """
+ if not source_types:
+ return sources
+
+ return [s for s in sources if s.get("source_type") in source_types]
+
+ def deduplicate_sources(self, sources: List[Dict]) -> List[Dict]:
+ """
+ Remove duplicate sources based on URL.
+
+ Args:
+ sources: List of sources that may contain duplicates
+
+ Returns:
+ Deduplicated list of sources
+ """
+ seen_urls = set()
+ unique_sources = []
+
+ for source in sources:
+ url = source.get("url", "")
+ if url and url not in seen_urls:
+ seen_urls.add(url)
+ unique_sources.append(source)
+ elif not url:
+ # Keep sources without URLs (shouldn't happen but be safe)
+ unique_sources.append(source)
+
+ return unique_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..6e65d3690c
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/knowledge/followup_context_manager.py
@@ -0,0 +1,371 @@
+"""
+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
+from loguru import logger
+
+from langchain_core.language_models.chat_models import BaseChatModel
+from ...utilities.search_utilities import remove_think_tags
+
+
+class FollowUpContextManager:
+ """
+ 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):
+ """
+ Initialize the context manager.
+
+ Args:
+ model: Language model for processing context
+ """
+ self.model = model
+ 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)
+
+ # Truncate if too long
+ if len(combined) > 5000:
+ combined = combined[:5000] + "..."
+
+ 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 relevant to the follow-up question.
+
+ Args:
+ research_data: Past research data
+ follow_up_query: The follow-up question
+
+ Returns:
+ Targeted summary
+ """
+ findings = self._extract_findings(research_data)
+ original_query = research_data.get("query", "")
+
+ if not findings or not self.model:
+ return findings[:500] if findings else ""
+
+ prompt = f"""
+Create a brief summary of previous research findings that are relevant to this follow-up question:
+
+Original research question: "{original_query}"
+Follow-up question: "{follow_up_query}"
+
+Previous findings:
+{findings[:3000]}
+
+Provide a 3-5 sentence summary focusing on aspects relevant to the follow-up question.
+"""
+
+ try:
+ response = self.model.invoke(prompt)
+ return remove_think_tags(response.content).strip()
+ except Exception as e:
+ logger.warning(f"Failed to create summary: {e}")
+ return findings[:500]
+
+ 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 follow-up research.
+
+ Args:
+ findings: Past research findings
+ query: Follow-up query
+ max_length: Maximum length of summary
+
+ Returns:
+ Concise summary
+ """
+ if not findings:
+ return ""
+
+ if len(findings) <= max_length:
+ return findings
+
+ if not self.model:
+ return findings[:max_length] + "..."
+
+ 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_length // 100} sentences that captures the most relevant information.
+"""
+
+ try:
+ response = self.model.invoke(prompt)
+ summary = remove_think_tags(response.content).strip()
+ if len(summary) > max_length:
+ summary = summary[:max_length] + "..."
+ return summary
+ except Exception as e:
+ logger.warning(f"Summarization failed: {e}")
+ return findings[:max_length] + "..."
+
+ 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.
+
+ Args:
+ context: Full context dictionary
+
+ Returns:
+ Formatted context for settings snapshot
+ """
+ return {
+ "followup_context": {
+ "parent_research_id": context.get("parent_research_id"),
+ "original_query": context.get("original_query"),
+ "follow_up_query": context.get("follow_up_query"),
+ "summary": context.get("summary"),
+ "key_entities": context.get("key_entities", []),
+ "past_sources_count": len(context.get("past_sources", [])),
+ "has_findings": bool(context.get("past_findings")),
+ "metadata": context.get("metadata", {}),
+ }
+ }
+
+ 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/query_generation/followup_query_reformulator.py b/src/local_deep_research/advanced_search_system/query_generation/followup_query_reformulator.py
new file mode 100644
index 0000000000..952eec35ee
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/query_generation/followup_query_reformulator.py
@@ -0,0 +1,268 @@
+"""
+Follow-up Query Reformulator
+
+Extends AdaptiveQueryGenerator to reformulate follow-up questions
+based on past research findings and context.
+"""
+
+from typing import Dict, List
+from loguru import logger
+
+from .adaptive_query_generator import AdaptiveQueryGenerator
+from ...utilities.search_utilities import remove_think_tags
+
+
+class FollowUpQueryReformulator(AdaptiveQueryGenerator):
+ """
+ Reformulates follow-up questions by combining them with past research context.
+
+ This class extends AdaptiveQueryGenerator to:
+ 1. Analyze past research findings
+ 2. Identify gaps and areas for deeper exploration
+ 3. Reformulate user questions to be more specific and targeted
+ 4. Combine new questions with relevant past context
+ """
+
+ def reformulate_with_context(
+ self,
+ query: str,
+ past_findings: str,
+ past_sources: List[Dict],
+ original_query: str = None,
+ ) -> str:
+ """
+ Reformulate a follow-up question using past research context.
+
+ Args:
+ query: The user's follow-up question
+ past_findings: Summary of previous research findings
+ past_sources: List of sources from previous research
+ original_query: The original research question (optional)
+
+ Returns:
+ Reformulated query that incorporates context
+ """
+ logger.info(f"Reformulating follow-up query: {query}")
+
+ # First, analyze what the user is asking for
+ query_intent = self._analyze_query_intent(query, past_findings)
+
+ # Identify key entities and concepts from past research
+ key_concepts = self._extract_key_concepts(past_findings)
+
+ # Combine query with findings for better search
+ reformulated = self._combine_query_with_findings(
+ query, past_findings, key_concepts, query_intent
+ )
+
+ logger.info(f"Reformulated query: {reformulated}")
+ return reformulated
+
+ def _analyze_query_intent(self, query: str, context: str) -> str:
+ """
+ Analyze what the user is trying to find out with their follow-up.
+
+ Args:
+ query: The follow-up question
+ context: Past research context
+
+ Returns:
+ Analysis of query intent
+ """
+ prompt = f"""
+Analyze this follow-up question in the context of previous research:
+
+Follow-up question: "{query}"
+
+Previous research context (summary):
+{context[:1500]}
+
+What is the user trying to find out? Identify:
+1. Whether they want clarification, expansion, or new information
+2. Specific aspects they're focusing on
+3. Any implicit assumptions or connections to the previous research
+
+Provide a brief analysis (2-3 sentences).
+"""
+
+ try:
+ response = self.model.invoke(prompt)
+ return remove_think_tags(response.content).strip()
+ except Exception as e:
+ logger.warning(f"Failed to analyze query intent: {e}")
+ return "expansion of previous findings"
+
+ def _extract_key_concepts(self, findings: str) -> List[str]:
+ """
+ Extract key concepts and entities from past findings.
+
+ Args:
+ findings: Past research findings
+
+ Returns:
+ List of key concepts
+ """
+ prompt = f"""
+Extract the 5 most important concepts, entities, or terms from these research findings:
+
+{findings[:2000]}
+
+Return only the concepts, one per line.
+"""
+
+ try:
+ response = self.model.invoke(prompt)
+ concepts = [
+ line.strip()
+ for line in remove_think_tags(response.content)
+ .strip()
+ .split("\n")
+ if line.strip()
+ ]
+ return concepts[:5]
+ except Exception as e:
+ logger.warning(f"Failed to extract key concepts: {e}")
+ return []
+
+ def _combine_query_with_findings(
+ self, query: str, summary: str, key_concepts: List[str], intent: str
+ ) -> str:
+ """
+ Combine the user's query with summarized findings to create an effective search query.
+
+ Args:
+ query: User's follow-up question
+ summary: Summary of past findings
+ key_concepts: Key concepts from past research
+ intent: Analyzed intent of the query
+
+ Returns:
+ Combined and optimized query
+ """
+ # Truncate summary to avoid token limits
+ summary_excerpt = summary[:1000] if summary else ""
+ concepts_str = ", ".join(key_concepts) if key_concepts else ""
+
+ prompt = f"""
+Create an optimized search query for this follow-up research question.
+
+User's follow-up question: "{query}"
+Query intent: {intent}
+Key concepts from previous research: {concepts_str}
+
+Previous findings summary:
+{summary_excerpt}
+
+Generate a search query that:
+1. Directly addresses the user's follow-up question
+2. Incorporates relevant context from previous findings
+3. Uses specific terms and entities already discovered
+4. Is neither too broad nor too narrow
+5. Uses appropriate search operators (AND, OR, quotes) if helpful
+
+Return only the search query, no explanation.
+"""
+
+ try:
+ response = self.model.invoke(prompt)
+ reformulated = remove_think_tags(response.content).strip()
+
+ # Fallback to original query if reformulation fails
+ if not reformulated or len(reformulated) < 3:
+ return query
+
+ return reformulated
+ except Exception as e:
+ logger.error(f"Failed to combine query with findings: {e}")
+ # Fallback: combine query with key concepts
+ if key_concepts:
+ return f"{query} {' '.join(key_concepts[:2])}"
+ return query
+
+ def generate_alternative_queries(
+ self, query: str, past_findings: str, max_alternatives: int = 3
+ ) -> List[str]:
+ """
+ Generate alternative formulations of the follow-up query.
+
+ Args:
+ query: The original follow-up query
+ past_findings: Summary of past research
+ max_alternatives: Maximum number of alternatives to generate
+
+ Returns:
+ List of alternative query formulations
+ """
+ prompt = f"""
+Generate {max_alternatives} alternative search queries for this follow-up question:
+
+Original question: "{query}"
+
+Context from previous research:
+{past_findings[:800]}
+
+Create diverse queries that:
+1. Approach the topic from different angles
+2. Use varied terminology
+3. Range from specific to broader searches
+
+Return only the queries, one per line.
+"""
+
+ try:
+ response = self.model.invoke(prompt)
+ alternatives = [
+ line.strip()
+ for line in remove_think_tags(response.content)
+ .strip()
+ .split("\n")
+ if line.strip()
+ ]
+ return alternatives[:max_alternatives]
+ except Exception as e:
+ logger.warning(f"Failed to generate alternatives: {e}")
+ # Return simple variations
+ return [query, f'"{query}"', f"{query} detailed information"][
+ :max_alternatives
+ ]
+
+ def optimize_for_source_reuse(
+ self, query: str, available_sources: List[Dict]
+ ) -> str:
+ """
+ Optimize query to better utilize already available sources.
+
+ Args:
+ query: The follow-up query
+ available_sources: List of available source documents
+
+ Returns:
+ Query optimized for searching within available sources
+ """
+ if not available_sources:
+ return query
+
+ # Extract domains and key terms from sources
+ domains = set()
+ titles = []
+ for source in available_sources[:10]: # Limit to avoid token overflow
+ if url := source.get("url", ""):
+ # Extract domain
+ try:
+ from urllib.parse import urlparse
+
+ domain = urlparse(url).netloc
+ domains.add(domain)
+ except:
+ pass
+ if title := source.get("title", ""):
+ titles.append(title)
+
+ # Create a query that leverages these sources
+ if domains:
+ site_restrictions = " OR ".join(
+ [f"site:{d}" for d in list(domains)[:3]]
+ )
+ return f"{query} ({site_restrictions})"
+
+ return query
diff --git a/src/local_deep_research/advanced_search_system/strategies/contextual_followup_strategy.py b/src/local_deep_research/advanced_search_system/strategies/contextual_followup_strategy.py
new file mode 100644
index 0000000000..2aa8c2fd36
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/strategies/contextual_followup_strategy.py
@@ -0,0 +1,312 @@
+"""
+Contextual Follow-Up Strategy
+
+This strategy acts as a wrapper that:
+1. Retrieves past research context (links and findings)
+2. Filters relevant links from previous research
+3. Passes the query with filtered context to a delegate strategy
+4. Enables efficient follow-up questions with link reuse
+"""
+
+from typing import Dict, List, Optional
+from loguru import logger
+from .base_strategy import BaseSearchStrategy
+
+
+class ContextualFollowUpStrategy(BaseSearchStrategy):
+ """
+ A wrapper strategy that enhances follow-up queries with past research context.
+
+ This strategy:
+ 1. Summarizes past research findings
+ 2. Filters past links relevant to the current question
+ 3. Delegates to another strategy with enriched context
+ 4. Avoids redundant searches by reusing relevant past links
+ """
+
+ def __init__(
+ self,
+ model,
+ search,
+ delegate_strategy: BaseSearchStrategy,
+ all_links_of_system=None,
+ settings_snapshot=None,
+ research_context: Optional[Dict] = None,
+ **kwargs,
+ ):
+ """
+ Initialize the 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 (past links, findings, etc.)
+ """
+ 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 {}
+
+ # Extract past research data if available
+ self.past_links = self._extract_past_links()
+ self.past_findings = self._extract_past_findings()
+
+ logger.info(
+ f"ContextualFollowUpStrategy initialized with {len(self.past_links)} past links"
+ )
+
+ def _extract_past_links(self) -> List[Dict]:
+ """Extract links from previous research context."""
+ links = []
+
+ # Check various sources of past links
+ if "past_links" in self.research_context:
+ links.extend(self.research_context["past_links"])
+
+ if "resources" in self.research_context:
+ # Extract from ResearchResource format
+ for resource in self.research_context["resources"]:
+ links.append(
+ {
+ "url": resource.get("url", ""),
+ "title": resource.get("title", ""),
+ "snippet": resource.get("content_preview", ""),
+ "source_type": resource.get("source_type", "web"),
+ }
+ )
+
+ if "all_links_of_system" in self.research_context:
+ links.extend(self.research_context["all_links_of_system"])
+
+ # Also check if we have links from a previous search in the same session
+ if self.all_links_of_system:
+ links.extend(self.all_links_of_system)
+
+ # Deduplicate by URL
+ unique_links = {}
+ for link in links:
+ url = link.get("url", "")
+ if url and url not in unique_links:
+ unique_links[url] = link
+
+ return list(unique_links.values())
+
+ def _extract_past_findings(self) -> str:
+ """Extract and summarize past research findings."""
+ findings_parts = []
+
+ # Extract from various possible sources
+ if "past_findings" in self.research_context:
+ findings_parts.append(self.research_context["past_findings"])
+
+ if "report_content" in self.research_context:
+ findings_parts.append(self.research_context["report_content"])
+
+ if "formatted_findings" in self.research_context:
+ findings_parts.append(self.research_context["formatted_findings"])
+
+ if "current_knowledge" in self.research_context:
+ findings_parts.append(self.research_context["current_knowledge"])
+
+ # Combine all findings
+ combined_findings = "\n\n".join(filter(None, findings_parts))
+
+ # If too long, summarize
+ if len(combined_findings) > 5000:
+ return self._summarize_findings(combined_findings)
+
+ return combined_findings
+
+ def _summarize_findings(self, findings: str) -> str:
+ """Create a concise summary of past findings."""
+ try:
+ prompt = f"""Summarize these research findings in 3-5 key points:
+
+{findings[:8000]}
+
+Provide a concise summary focusing on the most important facts and conclusions."""
+
+ response = self.model.invoke(prompt)
+ return (
+ response.content
+ if hasattr(response, "content")
+ else str(response)
+ )
+ except Exception as e:
+ logger.warning(f"Failed to summarize findings: {e}")
+ return findings[:2000] + "..."
+
+ def _filter_relevant_links(self, query: str) -> List[Dict]:
+ """Filter past links that are relevant to the current query."""
+ if not self.past_links:
+ return []
+
+ try:
+ # Prepare links for filtering
+ links_text = "\n".join(
+ [
+ f"{i + 1}. {link.get('title', 'Untitled')} - {link.get('url', '')}"
+ for i, link in enumerate(
+ self.past_links[:50]
+ ) # Limit to 50 for efficiency
+ ]
+ )
+
+ prompt = f"""Given this follow-up question: "{query}"
+
+And these links from previous research:
+{links_text}
+
+Which links are most relevant to answering the follow-up question?
+Return the numbers of the relevant links (comma-separated).
+Only include links that would help answer the specific question.
+If none are relevant, return "none".
+
+Relevant link numbers:"""
+
+ response = self.model.invoke(prompt)
+ content = (
+ response.content
+ if hasattr(response, "content")
+ else str(response)
+ )
+
+ # Parse response
+ if "none" in content.lower():
+ return []
+
+ # Extract numbers
+ import re
+
+ numbers = re.findall(r"\d+", content)
+ relevant_indices = [
+ int(n) - 1
+ for n in numbers
+ if 0 <= int(n) - 1 < len(self.past_links)
+ ]
+
+ # Return filtered links
+ filtered_links = [self.past_links[i] for i in relevant_indices]
+
+ logger.info(
+ f"Filtered {len(filtered_links)} relevant links from {len(self.past_links)} past links"
+ )
+ return filtered_links
+
+ except Exception as e:
+ logger.warning(f"Error filtering links: {e}")
+ # On error, return top 5 links as fallback
+ return self.past_links[:5]
+
+ def _create_enriched_query(
+ self, query: str, relevant_links: List[Dict]
+ ) -> str:
+ """Create an enriched query with context from past research."""
+ parts = [query]
+
+ # Add summary of past findings if available
+ if self.past_findings:
+ summary = self.past_findings[:1000] # Limit context size
+ parts.append(f"\n\nContext from previous research:\n{summary}")
+
+ # Add relevant links if any
+ if relevant_links:
+ links_context = "\n".join(
+ [
+ f"- {link.get('title', 'Untitled')}: {(link.get('snippet') or '')[:200]}"
+ for link in relevant_links[:5]
+ ]
+ )
+ parts.append(
+ f"\n\nRelevant sources already found:\n{links_context}"
+ )
+
+ return "\n".join(parts)
+
+ def analyze_topic(self, query: str) -> Dict:
+ """
+ Analyze a follow-up topic with context from past research.
+
+ Args:
+ query: The follow-up question to research
+
+ Returns:
+ Dict containing research findings enhanced with past context
+ """
+ logger.info(f"Starting contextual follow-up search for: {query}")
+
+ self._update_progress(
+ "Analyzing past research context", 10, {"phase": "context_analysis"}
+ )
+
+ # Filter relevant links from past research
+ relevant_links = self._filter_relevant_links(query)
+
+ self._update_progress(
+ f"Found {len(relevant_links)} relevant past sources",
+ 20,
+ {
+ "phase": "link_filtering",
+ "relevant_links": len(relevant_links),
+ "total_past_links": len(self.past_links),
+ },
+ )
+
+ # Create enriched query with context
+ enriched_query = self._create_enriched_query(query, relevant_links)
+
+ # Inject relevant links into the delegate strategy's all_links_of_system
+ if relevant_links:
+ if not self.delegate_strategy.all_links_of_system:
+ self.delegate_strategy.all_links_of_system = []
+
+ # Add relevant past links to the beginning
+ # This ensures they're considered but can be supplemented with new searches
+ existing_urls = {
+ link.get("url")
+ for link in self.delegate_strategy.all_links_of_system
+ }
+
+ for link in relevant_links:
+ if link.get("url") not in existing_urls:
+ self.delegate_strategy.all_links_of_system.insert(0, link)
+
+ self._update_progress(
+ "Delegating to search strategy with context",
+ 30,
+ {"phase": "delegation"},
+ )
+
+ # Delegate to the wrapped strategy with enriched context
+ # Pass the original query but with pre-loaded relevant links
+ result = self.delegate_strategy.analyze_topic(query)
+
+ # Enhance result with context information
+ result["contextual_search"] = True
+ result["past_links_used"] = len(relevant_links)
+ result["total_past_links"] = len(self.past_links)
+
+ # Add a note about context usage in the findings
+ if relevant_links and "formatted_findings" in result:
+ context_note = f"\n\n**Note:** This follow-up search reused {len(relevant_links)} relevant sources from previous research."
+ result["formatted_findings"] += context_note
+
+ # Store the enriched query for reference
+ result["enriched_query"] = enriched_query
+
+ self._update_progress(
+ "Contextual follow-up search complete", 100, {"phase": "complete"}
+ )
+
+ return result
+
+ def set_progress_callback(self, callback):
+ """Set progress callback for both wrapper and delegate."""
+ super().set_progress_callback(callback)
+ if self.delegate_strategy:
+ self.delegate_strategy.set_progress_callback(callback)
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..df7a319884
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/strategies/followup/__init__.py
@@ -0,0 +1,10 @@
+"""
+Follow-up Research Strategies
+
+This module 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..e76d7548ba
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/strategies/followup/enhanced_contextual_followup.py
@@ -0,0 +1,552 @@
+"""
+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 ...query_generation.followup_query_reformulator import (
+ FollowUpQueryReformulator,
+)
+from ...filters.followup_relevance_filter import FollowUpRelevanceFilter
+from ...knowledge.followup_context_manager import FollowUpContextManager
+
+
+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.query_reformulator = FollowUpQueryReformulator(model)
+ self.relevance_filter = FollowUpRelevanceFilter(model)
+ self.context_manager = FollowUpContextManager(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 original query directly without reformulation
+ contextualized_query = self._create_contextualized_query(query, query)
+
+ # 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 _create_contextualized_query(
+ self, reformulated_query: str, original_query: str
+ ) -> str:
+ """
+ Create a query that includes full context from previous research.
+
+ This ensures the LLM understands that queries like "provide data in a table"
+ refer to the previous research findings, not a new search about tables.
+
+ Args:
+ reformulated_query: The reformulated search query
+ original_query: The original user query
+
+ Returns:
+ Query with full context embedded
+ """
+ # Get the past findings - the complete text, no truncation
+ past_findings = self.full_context.get("past_findings", "")
+
+ # Get the original research query
+ original_research_query = self.full_context.get("original_query", "")
+
+ # 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_research_query}
+
+Previous findings:
+{past_findings}
+
+---
+USER'S FOLLOW-UP REQUEST: {original_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
+
+ def _reformulate_query(self, query: str) -> str:
+ """
+ Reformulate the query using past context.
+
+ Args:
+ query: Original follow-up query
+
+ Returns:
+ Reformulated query
+ """
+ past_findings = self.full_context.get("summary", "")
+ past_sources = self.full_context.get("past_sources", [])
+ original_query = self.full_context.get("original_query", "")
+
+ reformulated = self.query_reformulator.reformulate_with_context(
+ query=query,
+ past_findings=past_findings,
+ past_sources=past_sources,
+ original_query=original_query,
+ )
+
+ logger.info(f"Query reformulated: '{query}' -> '{reformulated}'")
+ return reformulated
+
+ 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
+ relevant = self.relevance_filter.filter_results(
+ results=past_sources,
+ query=query,
+ max_results=15, # Keep more sources for follow-up
+ threshold=0.3,
+ past_findings=self.full_context.get("past_findings", ""),
+ )
+
+ 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"
+ )
+
+ # Also pass context through settings if delegate supports it
+ if (
+ hasattr(self.delegate_strategy, "settings_snapshot")
+ and self.delegate_strategy.settings_snapshot
+ ):
+ self.delegate_strategy.settings_snapshot["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 _update_settings_with_context(self):
+ """
+ Update settings snapshot with complete follow-up context.
+ """
+ if not self.settings_snapshot:
+ self.settings_snapshot = {}
+
+ # Format context for settings
+ context_for_settings = (
+ self.context_manager.format_for_settings_snapshot(self.full_context)
+ )
+
+ # Add to settings
+ self.settings_snapshot.update(context_for_settings)
+
+ # Also update delegate's settings
+ if self.delegate_strategy and hasattr(
+ self.delegate_strategy, "settings_snapshot"
+ ):
+ if not self.delegate_strategy.settings_snapshot:
+ self.delegate_strategy.settings_snapshot = {}
+ self.delegate_strategy.settings_snapshot.update(
+ context_for_settings
+ )
+
+ logger.debug("Updated settings snapshot with follow-up context")
+
+ def _enhance_results(
+ self,
+ result: Dict,
+ original_query: str,
+ reformulated_query: str,
+ relevant_sources: List[Dict],
+ ) -> Dict:
+ """
+ Enhance search results with context information.
+
+ Args:
+ result: Results from delegate strategy
+ original_query: Original follow-up query
+ reformulated_query: Reformulated query used for search
+ relevant_sources: Sources that were reused
+
+ Returns:
+ Enhanced results
+ """
+ # Add follow-up metadata
+ result["followup_metadata"] = {
+ "original_query": original_query,
+ "reformulated_query": reformulated_query,
+ "past_sources_reused": len(relevant_sources),
+ "parent_research_id": self.full_context.get(
+ "parent_research_id", ""
+ ),
+ "original_research_query": self.full_context.get(
+ "original_query", ""
+ ),
+ }
+
+ # Add context summary to findings if available
+ if "formatted_findings" in result and self.full_context.get("summary"):
+ context_note = f"\n\n**Context from Previous Research:**\n{self.full_context['summary']}"
+ result["formatted_findings"] = (
+ context_note + "\n\n" + result["formatted_findings"]
+ )
+
+ # Mark this as enhanced follow-up research
+ result["strategy_used"] = "enhanced_contextual_followup"
+ result["contextual_search"] = True
+
+ # Include information about gaps addressed
+ if hasattr(self.context_manager, "identify_gaps"):
+ gaps = self.context_manager.identify_gaps(
+ self.research_context, original_query
+ )
+ if gaps:
+ result["gaps_addressed"] = gaps
+
+ # Add source statistics
+ all_sources = result.get("all_links_of_system", [])
+ new_sources = [
+ s for s in all_sources if not s.get("from_past_research")
+ ]
+
+ result["source_statistics"] = {
+ "total_sources": len(all_sources),
+ "reused_sources": len(relevant_sources),
+ "new_sources": len(new_sources),
+ "past_sources_available": len(
+ self.full_context.get("past_sources", [])
+ ),
+ }
+
+ logger.info(
+ f"Enhanced results: {len(relevant_sources)} past sources reused, "
+ f"{len(new_sources)} new sources found"
+ )
+
+ return result
+
+ 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)
+
+ def generate_alternative_approaches(self, query: str) -> List[str]:
+ """
+ Generate alternative approaches for the follow-up research.
+
+ Args:
+ query: The follow-up query
+
+ Returns:
+ List of alternative query approaches
+ """
+ alternatives = self.query_reformulator.generate_alternative_queries(
+ query=query,
+ past_findings=self.full_context.get("past_findings", ""),
+ max_alternatives=3,
+ )
+
+ return alternatives
diff --git a/src/local_deep_research/followup_research/README.md b/src/local_deep_research/followup_research/README.md
new file mode 100644
index 0000000000..adc3bfd33e
--- /dev/null
+++ b/src/local_deep_research/followup_research/README.md
@@ -0,0 +1,115 @@
+# Follow-up Research Module
+
+This module provides functionality for asking follow-up questions on existing research, reusing previous findings and sources to provide contextual answers.
+
+## Architecture
+
+The follow-up research feature is organized as a self-contained module:
+
+```
+followup_research/
+├── __init__.py # Module exports
+├── models.py # Data models (FollowUpRequest, FollowUpResponse)
+├── service.py # Business logic for follow-up research
+├── routes.py # Flask API endpoints
+├── static/
+│ └── followup.js # Frontend JavaScript
+└── README.md # This file
+```
+
+## How It Works
+
+1. **User initiates follow-up**: Clicks "Ask Follow-up Question" on a research result
+2. **Context loading**: Service loads parent research data and resources from database
+3. **Strategy execution**: Uses `ContextualFollowUpStrategy` which:
+ - Filters relevant links from parent research
+ - Summarizes relevant findings
+ - Delegates to `source-based` strategy for quick summary
+4. **Results**: Returns focused answer building on previous research
+
+## Configuration
+
+The follow-up research uses these default settings:
+- **Strategy**: `contextual-followup` (wrapper) → `source-based` (delegate)
+- **Iterations**: 1 (quick summary mode)
+- **Questions per iteration**: 3
+
+## API Endpoints
+
+### POST `/api/followup/prepare`
+Loads parent research context for preview.
+
+Request:
+```json
+{
+ "parent_research_id": "uuid",
+ "question": "follow-up question"
+}
+```
+
+### POST `/api/followup/start`
+Starts a follow-up research task.
+
+Request:
+```json
+{
+ "parent_research_id": "uuid",
+ "question": "follow-up question",
+ "strategy": "source-based",
+ "max_iterations": 1,
+ "questions_per_iteration": 3
+}
+```
+
+## Frontend Integration
+
+The JavaScript module is automatically included in the results page (`results.html`):
+- Located at: `web/static/js/followup.js`
+- Included via: `{{ url_for('research.serve_static', path='js/followup.js') }}`
+
+The script automatically:
+- Adds "Ask Follow-up Question" button to research results
+- Creates modal for entering follow-up questions
+- Handles API communication
+- Redirects to new research when started
+
+## Database Requirements
+
+The module requires these database tables:
+- `ResearchHistory`: Stores parent research data
+- `ResearchResource`: Stores research links and sources
+
+## Usage Example
+
+```python
+from local_deep_research.followup_research import FollowUpResearchService, FollowUpRequest
+
+# Initialize service
+service = FollowUpResearchService(username="user123")
+
+# Create follow-up request
+request = FollowUpRequest(
+ parent_research_id="abc-123",
+ question="What are the implications of the findings?",
+ strategy="source-based",
+ max_iterations=1
+)
+
+# Perform follow-up
+params = service.perform_followup(request)
+```
+
+## Benefits
+
+- **Efficiency**: Reuses already-fetched content, reducing API calls
+- **Context Preservation**: Answers build coherently on original research
+- **Clean Architecture**: Self-contained module, doesn't pollute main codebase
+- **Flexibility**: Can use any strategy as the delegate
+
+## Future Enhancements
+
+- [ ] Support multiple delegate strategies
+- [ ] Add conversation threading for multi-turn follow-ups
+- [ ] Implement relevance scoring visualization
+- [ ] Add export of follow-up chains
+- [ ] Support batch follow-up questions
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..d2fdbfb496
--- /dev/null
+++ b/src/local_deep_research/followup_research/__init__.py
@@ -0,0 +1,15 @@
+"""
+Follow-up Research Module
+
+This module 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..356348b58e
--- /dev/null
+++ b/src/local_deep_research/followup_research/routes.py
@@ -0,0 +1,324 @@
+"""
+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 as e:
+ logger.error(f"Error preparing follow-up: {e}")
+ return jsonify({"success": False, "error": str(e)}), 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",
+ },
+ "system": {
+ "timestamp": created_at,
+ "user": username,
+ "version": "1.0",
+ },
+ }
+
+ 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"About to start research with query: {research_params['query']} (type: {type(research_params['query'])})"
+ )
+ logger.info(f"Settings snapshot type: {type(settings_snapshot)}")
+ logger.info(
+ f"Settings snapshot keys: {list(settings_snapshot.keys())[:5] if settings_snapshot else 'None'}"
+ ) # First 5 keys
+
+ # 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")
+
+ research_thread = 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 as e:
+ import traceback
+
+ logger.error(f"Error starting follow-up: {e}")
+ logger.error(f"Traceback: {traceback.format_exc()}")
+ return jsonify({"success": False, "error": str(e)}), 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..084faae1fe
--- /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 as e:
+ logger.error(f"Error loading parent research: {e}")
+ 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..61cab67aed 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -50,6 +50,9 @@ from .advanced_search_system.strategies.source_based_strategy import (
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
from .citation_handler import CitationHandler
@@ -551,6 +554,134 @@ class AdvancedSearchSystem:
]:
logger.info("Creating NewsAggregationStrategy instance")
self.strategy = NewsAggregationStrategy()
+ elif strategy_name.lower() in [
+ "enhanced-contextual-followup",
+ "enhanced_contextual_followup",
+ "contextual-followup",
+ "contextual_followup",
+ ]:
+ 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"
+ )
+
+ # Create the appropriate delegate strategy based on user's selection
+ if delegate_strategy_name.lower() in [
+ "source-based",
+ "source_based",
+ "source_based_search",
+ ]:
+ delegate = SourceBasedSearchStrategy(
+ model=self.model,
+ search=self.search,
+ include_text_content=True,
+ use_cross_engine_filter=True,
+ all_links_of_system=[],
+ use_atomic_facts=False,
+ settings_snapshot=self.settings_snapshot,
+ )
+ elif delegate_strategy_name.lower() in [
+ "focused-iteration",
+ "focused_iteration",
+ ]:
+ from .advanced_search_system.strategies.focused_iteration_strategy import (
+ FocusedIterationStrategy,
+ )
+
+ delegate = FocusedIterationStrategy(
+ model=self.model,
+ search=self.search,
+ all_links_of_system=[],
+ knowledge_accumulation_mode=True,
+ settings_snapshot=self.settings_snapshot,
+ )
+ elif delegate_strategy_name.lower() in [
+ "multi-source",
+ "multi_source",
+ "multi-source_cross_reference",
+ ]:
+ from .advanced_search_system.strategies.multi_source_strategy import (
+ MultiSourceCrossReferenceStrategy,
+ )
+
+ delegate = MultiSourceCrossReferenceStrategy(
+ model=self.model,
+ search=self.search,
+ all_links_of_system=[],
+ knowledge_accumulation_mode=True,
+ settings_snapshot=self.settings_snapshot,
+ )
+ elif delegate_strategy_name.lower() in [
+ "academic",
+ "academic_deep_dive",
+ ]:
+ from .advanced_search_system.strategies.academic_strategy import (
+ AcademicDeepDiveStrategy,
+ )
+
+ delegate = AcademicDeepDiveStrategy(
+ model=self.model,
+ search=self.search,
+ all_links_of_system=[],
+ knowledge_accumulation_mode=True,
+ settings_snapshot=self.settings_snapshot,
+ )
+ elif delegate_strategy_name.lower() in [
+ "investigative",
+ "investigative_journalism",
+ ]:
+ from .advanced_search_system.strategies.investigative_strategy import (
+ InvestigativeJournalismStrategy,
+ )
+
+ delegate = InvestigativeJournalismStrategy(
+ model=self.model,
+ search=self.search,
+ all_links_of_system=[],
+ settings_snapshot=self.settings_snapshot,
+ )
+ elif delegate_strategy_name.lower() in [
+ "comprehensive",
+ "comprehensive_analysis",
+ ]:
+ from .advanced_search_system.strategies.comprehensive_strategy import (
+ ComprehensiveAnalysisStrategy,
+ )
+
+ delegate = ComprehensiveAnalysisStrategy(
+ model=self.model,
+ search=self.search,
+ all_links_of_system=[],
+ settings_snapshot=self.settings_snapshot,
+ )
+ else:
+ # Default to source-based if unknown strategy
+ logger.warning(
+ f"Unknown delegate strategy: {delegate_strategy_name}, defaulting to source-based"
+ )
+ delegate = SourceBasedSearchStrategy(
+ model=self.model,
+ search=self.search,
+ include_text_content=True,
+ use_cross_engine_filter=True,
+ all_links_of_system=[],
+ use_atomic_facts=False,
+ settings_snapshot=self.settings_snapshot,
+ )
+
+ # 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,
+ settings_snapshot=self.settings_snapshot,
+ research_context=self.research_context,
+ )
else:
logger.info("Creating StandardSearchStrategy instance")
# Import lazily to avoid database access during module import
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index f1d49ea0b4..b10563f73f 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -403,6 +403,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 3793e090ed..777b680b35 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -271,6 +271,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(
@@ -391,6 +392,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())}"
)
@@ -873,6 +881,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
@@ -1137,6 +1162,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..385f2c3526
--- /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 as e:
+ logger.error(f"Error saving research sources: {e}")
+ 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 as e:
+ logger.error(f"Error retrieving research sources: {e}")
+ 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 as e:
+ logger.error(f"Error copying research sources: {e}")
+ 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 as e:
+ logger.error(f"Error updating research with sources: {e}")
+ 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 e517eef561..2a96d6529b 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');
@@ -669,23 +665,6 @@
});
}
- // Iterations change - save to settings manager
- if (iterationsInput) {
- iterationsInput.addEventListener('change', function() {
- const iterations = parseInt(this.value);
- console.log('Iterations changed to:', iterations);
- saveSearchSetting('search.iterations', iterations);
- });
- }
-
- // Questions per iteration change - save to settings manager
- if (questionsPerIterationInput) {
- questionsPerIterationInput.addEventListener('change', function() {
- const questions = parseInt(this.value);
- console.log('Questions per iteration changed to:', questions);
- saveSearchSetting('search.questions_per_iteration', questions);
- });
- }
// Load options data from APIs
Promise.all([
@@ -2072,9 +2051,6 @@
// 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
@@ -2105,8 +2081,6 @@
model: model,
custom_endpoint: customEndpoint,
search_engine: searchEngine,
- iterations: iterations,
- questions_per_iteration: questionsPerIteration,
strategy: strategy
};
diff --git a/src/local_deep_research/web/static/js/components/settings_sync.js b/src/local_deep_research/web/static/js/components/settings_sync.js
index 45d373e6aa..5544d6c9bb 100644
--- a/src/local_deep_research/web/static/js/components/settings_sync.js
+++ b/src/local_deep_research/web/static/js/components/settings_sync.js
@@ -80,22 +80,8 @@ function connectMenuSettings() {
});
}
- // Handle iterations and questions per iteration
- const iterationsInput = document.getElementById('iterations');
- if (iterationsInput) {
- iterationsInput.addEventListener('change', function(e) {
- console.log('Iterations changed to:', this.value);
- saveMenuSettings('search.iterations', this.value);
- });
- }
-
- const questionsInput = document.getElementById('questions_per_iteration');
- if (questionsInput) {
- questionsInput.addEventListener('change', function(e) {
- console.log('Questions per iteration changed to:', this.value);
- saveMenuSettings('search.questions_per_iteration', this.value);
- });
- }
+ // Iterations and questions are now only configured in Settings page
+ // No longer synced from research form
console.log('Menu settings handlers initialized');
}
diff --git a/src/local_deep_research/web/static/js/followup.js b/src/local_deep_research/web/static/js/followup.js
new file mode 100644
index 0000000000..803a63e5a0
--- /dev/null
+++ b/src/local_deep_research/web/static/js/followup.js
@@ -0,0 +1,368 @@
+/**
+ * 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
+ */
+ createModal() {
+ // Check if modal already exists
+ if (document.getElementById('followUpModal')) {
+ return;
+ }
+
+ const modalHtml = `
+ <div class="modal fade" id="followUpModal" tabindex="-1" aria-labelledby="followUpModalLabel" aria-hidden="true" style="z-index: 10000;">
+ <div class="modal-dialog modal-lg modal-dialog-centered">
+ <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>
+ `;
+
+ // Add modal to page
+ document.body.insertAdjacentHTML('beforeend', modalHtml);
+ this.modalElement = document.getElementById('followUpModal');
+
+ // 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) {
+ this.createModal();
+ }
+
+ // Load parent context
+ await this.loadParentContext();
+
+ // Show modal
+ const modal = new bootstrap.Modal(this.modalElement);
+ modal.show();
+ }
+
+ /**
+ * 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..49d6adf9d2 100644
--- a/src/local_deep_research/web/static/js/research_form.js
+++ b/src/local_deep_research/web/static/js/research_form.js
@@ -14,10 +14,6 @@ document.addEventListener('DOMContentLoaded', function() {
* Initialize the research form with values from settings
*/
function initResearchForm() {
- // Get form elements
- const iterationsInput = document.getElementById('iterations');
- const questionsInput = document.getElementById('questions_per_iteration');
-
// Fetch all settings at once (more efficient)
fetch(URLS.SETTINGS_API.BASE)
.then(response => {
@@ -34,18 +30,6 @@ function initResearchForm() {
// Cache settings globally for warning logic
globalSettings = settings;
- // Look for the iterations setting
- for (const key in settings) {
- const setting = settings[key];
- if (key === 'search.iterations') {
- iterationsInput.value = setting.value;
- }
-
- if (key === 'search.questions_per_iteration') {
- questionsInput.value = setting.value;
- }
- }
-
// Initialize warnings after settings are loaded
initializeWarnings();
}
@@ -77,32 +61,11 @@ function patchFormSubmitHandler() {
/**
* Save research settings to the database
+ * Note: Iterations and questions are now only configured in Settings page
*/
function saveResearchSettings() {
- const iterations = document.getElementById('iterations').value;
- const questions = document.getElementById('questions_per_iteration').value;
-
-
- // Get CSRF token
- const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
-
- // Save settings
- fetch(URLS.SETTINGS_API.SAVE_ALL_SETTINGS, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': csrfToken
- },
- body: JSON.stringify({
- 'search.iterations': parseInt(iterations),
- 'search.questions_per_iteration': parseInt(questions)
- })
- })
- .then(response => response.json())
- .then(data => {
- })
- .catch(error => {
- });
+ // Settings are now managed through the Settings page only
+ // This function is kept for compatibility but no longer saves iterations/questions
}
/**
diff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.html
index 7e2972136b..1155543fe9 100644
--- a/src/local_deep_research/web/templates/pages/research.html
+++ b/src/local_deep_research/web/templates/pages/research.html
@@ -126,21 +126,6 @@
</div>
</div>
- <div class="form-row">
- <!-- Search Iterations -->
- <div class="form-group half">
- <label for="iterations">Search Iterations</label>
- <input type="number" id="iterations" name="iterations" class="form-control" min="1" max="5" value="{{ settings.search_iterations }}">
- <span class="input-help">Number of research cycles to perform</span>
- </div>
-
- <!-- Questions Per Iteration -->
- <div class="form-group half">
- <label for="questions_per_iteration">Questions Per Iteration</label>
- <input type="number" id="questions_per_iteration" name="questions_per_iteration" class="form-control" min="1" max="10" value="{{ settings.search_questions_per_iteration }}">
- <span class="input-help">Follow-up questions in each cycle</span>
- </div>
- </div>
<div class="form-row">
<!-- Search Strategy -->
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..f80f364319 100644
--- a/src/local_deep_research/web/utils/formatters.py
+++ b/src/local_deep_research/web/utils/formatters.py
@@ -45,29 +45,30 @@ 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
+ # Keep SEARCH QUESTIONS BY ITERATION section - it's useful information
+ # Previously this was being removed, but users want to see the iteration questions
+ # if "SEARCH QUESTIONS BY ITERATION:" in content:
+ # logger.info("Found SEARCH QUESTIONS BY ITERATION section")
+ # search_index = content.index("SEARCH QUESTIONS BY ITERATION:")
+ # next_major_section = -1
+ # for marker in ["DETAILED FINDINGS:", "COMPLETE RESEARCH:"]:
+ # if marker in content[search_index:]:
+ # marker_pos = content.index(marker, search_index)
+ # if (
+ # next_major_section == -1
+ # or marker_pos < next_major_section
+ # ):
+ # next_major_section = marker_pos
- if next_major_section != -1:
- logger.info(
- f"Removing section from index {search_index} to {next_major_section}"
- )
- content = content[:search_index] + content[next_major_section:]
- else:
- # If no later section, just remove everything from SEARCH QUESTIONS onwards
- logger.info(f"Removing everything after index {search_index}")
- content = content[:search_index].strip()
+ # if next_major_section != -1:
+ # logger.info(
+ # f"Removing section from index {search_index} to {next_major_section}"
+ # )
+ # content = content[:search_index] + content[next_major_section:]
+ # else:
+ # # If no later section, just remove everything from SEARCH QUESTIONS onwards
+ # logger.info(f"Removing everything after index {search_index}")
+ # content = content[:search_index].strip()
logger.info(f"Final markdown length: {len(content.strip())}")
return content.strip()
diff --git a/test_api_endpoint.py b/test_api_endpoint.py
deleted file mode 100644
index 5f65488b9c..0000000000
--- a/test_api_endpoint.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/env python3
-"""Test the API endpoint directly"""
-
-import os
-import sys
-import tempfile
-import shutil
-
-# Set up environment
-temp_dir = tempfile.mkdtemp()
-os.environ["LDR_DATA_DIR"] = temp_dir
-os.environ["TESTING"] = "1"
-
-# Add src to path
-sys.path.insert(0, "src")
-
-try:
- from local_deep_research.web.app_factory import create_app
- from local_deep_research.database.auth.init_auth_db import (
- init_auth_database,
- )
-
- print("Creating Flask app...")
- app, _ = create_app()
- app.config["TESTING"] = True
- app.config["WTF_CSRF_ENABLED"] = False
-
- # Initialize auth database
- init_auth_database()
-
- client = app.test_client()
-
- # Register and login
- print("\nRegistering test user...")
- client.post(
- "/auth/register",
- data={
- "username": "testuser",
- "password": "testpassword123",
- "confirm_password": "testpassword123",
- "acknowledge": "true",
- },
- )
-
- print("Logging in...")
- client.post(
- "/auth/login",
- data={
- "username": "testuser",
- "password": "testpassword123",
- },
- )
-
- # Test the API endpoint
- print("\nTesting /api/v1/quick_summary endpoint...")
- payload = {
- "query": "test",
- "search_tool": "wikipedia",
- "iterations": 1,
- "temperature": 0.7,
- }
-
- response = client.post(
- "/api/v1/quick_summary",
- json=payload,
- content_type="application/json",
- )
-
- print(f"Status code: {response.status_code}")
- print(f"Response data: {response.data.decode()[:500]}")
-
- if response.status_code == 500:
- print("\nFull response:")
- print(response.data.decode())
-
-except Exception as e:
- print(f"Error: {e}")
- import traceback
-
- traceback.print_exc()
-finally:
- # Clean up
- shutil.rmtree(temp_dir, ignore_errors=True)