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: Add Iterative Refinement Strategy for progressive research improvement

LearningCircuitf18f7780cf8e
diff --git a/src/local_deep_research/advanced_search_system/strategies/iterative_refinement_strategy.py b/src/local_deep_research/advanced_search_system/strategies/iterative_refinement_strategy.py
new file mode 100644
index 0000000000..cbb5d2a4c3
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/strategies/iterative_refinement_strategy.py
@@ -0,0 +1,485 @@
+"""
+Iterative Refinement Strategy
+
+This strategy orchestrates iterative refinement of research results by:
+1. Running initial research with a base strategy
+2. Using LLM to evaluate results and identify gaps
+3. Generating follow-up queries to address gaps
+4. Calling the follow-up strategy to refine results
+5. Repeating until quality threshold is met or max iterations reached
+"""
+
+import json
+from typing import Dict
+from loguru import logger
+
+from .base_strategy import BaseSearchStrategy
+from .followup.enhanced_contextual_followup import (
+ EnhancedContextualFollowUpStrategy,
+)
+
+
+class IterativeRefinementStrategy(BaseSearchStrategy):
+ """
+ Strategy that iteratively refines research results using LLM-guided decisions.
+
+ This strategy acts as an orchestrator that:
+ - Runs initial research using any base strategy
+ - Evaluates results quality with LLM
+ - Generates targeted follow-up queries
+ - Uses EnhancedContextualFollowUpStrategy for refinement
+ - Accumulates knowledge across iterations
+ """
+
+ def __init__(
+ self,
+ model,
+ search,
+ initial_strategy: BaseSearchStrategy,
+ all_links_of_system=None,
+ settings_snapshot=None,
+ evaluation_frequency: int = 1,
+ max_refinements: int = 3,
+ confidence_threshold: float = 0.8,
+ **kwargs,
+ ):
+ """
+ Initialize the iterative refinement strategy.
+
+ Args:
+ model: The LLM model to use
+ search: The search engine
+ initial_strategy: Base strategy for initial research and follow-up delegate
+ all_links_of_system: Accumulated links from past searches
+ settings_snapshot: Settings configuration
+ evaluation_frequency: Evaluate after N refinement rounds (1 = every round)
+ max_refinements: Maximum number of refinement cycles
+ confidence_threshold: Confidence level to stop refinement (0.0-1.0)
+ """
+ super().__init__(all_links_of_system, settings_snapshot)
+
+ self.model = model
+ self.search = search
+ self.initial_strategy = initial_strategy
+ self.evaluation_frequency = evaluation_frequency
+ self.max_refinements = max_refinements
+ self.confidence_threshold = confidence_threshold
+
+ # Track refinement history
+ self.refinement_history = []
+
+ logger.info(
+ f"IterativeRefinementStrategy initialized with "
+ f"max_refinements={max_refinements}, "
+ f"confidence_threshold={confidence_threshold}, "
+ f"evaluation_frequency={evaluation_frequency}"
+ )
+
+ def analyze_topic(self, query: str) -> Dict:
+ """
+ Analyze a topic with iterative refinement.
+
+ Args:
+ query: The research query to analyze
+
+ Returns:
+ Research findings with iterative refinements
+ """
+ logger.info(f"Starting iterative refinement research for: {query}")
+
+ self._update_progress(
+ "Running initial research",
+ 10,
+ {"phase": "initial_research", "query": query},
+ )
+
+ # Step 1: Run initial research
+ results = self.initial_strategy.analyze_topic(query)
+
+ # Build initial research context
+ research_context = self._build_research_context(results, query)
+
+ # Track all accumulated sources
+ all_accumulated_sources = results.get("all_links_of_system", []).copy()
+
+ refinement_count = 0
+ rounds_since_evaluation = 0
+
+ # Main refinement loop
+ while refinement_count < self.max_refinements:
+ rounds_since_evaluation += 1
+
+ # Evaluate if it's time (based on frequency)
+ if rounds_since_evaluation >= self.evaluation_frequency:
+ progress = 20 + (refinement_count * 60 / self.max_refinements)
+
+ self._update_progress(
+ f"Evaluating research quality (refinement {refinement_count + 1}/{self.max_refinements})",
+ progress,
+ {"phase": "evaluation", "refinement": refinement_count + 1},
+ )
+
+ # Step 2: Use LLM to evaluate current results
+ evaluation = self._evaluate_with_llm(
+ results, query, refinement_count
+ )
+
+ logger.info(
+ f"LLM evaluation - Action: {evaluation.get('action')}, "
+ f"Confidence: {evaluation.get('confidence', 0):.2f}"
+ )
+
+ # Record evaluation in history
+ self.refinement_history.append(
+ {
+ "iteration": refinement_count + 1,
+ "evaluation": evaluation,
+ "sources_count": len(all_accumulated_sources),
+ }
+ )
+
+ # Check if we should stop
+ if evaluation.get("action") == "COMPLETE":
+ logger.info("LLM determined research is complete")
+ break
+
+ if evaluation.get("confidence", 0) >= self.confidence_threshold:
+ logger.info(
+ f"Confidence threshold met: {evaluation.get('confidence'):.2f} >= {self.confidence_threshold}"
+ )
+ break
+
+ # Step 3: Generate follow-up query for refinement
+ followup_query = evaluation.get("refinement_query")
+
+ if not followup_query:
+ logger.warning(
+ "No refinement query generated, stopping refinement"
+ )
+ break
+
+ logger.info(f"Refinement query: {followup_query}")
+
+ self._update_progress(
+ f"Running follow-up research: {followup_query[:100]}...",
+ progress + 10,
+ {"phase": "followup", "query": followup_query},
+ )
+
+ # Step 4: Create follow-up strategy with accumulated context
+ followup_strategy = EnhancedContextualFollowUpStrategy(
+ model=self.model,
+ search=self.search,
+ delegate_strategy=self.initial_strategy.__class__(
+ search=self.search,
+ model=self.model,
+ all_links_of_system=[], # Fresh links for this follow-up
+ settings_snapshot=self.settings_snapshot,
+ search_original_query=False, # Don't search original in follow-up
+ ),
+ all_links_of_system=[], # Fresh for this iteration
+ settings_snapshot=self.settings_snapshot,
+ research_context=research_context,
+ )
+
+ # Pass progress callback if available
+ if self.progress_callback:
+ followup_strategy.set_progress_callback(
+ self.progress_callback
+ )
+
+ # Step 5: Run follow-up research
+ followup_results = followup_strategy.analyze_topic(
+ followup_query
+ )
+
+ # Step 6: Merge results
+ results = self._merge_results(
+ results, followup_results, followup_query
+ )
+
+ # Update accumulated sources
+ new_sources = followup_results.get("all_links_of_system", [])
+ for source in new_sources:
+ # Check if URL already exists to avoid duplicates
+ if not any(
+ s.get("url") == source.get("url")
+ for s in all_accumulated_sources
+ ):
+ all_accumulated_sources.append(source)
+
+ # Update research context for next iteration
+ research_context = self._build_research_context(results, query)
+
+ # Reset evaluation counter
+ rounds_since_evaluation = 0
+
+ refinement_count += 1
+
+ # Add refinement metadata to results
+ results["refinement_metadata"] = {
+ "strategy": "iterative_refinement",
+ "refinements_performed": refinement_count,
+ "max_refinements": self.max_refinements,
+ "final_confidence": self.refinement_history[-1]["evaluation"].get(
+ "confidence", 0
+ )
+ if self.refinement_history
+ else 0,
+ "total_sources": len(all_accumulated_sources),
+ "refinement_history": self.refinement_history,
+ }
+
+ # Ensure all accumulated sources are in final results
+ results["all_links_of_system"] = all_accumulated_sources
+
+ self._update_progress(
+ f"Research complete after {refinement_count} refinement(s)",
+ 100,
+ {"phase": "complete", "refinements": refinement_count},
+ )
+
+ logger.info(
+ f"Iterative refinement complete: {refinement_count} refinements, "
+ f"{len(all_accumulated_sources)} total sources"
+ )
+
+ return results
+
+ def _evaluate_with_llm(
+ self, results: Dict, original_query: str, iteration: int
+ ) -> Dict:
+ """
+ Use LLM to evaluate current research results and decide on refinement.
+
+ Args:
+ results: Current research results
+ original_query: The original research query
+ iteration: Current refinement iteration number
+
+ Returns:
+ Dictionary with evaluation results including action and refinement query
+ """
+ # Get formatted findings for evaluation
+ findings = results.get("formatted_findings", "")
+ sources_count = len(results.get("all_links_of_system", []))
+
+ # Build gaps summary from refinement history
+ previous_gaps = []
+ if self.refinement_history:
+ for hist in self.refinement_history:
+ gaps = hist["evaluation"].get("gaps", [])
+ previous_gaps.extend(gaps)
+
+ prompt = f"""You are evaluating research results to determine if refinement is needed.
+
+Original Research Query: {original_query}
+Current Refinement Iteration: {iteration + 1} of {self.max_refinements}
+
+Current Research Findings:
+{findings[:3000]} # Truncate for token limits
+
+Number of sources found: {sources_count}
+Previous gaps identified: {", ".join(previous_gaps) if previous_gaps else "None"}
+
+Your task:
+1. Evaluate if the current research adequately answers the original query
+2. Identify any significant gaps, missing information, or areas needing clarification
+3. Determine if refinement would meaningfully improve the answer
+4. If refinement is needed, create a specific follow-up query
+
+Consider:
+- Completeness: Does the research fully address the query?
+- Accuracy: Is there conflicting information that needs resolution?
+- Specificity: Are there vague areas that need more detail?
+- Evidence: Is there sufficient supporting evidence?
+
+Respond in JSON format:
+{{
+ "action": "REFINE" or "COMPLETE",
+ "confidence": 0.0 to 1.0 (how confident you are the research is complete),
+ "gaps": ["list", "of", "identified", "gaps"],
+ "reasoning": "Brief explanation of your decision",
+ "refinement_query": "Specific follow-up question if action is REFINE, otherwise null"
+}}
+
+Be selective with refinement - only suggest it if it would significantly improve the answer.
+Focus refinement queries on the most critical gaps."""
+
+ try:
+ response = self.model.invoke(prompt)
+
+ # Extract content from response
+ if hasattr(response, "content"):
+ content = response.content
+ else:
+ content = str(response)
+
+ # Parse JSON from response
+ # Handle case where LLM might include markdown code blocks
+ if "```json" in content:
+ json_str = content.split("```json")[1].split("```")[0].strip()
+ elif "```" in content:
+ json_str = content.split("```")[1].split("```")[0].strip()
+ else:
+ # Try to find JSON object in the response
+ import re
+
+ json_match = re.search(r"\{.*\}", content, re.DOTALL)
+ if json_match:
+ json_str = json_match.group(0)
+ else:
+ json_str = content
+
+ evaluation = json.loads(json_str)
+
+ # Validate and clean up the evaluation
+ if "action" not in evaluation:
+ evaluation["action"] = "COMPLETE"
+
+ evaluation["action"] = evaluation["action"].upper()
+ if evaluation["action"] not in ["REFINE", "COMPLETE"]:
+ evaluation["action"] = "COMPLETE"
+
+ # Ensure confidence is a float between 0 and 1
+ evaluation["confidence"] = max(
+ 0.0, min(1.0, float(evaluation.get("confidence", 0.5)))
+ )
+
+ # Ensure gaps is a list
+ if not isinstance(evaluation.get("gaps", []), list):
+ evaluation["gaps"] = []
+
+ return evaluation
+
+ except Exception as e:
+ logger.exception("Error in LLM evaluation")
+ # Return default to continue without refinement
+ return {
+ "action": "COMPLETE",
+ "confidence": 0.5,
+ "gaps": [],
+ "reasoning": f"Evaluation error: {str(e)}",
+ "refinement_query": None,
+ }
+
+ def _build_research_context(
+ self, results: Dict, original_query: str
+ ) -> Dict:
+ """
+ Build research context for follow-up strategy.
+
+ Args:
+ results: Current research results
+ original_query: Original research query
+
+ Returns:
+ Context dictionary for follow-up strategy
+ """
+ context = {
+ "original_query": original_query,
+ "past_findings": results.get("formatted_findings", ""),
+ "past_sources": results.get("all_links_of_system", []),
+ "resources": results.get("all_links_of_system", []),
+ "delegate_strategy": self.initial_strategy.__class__.__name__.replace(
+ "Strategy", ""
+ )
+ .replace("SearchStrategy", "")
+ .lower(),
+ }
+
+ # Add iteration information if available
+ if "questions_by_iteration" in results:
+ context["questions_by_iteration"] = results[
+ "questions_by_iteration"
+ ]
+
+ # Add findings if available
+ if "findings" in results:
+ context["findings"] = results["findings"]
+
+ return context
+
+ def _merge_results(
+ self,
+ original_results: Dict,
+ followup_results: Dict,
+ followup_query: str,
+ ) -> Dict:
+ """
+ Merge follow-up results into original results.
+
+ Args:
+ original_results: Original research results
+ followup_results: Follow-up research results
+ followup_query: The follow-up query used
+
+ Returns:
+ Merged results dictionary
+ """
+ merged = original_results.copy()
+
+ # Append new findings
+ if "findings" in followup_results:
+ if "findings" not in merged:
+ merged["findings"] = []
+
+ # Add a separator finding
+ merged["findings"].append(
+ {
+ "phase": f"Refinement: {followup_query[:100]}",
+ "content": f"Follow-up research for: {followup_query}",
+ "type": "refinement_separator",
+ }
+ )
+
+ # Add the new findings
+ merged["findings"].extend(followup_results["findings"])
+
+ # Merge formatted findings with clear separation
+ if "formatted_findings" in followup_results:
+ original_findings = merged.get("formatted_findings", "")
+ followup_findings = followup_results["formatted_findings"]
+
+ merged["formatted_findings"] = f"""{original_findings}
+
+---
+## Refinement: {followup_query}
+
+{followup_findings}"""
+
+ # Update current knowledge to latest
+ if "current_knowledge" in followup_results:
+ merged["current_knowledge"] = followup_results["current_knowledge"]
+
+ # Merge questions by iteration
+ if "questions_by_iteration" in followup_results:
+ if "questions_by_iteration" not in merged:
+ merged["questions_by_iteration"] = {}
+
+ # Add follow-up questions with new keys
+ max_iter = (
+ max(merged["questions_by_iteration"].keys())
+ if merged["questions_by_iteration"]
+ else 0
+ )
+ for key, questions in followup_results[
+ "questions_by_iteration"
+ ].items():
+ merged["questions_by_iteration"][max_iter + key] = questions
+
+ # Merge links (handled in main loop to avoid duplicates)
+ # Don't merge here as we handle it in analyze_topic
+
+ return merged
+
+ def set_progress_callback(self, callback):
+ """
+ Set progress callback for both this strategy and delegates.
+
+ Args:
+ callback: Progress callback function
+ """
+ super().set_progress_callback(callback)
+ if self.initial_strategy:
+ self.initial_strategy.set_progress_callback(callback)
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index e4b3543917..98ee96b80c 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -713,7 +713,8 @@
"name": "Search Strategy",
"options": [
"source-based",
- "focused-iteration"
+ "focused-iteration",
+ "iterative-refinement"
],
"step": null,
"type": "SEARCH",
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index 3b362c72ae..c1d334eeb4 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -64,6 +64,7 @@ class AdvancedSearchSystem:
- "concurrent-dual-confidence": Concurrent search & evaluation with progressive constraint relaxation
- "modular": Modular architecture using constraint checking and candidate exploration modules
- "browsecomp-entity": Entity-focused search for BrowseComp questions with knowledge graph building
+ - "iterative-refinement": Iteratively refines results using LLM evaluation and follow-up queries
include_text_content: If False, only includes metadata and links in search results
use_cross_engine_filter: Whether to filter results across search
engines.
diff --git a/src/local_deep_research/search_system_factory.py b/src/local_deep_research/search_system_factory.py
index 80056c3a13..640375f474 100644
--- a/src/local_deep_research/search_system_factory.py
+++ b/src/local_deep_research/search_system_factory.py
@@ -615,6 +615,39 @@ def create_strategy(
all_links_of_system=all_links_of_system,
)
+ # Iterative refinement strategy
+ elif strategy_name_lower in [
+ "iterative-refinement",
+ "iterative_refinement",
+ ]:
+ from .advanced_search_system.strategies.iterative_refinement_strategy import (
+ IterativeRefinementStrategy,
+ )
+
+ # Get the initial strategy to use (default to source-based)
+ initial_strategy_name = kwargs.get("initial_strategy", "source-based")
+
+ # Create the initial strategy
+ initial_strategy = create_strategy(
+ strategy_name=initial_strategy_name,
+ model=model,
+ search=search,
+ all_links_of_system=[], # Fresh list for initial strategy
+ settings_snapshot=settings_snapshot,
+ search_original_query=kwargs.get("search_original_query", True),
+ )
+
+ return IterativeRefinementStrategy(
+ model=model,
+ search=search,
+ initial_strategy=initial_strategy,
+ all_links_of_system=all_links_of_system,
+ settings_snapshot=settings_snapshot,
+ evaluation_frequency=kwargs.get("evaluation_frequency", 1),
+ max_refinements=kwargs.get("max_refinements", 3),
+ confidence_threshold=kwargs.get("confidence_threshold", 0.8),
+ )
+
# Standard strategy
elif strategy_name_lower == "standard":
from .advanced_search_system.strategies.standard_strategy import (
diff --git a/src/local_deep_research/web/templates/pages/news-subscription-form.html b/src/local_deep_research/web/templates/pages/news-subscription-form.html
index be0564a1fb..c167467545 100644
--- a/src/local_deep_research/web/templates/pages/news-subscription-form.html
+++ b/src/local_deep_research/web/templates/pages/news-subscription-form.html
@@ -198,6 +198,7 @@
<select class="form-select" id="subscription-strategy">
<option value="source-based" {% if (subscription and subscription.search_strategy == 'source-based') or (not subscription and default_settings.search_strategy == 'source-based') %}selected{% endif %}>Source Based (Comprehensive research)</option>
<option value="focused-iteration" {% if (subscription and subscription.search_strategy == 'focused-iteration') or (not subscription and default_settings.search_strategy == 'focused-iteration') %}selected{% endif %}>Focused Iteration (Fast Q&A)</option>
+ <option value="iterative-refinement" {% if (subscription and subscription.search_strategy == 'iterative-refinement') or (not subscription and default_settings.search_strategy == 'iterative-refinement') %}selected{% endif %}>Iterative Refinement (Progressive refinement)</option>
</select>
<div class="form-text">Choose the search strategy that best fits your needs</div>
</div>
diff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.html
index 6ea627ed5a..9e1f100e29 100644
--- a/src/local_deep_research/web/templates/pages/research.html
+++ b/src/local_deep_research/web/templates/pages/research.html
@@ -149,8 +149,9 @@
<select id="strategy" name="strategy" class="ldr-form-control">
<option value="source-based" {% if settings.search_strategy == 'source-based' %}selected{% endif %}>Source-Based (~70% SimpleQA, Comprehensive Research & Text Creation)</option>
<option value="focused-iteration" {% if settings.search_strategy == 'focused-iteration' %}selected{% endif %}>Focused Iteration (~95% SimpleQA, Fast & Precise Q&A)</option>
+ <option value="iterative-refinement" {% if settings.search_strategy == 'iterative-refinement' %}selected{% endif %}>Iterative Refinement (LLM-guided progressive refinement)</option>
</select>
- <span class="input-help">Source-Based: Proven strategy for detailed research. Focused Iteration: 2x faster for direct answers. Performance varies with LLM and configuration.</span>
+ <span class="input-help">Source-Based: Proven strategy for detailed research. Focused Iteration: 2x faster for direct answers. Iterative Refinement: Automatically refines results until comprehensive. Performance varies with LLM and configuration.</span>
</div>
<!-- Empty div for layout balance -->