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.

refactor: Remove unused follow-up research components

LearningCircuitcaf33fd1b72e
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
deleted file mode 100644
index 6e265ffbed..0000000000
--- a/src/local_deep_research/advanced_search_system/query_generation/followup_query_reformulator.py
+++ /dev/null
@@ -1,268 +0,0 @@
-"""
-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:
- logger.exception("Failed to combine query with findings")
- # 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/followup/enhanced_contextual_followup.py b/src/local_deep_research/advanced_search_system/strategies/followup/enhanced_contextual_followup.py
index e76d7548ba..4c1500cbf1 100644
--- a/src/local_deep_research/advanced_search_system/strategies/followup/enhanced_contextual_followup.py
+++ b/src/local_deep_research/advanced_search_system/strategies/followup/enhanced_contextual_followup.py
@@ -9,9 +9,6 @@ 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
@@ -56,7 +53,6 @@ class EnhancedContextualFollowUpStrategy(BaseSearchStrategy):
self.research_context = research_context or {}
# Initialize components
- self.query_reformulator = FollowUpQueryReformulator(model)
self.relevance_filter = FollowUpRelevanceFilter(model)
self.context_manager = FollowUpContextManager(model)
@@ -314,30 +310,6 @@ Please address this specific request using the context and findings above.
)
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.
@@ -422,106 +394,6 @@ Please address this specific request using the context and findings above.
"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.
@@ -532,21 +404,3 @@ Please address this specific request using the context and findings above.
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