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: delete 3 dead strategy files and 4 orphaned test files (~3,200 lines) (#3147)

LearningCircuit249d2440a3d8
diff --git a/docs/strategies/deleted/pr-3147-dead-strategies.md b/docs/strategies/deleted/pr-3147-dead-strategies.md
new file mode 100644
index 0000000000..0d1be8e07e
--- /dev/null
+++ b/docs/strategies/deleted/pr-3147-dead-strategies.md
@@ -0,0 +1,105 @@
+# PR #3147 — delete 3 dead strategy files + 4 orphaned test files
+
+Components deleted in PR #3147 (see that PR for the full pre-deletion code —
+this file only summarises what was novel).
+
+All three were unreachable from `search_system_factory.py` at deletion, with
+no consumers outside their own test files and the `STRATEGY_IMPORTS` list in
+`tests/strategies/conftest.py`.
+
+---
+
+## Component: `ImprovedEvidenceBasedStrategy`
+
+- File deleted: `src/local_deep_research/advanced_search_system/strategies/improved_evidence_based_strategy.py` (782 LOC at deletion).
+- Reachability: not in `search_system_factory.py`; only referenced by its own two test files and `STRATEGY_IMPORTS`.
+- Closest reachable successor: `EnhancedEvidenceBasedStrategy` (`src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy_v2.py`, factory key `"evidence"`).
+
+### Useful ideas from the pre-deletion version
+
+None uniquely interesting. Every distinctive mechanism had a more capable
+analog in v2 at deletion time — 4-stage discovery vs v2's 5-stage, binary
+failed-query blacklist vs v2's EMA pattern-success tracking, simple
+source-ratio diversity vs v2's entropy-based scoring, plain dict state vs
+v2's `QueryPattern` / `SourceProfile` dataclasses, naive re-search final
+verification vs v2's unused-source-driven verification.
+
+### Why deletion was safe
+
+v2 was the factory's `"evidence"` target at deletion and is a strict
+functional superset. Last 12 months of git history on the Improved file
+showed lint sweeps and audit fixes only — no feature work.
+
+### Recovery path
+
+Do not restore the file. If any piece of the v1-improved flow proves useful,
+add it as a method or option on `EnhancedEvidenceBasedStrategy`.
+
+---
+
+## Component: `LLMDrivenModularStrategy`
+
+- File deleted: `src/local_deep_research/advanced_search_system/strategies/llm_driven_modular_strategy.py` (~820 LOC at deletion).
+- Reachability: not in `search_system_factory.py`; inner classes (`CandidateConfidence`, `LLMConstraintProcessor`, `EarlyRejectionManager`) were duplicated in `ModularStrategy`.
+- Closest reachable successor: `ModularStrategy` (`src/local_deep_research/advanced_search_system/strategies/modular_strategy.py`, factory keys `"modular"` / `"modular-parallel"`). The factory instantiates it with `llm_constraint_processing=True` by default, so "LLM-driven" behavior is already the production path.
+
+### Useful ideas from the pre-deletion version
+
+- **5-phase query generation** — LLMDriven ran a 5-step pipeline
+ (decompose → combinations → creative-angles → optimize → execute) with
+ two extra LLM calls that `ModularStrategy` doesn't make. See
+ `generate_creative_search_angles()` and `optimize_search_combinations()`
+ in the pre-deletion file. The first asks the model for 30–40
+ alternate-angle queries (character / title / genre guessing, reverse
+ searches) via a detective framing; the second reorganises generated
+ queries into priority buckets (`high_priority`, `systematic_granular`,
+ `creative_angles`, `contextual_searches`, `fallback_broad`) and
+ de-dupes. Both are exploratory prompt-engineering tricks that were
+ never validated against a benchmark; the extra cost was never shown
+ to be worth it.
+- **Divergent `EarlyRejectionManager` thresholds** — LLMDriven rejected
+ on `negative > 0.7 OR positive < 0.1` (aggressive dual-check);
+ `ModularStrategy` uses `negative > 0.85` only (conservative
+ single-check). `ModularStrategy`'s threshold is the deliberate
+ production default — it prefers not rejecting on absence-of-positive.
+ Noted here so a future reader doesn't "fix" it by tightening.
+
+### Why deletion was safe
+
+`ModularStrategy` subsumes LLMDriven on every axis except the two
+exploratory methods above: the shared inner classes are near-identical,
+`ModularStrategy`'s explorer factory is more flexible than LLMDriven's
+hardcoded `AdaptiveExplorer`, and only `ModularStrategy` has search
+caching, background evaluation, and candidate recovery.
+
+### Recovery path
+
+If the 5-phase generation becomes interesting for a real workload,
+reintroduce it as an optional mode on `ModularStrategy` (e.g. a
+`llm_creative_angles=True` flag) or as a new `CuratedQueryExplorer`
+variant. Do not resurrect the parallel strategy class.
+
+---
+
+## Component: `DirectSearchStrategy`
+
+- File deleted: `src/local_deep_research/advanced_search_system/strategies/direct_search_strategy.py` (219 LOC at deletion).
+- Reachability: not in `search_system_factory.py`; no dedicated test file; only referenced in `STRATEGY_IMPORTS`.
+- Closest reachable successors: `RapidSearchStrategy` (factory key `"rapid"`) and `StandardSearchStrategy` configured with `iterations=1, questions_per_iteration=1` (factory key `"standard"`).
+
+### Useful ideas from the pre-deletion version
+
+None. The strategy was a strict degenerate case of `StandardSearchStrategy`
+reduced to one iteration with one question — same progress labels, same
+citation-handler call, same findings-repository shape.
+
+### Why deletion was safe
+
+No unique logic, no dedicated tests, no external references. Any "single
+direct search" use case is already covered by an existing strategy
+configuration.
+
+### Recovery path
+
+Do not restore. Configure `RapidSearchStrategy` or
+`StandardSearchStrategy` with minimal iteration settings instead.
diff --git a/src/local_deep_research/advanced_search_system/strategies/direct_search_strategy.py b/src/local_deep_research/advanced_search_system/strategies/direct_search_strategy.py
deleted file mode 100644
index e793413311..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/direct_search_strategy.py
+++ /dev/null
@@ -1,219 +0,0 @@
-"""
-Direct search strategy for focused single-query searches.
-
-This strategy is optimized for:
-1. Entity identification queries (who, what, which)
-2. Single-pass searches without iteration
-3. Minimal LLM calls for efficiency
-"""
-
-from typing import Dict
-
-from loguru import logger
-
-from ...citation_handler import CitationHandler
-
-# Model and search should be provided by AdvancedSearchSystem
-from ..filters.cross_engine_filter import CrossEngineFilter
-from ..findings.repository import FindingsRepository
-from .base_strategy import BaseSearchStrategy
-
-
-class DirectSearchStrategy(BaseSearchStrategy):
- """
- Direct search strategy that performs a single focused search and synthesis.
-
- Key features:
- 1. No question generation - uses the original query directly
- 2. Single search pass - no iterations
- 3. Minimal LLM calls - only for final synthesis
- 4. Optimized for entity identification and focused queries
- """
-
- def __init__(
- self,
- search,
- model,
- citation_handler=None,
- include_text_content: bool = True,
- use_cross_engine_filter: bool = True,
- filter_reorder: bool = True,
- filter_reindex: bool = True,
- cross_engine_max_results: int = None,
- all_links_of_system=None,
- settings_snapshot=None,
- ):
- """Initialize with minimal components for efficiency."""
- super().__init__(
- all_links_of_system=all_links_of_system,
- settings_snapshot=settings_snapshot,
- )
- self.search = search
- self.model = model
- self.progress_callback = None
-
- self.include_text_content = include_text_content
- self.use_cross_engine_filter = use_cross_engine_filter
- self.filter_reorder = filter_reorder
- self.filter_reindex = filter_reindex
-
- # Initialize the cross-engine filter
- self.cross_engine_filter = CrossEngineFilter(
- model=self.model,
- max_results=cross_engine_max_results,
- default_reorder=filter_reorder,
- default_reindex=filter_reindex,
- )
-
- # Use provided citation_handler or create one
- self.citation_handler = citation_handler or CitationHandler(
- self.model, settings_snapshot=settings_snapshot
- )
- self.findings_repository = FindingsRepository(self.model)
-
- def analyze_topic(self, query: str) -> Dict:
- """
- Direct search implementation - single query, single synthesis.
- """
- logger.info(f"Starting direct search on topic: {query}")
- findings = []
- total_citation_count_before_this_search = len(self.all_links_of_system)
-
- self._update_progress(
- "Initializing direct search",
- 5,
- {
- "phase": "init",
- "strategy": "direct",
- "query": query[:100],
- },
- )
-
- # Check search engine
- if not self._validate_search_engine():
- return {
- "findings": [],
- "iterations": 1,
- "questions_by_iteration": {1: [query]},
- "formatted_findings": "Error: Unable to conduct research without a search engine.",
- "current_knowledge": "",
- "error": "No search engine available",
- }
-
- try:
- # Single direct search
- self._update_progress(
- f"Searching: {query[:200]}...",
- 20,
- {"phase": "searching", "query": query},
- )
-
- search_results = self.search.run(query)
-
- if not search_results:
- search_results = []
-
- self._update_progress(
- f"Found {len(search_results)} results",
- 40,
- {
- "phase": "search_complete",
- "result_count": len(search_results),
- },
- )
-
- # Optional: Apply cross-engine filter
- if self.use_cross_engine_filter and search_results:
- self._update_progress(
- "Filtering search results",
- 50,
- {"phase": "filtering"},
- )
-
- filtered_results = self.cross_engine_filter.filter_results(
- search_results,
- query,
- reorder=self.filter_reorder,
- reindex=self.filter_reindex,
- start_index=len(self.all_links_of_system),
- )
-
- self._update_progress(
- f"Filtered to {len(filtered_results)} results",
- 60,
- {
- "phase": "filtering_complete",
- "filtered_count": len(filtered_results),
- },
- )
- else:
- filtered_results = search_results
-
- # Add to all links
- self.all_links_of_system.extend(filtered_results)
-
- # Final synthesis
- self._update_progress(
- "Generating synthesis",
- 80,
- {"phase": "synthesis"},
- )
-
- final_citation_result = self.citation_handler.analyze_followup(
- query,
- filtered_results,
- previous_knowledge="",
- nr_of_links=total_citation_count_before_this_search,
- )
-
- if final_citation_result:
- synthesized_content = final_citation_result["content"]
- documents = final_citation_result.get("documents", [])
- else:
- synthesized_content = "No relevant results found."
- documents = []
-
- # Create finding
- finding = {
- "phase": "Direct Search",
- "content": synthesized_content,
- "question": query,
- "search_results": filtered_results,
- "documents": documents,
- }
- findings.append(finding)
-
- # Add documents to repository
- self.findings_repository.add_documents(documents)
-
- # Format findings
- formatted_findings = (
- self.findings_repository.format_findings_to_text(
- findings, synthesized_content
- )
- )
-
- except Exception as e:
- error_msg = f"Error in direct search: {e!s}"
- logger.exception(error_msg)
- synthesized_content = f"Error: {e!s}"
- formatted_findings = f"Error: {e!s}"
- finding = {
- "phase": "Error",
- "content": synthesized_content,
- "question": query,
- "search_results": [],
- "documents": [],
- }
- findings.append(finding)
-
- self._update_progress("Search complete", 100, {"phase": "complete"})
-
- return {
- "findings": findings,
- "iterations": 1,
- "questions_by_iteration": {1: [query]},
- "formatted_findings": formatted_findings,
- "current_knowledge": synthesized_content,
- "all_links_of_system": self.all_links_of_system,
- }
diff --git a/src/local_deep_research/advanced_search_system/strategies/improved_evidence_based_strategy.py b/src/local_deep_research/advanced_search_system/strategies/improved_evidence_based_strategy.py
deleted file mode 100644
index 7a22670f2f..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/improved_evidence_based_strategy.py
+++ /dev/null
@@ -1,782 +0,0 @@
-"""
-Improved evidence-based search strategy for complex query resolution.
-
-Key improvements:
-1. Multi-stage candidate discovery with adaptive query generation
-2. Dynamic constraint combination for cross-constraint searches
-3. Query adaptation based on partial results
-4. Enhanced source diversity management
-"""
-
-import itertools
-from collections import defaultdict
-from dataclasses import dataclass
-from datetime import datetime, UTC
-from typing import Any, Dict, List, Set
-
-from langchain_core.language_models import BaseChatModel
-
-from ...utilities.search_utilities import remove_think_tags
-from ..candidates.base_candidate import Candidate
-from ..constraints.base_constraint import Constraint, ConstraintType
-from ..constraints.constraint_analyzer import ConstraintAnalyzer
-from ..evidence.base_evidence import EvidenceType
-from ..evidence.evaluator import EvidenceEvaluator
-from ..findings.repository import FindingsRepository
-from .base_strategy import BaseSearchStrategy
-
-
-@dataclass
-class SearchAttempt:
- """Track search attempts for query adaptation."""
-
- query: str
- constraint_ids: List[str]
- results_count: int
- candidates_found: int
- timestamp: str
- strategy_type: str # 'single', 'combined', 'exploratory'
-
-
-class ImprovedEvidenceBasedStrategy(BaseSearchStrategy):
- """
- Improved evidence-based strategy with adaptive search capabilities.
-
- Key improvements:
- 1. Multi-stage candidate discovery
- 2. Adaptive query generation based on results
- 3. Cross-constraint search optimization
- 4. Source diversity tracking and enhancement
- """
-
- def __init__(
- self,
- model: BaseChatModel,
- search: Any,
- all_links_of_system: List[str],
- max_iterations: int = 20,
- confidence_threshold: float = 0.85,
- candidate_limit: int = 15, # Increased for better diversity
- evidence_threshold: float = 0.6,
- max_search_iterations: int = 3,
- questions_per_iteration: int = 3,
- min_source_diversity: int = 3, # Minimum different sources
- adaptive_query_count: int = 3, # Number of adaptive queries per stage
- ):
- """Initialize the improved evidence-based strategy."""
- super().__init__(all_links_of_system)
- self.model = model
- self.search = search
- self.max_iterations = max_iterations
- self.confidence_threshold = confidence_threshold
- self.candidate_limit = candidate_limit
- self.evidence_threshold = evidence_threshold
- self.max_search_iterations = max_search_iterations
- self.questions_per_iteration = questions_per_iteration
- self.min_source_diversity = min_source_diversity
- self.adaptive_query_count = adaptive_query_count
-
- # Initialize components
- self.constraint_analyzer = ConstraintAnalyzer(model)
- self.evidence_evaluator = EvidenceEvaluator(model)
- self.findings_repository = FindingsRepository(model)
-
- # State tracking
- self.constraints: List[Constraint] = []
- self.candidates: List[Candidate] = []
- self.search_history: List[Dict] = []
- self.search_attempts: List[SearchAttempt] = []
- self.failed_queries: Set[str] = set()
- self.successful_patterns: List[Dict[str, Any]] = []
- self.source_types: Dict[str, Set[str]] = defaultdict(set)
- self.iteration: int = 0
-
- def analyze_topic(self, query: str) -> Dict:
- """Analyze a topic using improved evidence-based approach."""
- # Initialize
- self.all_links_of_system.clear()
- self.questions_by_iteration = []
- self.findings = []
- self.iteration = 0
- self.search_attempts.clear()
- self.failed_queries.clear()
- self.successful_patterns.clear()
-
- # Step 1: Extract initial constraints
- if self.progress_callback:
- self.progress_callback(
- "Analyzing query for constraint extraction...",
- 2,
- {"phase": "constraint_analysis", "status": "starting"},
- )
-
- self.constraints = self.constraint_analyzer.extract_constraints(query)
-
- # Step 2: Multi-stage candidate discovery
- self._multi_stage_candidate_discovery()
-
- # Step 3: Main evidence-gathering loop with adaptive search
- while (
- self.iteration < self.max_iterations
- and not self._has_sufficient_answer()
- ):
- self.iteration += 1
-
- if self.progress_callback:
- progress = 15 + int((self.iteration / self.max_iterations) * 70)
- self.progress_callback(
- f"Iteration {self.iteration}/{self.max_iterations} - {self._get_iteration_status()}",
- progress,
- {
- "phase": "iteration_start",
- "iteration": self.iteration,
- "candidates_count": len(self.candidates),
- "search_attempts": len(self.search_attempts),
- "successful_patterns": len(self.successful_patterns),
- },
- )
-
- # Adaptive evidence gathering
- self._adaptive_evidence_gathering()
-
- # Score and prune with diversity consideration
- self._score_with_diversity()
-
- # Adaptive candidate discovery if needed
- if len(self.candidates) < 3 or self._needs_diversity():
- self._adaptive_candidate_search()
-
- # Step 4: Cross-validation and final verification
- self._cross_validate_candidates()
-
- # Step 5: Generate final answer
- return self._synthesize_final_answer(query)
-
- def _multi_stage_candidate_discovery(self):
- """Multi-stage candidate discovery with different strategies."""
- stages = [
- ("distinctive", self._discover_with_distinctive_constraints),
- ("combined", self._discover_with_combined_constraints),
- ("exploratory", self._discover_with_exploratory_search),
- ("pattern_based", self._discover_with_pattern_matching),
- ]
-
- for stage_name, discovery_method in stages:
- if self.progress_callback:
- self.progress_callback(
- f"Stage {stage_name}: Discovering candidates...",
- 5 + stages.index((stage_name, discovery_method)) * 3,
- {"phase": "candidate_discovery", "stage": stage_name},
- )
-
- new_candidates = discovery_method()
-
- # Add unique candidates
- existing_names = {c.name.lower() for c in self.candidates}
- for candidate in new_candidates:
- if candidate.name.lower() not in existing_names:
- self.candidates.append(candidate)
- existing_names.add(candidate.name.lower())
-
- # Stop if we have enough diverse candidates
- if len(self.candidates) >= self.candidate_limit // 2:
- break
-
- def _discover_with_distinctive_constraints(self) -> List[Candidate]:
- """Discover candidates using most distinctive constraints."""
- distinctive = self._get_adaptive_distinctive_constraints()
- candidates = []
-
- for constraint_combo in self._generate_constraint_combinations(
- distinctive, max_size=3
- ):
- query = self._create_adaptive_search_query(constraint_combo)
- if query not in self.failed_queries:
- results = self._execute_tracked_search(
- query, constraint_combo, "distinctive"
- )
- candidates.extend(
- self._extract_candidates_with_context(results, query)
- )
-
- if candidates: # Track successful patterns
- self.successful_patterns.append(
- {
- "constraints": [c.id for c in constraint_combo],
- "query_pattern": query,
- "candidates_found": len(candidates),
- }
- )
-
- return candidates
-
- def _discover_with_combined_constraints(self) -> List[Candidate]:
- """Discover candidates using strategic constraint combinations."""
- # Combine constraints from different types for better results
- type_groups = defaultdict(list)
- for c in self.constraints:
- type_groups[c.type].append(c)
-
- candidates = []
- # Cross-type combinations
- for type1, type2 in itertools.combinations(type_groups.keys(), 2):
- for c1, c2 in itertools.product(
- type_groups[type1][:2], type_groups[type2][:2]
- ):
- query = self._create_cross_constraint_query([c1, c2])
- results = self._execute_tracked_search(
- query, [c1, c2], "combined"
- )
- candidates.extend(
- self._extract_candidates_with_context(results, query)
- )
-
- return candidates
-
- def _discover_with_exploratory_search(self) -> List[Candidate]:
- """Use exploratory searches to find unexpected candidates."""
- candidates = []
-
- # Generate exploratory queries
- exploratory_prompt = f"""
-Based on these constraints, generate 3 exploratory search queries that might find relevant candidates:
-
-Constraints:
-{self._format_constraints_for_prompt(self.constraints[:5])}
-
-Create queries that:
-1. Use alternative phrasings or related concepts
-2. Explore edge cases or unusual combinations
-3. Look for historical or contextual matches
-
-Return only the queries, one per line.
-"""
-
- response = self.model.invoke(exploratory_prompt)
- queries = remove_think_tags(str(response.content)).strip().split("\n")
-
- for query in queries[:3]:
- if query.strip() and query not in self.failed_queries:
- results = self._execute_tracked_search(
- query, self.constraints[:3], "exploratory"
- )
- candidates.extend(
- self._extract_candidates_with_context(results, query)
- )
-
- return candidates
-
- def _discover_with_pattern_matching(self) -> List[Candidate]:
- """Use pattern matching based on successful patterns."""
- if not self.successful_patterns:
- return []
-
- candidates = []
-
- # Adapt successful patterns
- for pattern in self.successful_patterns[:3]:
- constraint_ids = pattern["constraints"]
- constraints = [
- c for c in self.constraints if c.id in constraint_ids
- ]
-
- # Create variations of successful queries
- adapted_query = self._adapt_successful_query(
- pattern["query_pattern"], constraints
- )
- results = self._execute_tracked_search(
- adapted_query, constraints, "pattern_based"
- )
- candidates.extend(
- self._extract_candidates_with_context(results, adapted_query)
- )
-
- return candidates
-
- def _adaptive_evidence_gathering(self):
- """Gather evidence with adaptive query generation."""
- for candidate in self.candidates[:5]:
- unverified = candidate.get_unverified_constraints(self.constraints)
-
- if not unverified:
- continue
-
- # Sort by weight and group by type
- unverified.sort(key=lambda c: c.weight, reverse=True)
- type_groups = defaultdict(list)
- for c in unverified:
- type_groups[c.type].append(c)
-
- # Try different evidence gathering strategies
- for constraints in type_groups.values():
- # Try single constraint
- for c in constraints[:2]:
- query = self._create_evidence_query(candidate, [c])
- results = self._execute_tracked_search(
- query, [c], "evidence"
- )
- evidence = self.evidence_evaluator.extract_evidence(
- results.get("current_knowledge", ""), candidate.name, c
- )
- candidate.add_evidence(c.id, evidence)
-
- # Try combined constraints of same type
- if len(constraints) > 1:
- query = self._create_evidence_query(
- candidate, constraints[:2]
- )
- results = self._execute_tracked_search(
- query, constraints[:2], "evidence_combined"
- )
-
- for c in constraints[:2]:
- evidence = self.evidence_evaluator.extract_evidence(
- results.get("current_knowledge", ""),
- candidate.name,
- c,
- )
- if (
- c.id not in candidate.evidence
- or evidence.confidence
- > candidate.evidence[c.id].confidence
- ):
- candidate.add_evidence(c.id, evidence)
-
- def _create_adaptive_search_query(
- self, constraints: List[Constraint]
- ) -> str:
- """Create adaptive search queries based on past performance."""
- # Check if similar constraint combinations have been successful
- constraint_ids = {c.id for c in constraints}
-
- for pattern in self.successful_patterns:
- if (
- len(constraint_ids.intersection(pattern["constraints"]))
- >= len(constraint_ids) // 2
- ):
- # Adapt successful pattern
- return self._adapt_successful_query(
- pattern["query_pattern"], constraints
- )
-
- # Check failed queries to avoid repetition
- base_query = self._create_base_search_query(constraints)
- if base_query in self.failed_queries:
- # Modify query to avoid failure
- return self._modify_failed_query(base_query, constraints)
-
- return base_query
-
- def _create_cross_constraint_query(
- self, constraints: List[Constraint]
- ) -> str:
- """Create queries that leverage relationships between constraints."""
- prompt = f"""
-Create a search query that finds candidates satisfying BOTH/ALL of these constraints:
-
-{self._format_constraints_for_prompt(constraints)}
-
-The query should:
-1. Find entities that match both/all constraints
-2. Use operators to require both/all conditions
-3. Focus on finding specific names or entities
-
-Return only the search query.
-"""
-
- response = self.model.invoke(prompt)
- return remove_think_tags(str(response.content)).strip()
-
- def _create_evidence_query(
- self, candidate: Candidate, constraints: List[Constraint]
- ) -> str:
- """Create targeted evidence queries."""
- constraint_desc = self._format_constraints_for_prompt(constraints)
-
- prompt = f"""
-Create a search query to verify if "{candidate.name}" satisfies these constraints:
-
-{constraint_desc}
-
-The query should:
-1. Include the candidate name
-2. Target the specific constraint requirements
-3. Find factual evidence, not opinions
-
-Return only the search query.
-"""
-
- response = self.model.invoke(prompt)
- return remove_think_tags(str(response.content)).strip()
-
- def _score_with_diversity(self):
- """Score candidates considering source diversity."""
- for candidate in self.candidates:
- # Base score from evidence
- candidate.calculate_score(self.constraints)
-
- # Diversity bonus
- diversity_score = self._calculate_diversity_score(candidate)
- candidate.score = 0.8 * candidate.score + 0.2 * diversity_score
-
- # Track source types
- for evidence in candidate.evidence.values():
- if hasattr(evidence, "source"):
- self.source_types[candidate.name].add(evidence.source)
-
- # Sort by adjusted score
- self.candidates.sort(key=lambda c: c.score, reverse=True)
-
- # Prune while maintaining some diversity
- self._prune_with_diversity()
-
- def _cross_validate_candidates(self):
- """Cross-validate top candidates using different approaches."""
- if not self.candidates:
- return
-
- top_candidates = self.candidates[:3]
-
- for candidate in top_candidates:
- # Validate using different search engines or approaches
- validation_queries = self._generate_validation_queries(candidate)
-
- for query in validation_queries:
- results = self._execute_tracked_search(
- query, self.constraints, "validation"
- )
-
- # Update evidence if better found
- for constraint in self.constraints:
- evidence = self.evidence_evaluator.extract_evidence(
- results.get("current_knowledge", ""),
- candidate.name,
- constraint,
- )
-
- if (
- constraint.id not in candidate.evidence
- or evidence.confidence
- > candidate.evidence[constraint.id].confidence
- ):
- candidate.add_evidence(constraint.id, evidence)
-
- def _execute_tracked_search(
- self, query: str, constraints: List[Constraint], strategy_type: str
- ) -> Dict:
- """Execute search with tracking for adaptation."""
- results = self._execute_search(query)
-
- # Track the attempt
- candidates_found = len(
- self._extract_candidates_with_context(results, query)
- )
- attempt = SearchAttempt(
- query=query,
- constraint_ids=[c.id for c in constraints],
- results_count=len(results.get("all_links_of_system", [])),
- candidates_found=candidates_found,
- timestamp=datetime.now(UTC).isoformat(),
- strategy_type=strategy_type,
- )
- self.search_attempts.append(attempt)
-
- # Mark as failed if no results
- if candidates_found == 0:
- self.failed_queries.add(query)
-
- return results
-
- def _needs_diversity(self) -> bool:
- """Check if we need more diverse candidates."""
- if len(self.candidates) < 3:
- return True
-
- # Check source diversity
- top_sources = self.source_types.get(self.candidates[0].name, set())
- return len(top_sources) < self.min_source_diversity
-
- def _generate_constraint_combinations(
- self, constraints: List[Constraint], max_size: int = 3
- ) -> List[List[Constraint]]:
- """Generate strategic constraint combinations."""
- combinations = []
-
- # Single constraints
- combinations.extend([[c] for c in constraints])
-
- # Pairs
- for size in range(2, min(len(constraints), max_size) + 1):
- for combo in itertools.combinations(constraints, size):
- combinations.append(list(combo))
-
- return combinations
-
- def _format_constraints_for_prompt(
- self, constraints: List[Constraint]
- ) -> str:
- """Format constraints for LLM prompts."""
- formatted = []
- for c in constraints:
- formatted.append(
- f"- {c.type.value}: {c.description} (weight: {c.weight:.2f})"
- )
- return "\n".join(formatted)
-
- def _adapt_successful_query(
- self, pattern_query: str, constraints: List[Constraint]
- ) -> str:
- """Adapt a successful query pattern with new constraints."""
- prompt = f"""
-Adapt this successful search query pattern with new constraints:
-
-Original query: {pattern_query}
-
-New constraints:
-{self._format_constraints_for_prompt(constraints)}
-
-Create a similar query structure but with the new constraint values.
-Return only the adapted query.
-"""
-
- response = self.model.invoke(prompt)
- return remove_think_tags(str(response.content)).strip()
-
- def _modify_failed_query(
- self, failed_query: str, constraints: List[Constraint]
- ) -> str:
- """Modify a failed query to try a different approach."""
- prompt = f"""
-This search query returned no results: {failed_query}
-
-Constraints we're trying to satisfy:
-{self._format_constraints_for_prompt(constraints)}
-
-Create an alternative query that:
-1. Uses different keywords or phrases
-2. Tries a different search approach
-3. Still targets the same constraints
-
-Return only the modified query.
-"""
-
- response = self.model.invoke(prompt)
- return remove_think_tags(str(response.content)).strip()
-
- def _calculate_diversity_score(self, candidate: Candidate) -> float:
- """Calculate diversity score for a candidate."""
- if not candidate.evidence:
- return 0.0
-
- # Source diversity
- sources = self.source_types.get(candidate.name, set())
- source_score = min(len(sources) / self.min_source_diversity, 1.0)
-
- # Evidence type diversity
- evidence_types = {e.type for e in candidate.evidence.values()}
- type_score = len(evidence_types) / len(EvidenceType)
-
- # Confidence distribution (prefer balanced confidence)
- confidences = [e.confidence for e in candidate.evidence.values()]
- if confidences:
- variance = sum((c - 0.7) ** 2 for c in confidences) / len(
- confidences
- )
- confidence_score = 1.0 / (1.0 + variance)
- else:
- confidence_score = 0.0
-
- return (source_score + type_score + confidence_score) / 3.0
-
- def _prune_with_diversity(self):
- """Prune candidates while maintaining diversity."""
- if len(self.candidates) <= self.candidate_limit:
- return
-
- # Keep top candidates
- kept = self.candidates[: self.candidate_limit // 2]
- remaining = self.candidates[self.candidate_limit // 2 :]
-
- # Add diverse candidates from remaining
- for candidate in remaining:
- if len(kept) >= self.candidate_limit:
- break
-
- # Check if this candidate adds diversity
- if self._adds_diversity(candidate, kept):
- kept.append(candidate)
-
- # Fill remaining slots with highest scoring
- for candidate in remaining:
- if len(kept) >= self.candidate_limit:
- break
- if candidate not in kept:
- kept.append(candidate)
-
- self.candidates = kept
-
- def _adds_diversity(
- self, candidate: Candidate, existing: List[Candidate]
- ) -> bool:
- """Check if a candidate adds diversity to the existing set."""
- # Check source diversity
- candidate_sources = self.source_types.get(candidate.name, set())
- existing_sources = set()
- for c in existing:
- existing_sources.update(self.source_types.get(c.name, set()))
-
- new_sources = candidate_sources - existing_sources
- if new_sources:
- return True
-
- # Check constraint coverage
- candidate_constraints = set(candidate.evidence.keys())
- existing_constraints = set()
- for c in existing:
- existing_constraints.update(c.evidence.keys())
-
- new_constraints = candidate_constraints - existing_constraints
- return len(new_constraints) > 0
-
- def _generate_validation_queries(self, candidate: Candidate) -> List[str]:
- """Generate validation queries for cross-checking."""
- queries = []
-
- # Query combining multiple constraints
- high_weight_constraints = sorted(
- self.constraints, key=lambda c: c.weight, reverse=True
- )[:3]
- combined_query = f'"{candidate.name}" ' + " ".join(
- c.to_search_terms() for c in high_weight_constraints
- )
- queries.append(combined_query)
-
- # Query with alternative phrasing
- alt_prompt = f"""
-Create an alternative search query to validate "{candidate.name}" as the answer.
-Use different keywords but same intent.
-
-Return only the query.
-"""
- response = self.model.invoke(alt_prompt)
- queries.append(remove_think_tags(str(response.content)).strip())
-
- # Source-specific query
- if self.source_types.get(candidate.name):
- source_query = f'"{candidate.name}" site:{list(self.source_types[candidate.name])[0]}'
- queries.append(source_query)
-
- return queries
-
- def _extract_candidates_with_context(
- self, results: Dict, query: str
- ) -> List[Candidate]:
- """Extract candidates with context awareness."""
- # Use the original extraction method but with context
- candidates = self._extract_candidates_from_results(results, query)
-
- # Add context metadata
- for candidate in candidates:
- candidate.metadata["discovery_query"] = query
- candidate.metadata["discovery_stage"] = self.iteration
-
- return candidates
-
- def _create_base_search_query(self, constraints: List[Constraint]) -> str:
- """Create a base search query from constraints."""
- # Use an improved prompt that considers constraint relationships
- prompt = f"""
-Create a search query that finds specific entities satisfying these constraints:
-
-{self._format_constraints_for_prompt(constraints)}
-
-Guidelines:
-1. Focus on finding names/entities, not general information
-2. Use the most distinctive constraints
-3. Combine constraints effectively
-4. Keep the query concise but comprehensive
-
-Return only the search query.
-"""
-
- response = self.model.invoke(prompt)
- return remove_think_tags(str(response.content)).strip()
-
- def _adaptive_candidate_search(self):
- """Adaptively search for more candidates based on current state."""
- # Analyze what types of candidates we're missing
- covered_constraints = set()
- for candidate in self.candidates[:5]:
- covered_constraints.update(candidate.evidence.keys())
-
- uncovered = [
- c for c in self.constraints if c.id not in covered_constraints
- ]
-
- if uncovered:
- # Search specifically for uncovered constraints
- queries = []
- for constraint_group in self._generate_constraint_combinations(
- uncovered[:5], max_size=2
- ):
- query = self._create_adaptive_search_query(constraint_group)
- queries.append((query, constraint_group))
-
- for query, constraints in queries[: self.adaptive_query_count]:
- results = self._execute_tracked_search(
- query, constraints, "adaptive"
- )
- new_candidates = self._extract_candidates_with_context(
- results, query
- )
-
- # Add unique candidates
- existing_names = {c.name.lower() for c in self.candidates}
- for candidate in new_candidates:
- if candidate.name.lower() not in existing_names:
- self.candidates.append(candidate)
- existing_names.add(candidate.name.lower())
-
- def _get_adaptive_distinctive_constraints(self) -> List[Constraint]:
- """Get distinctive constraints with adaptive prioritization."""
- # Start with basic prioritization
- priority_order = [
- ConstraintType.NAME_PATTERN,
- ConstraintType.LOCATION,
- ConstraintType.EVENT,
- ConstraintType.STATISTIC,
- ConstraintType.COMPARISON,
- ConstraintType.PROPERTY,
- ConstraintType.TEMPORAL,
- ConstraintType.EXISTENCE,
- ]
-
- # Adjust based on successful patterns
- if self.successful_patterns:
- # Count successful constraint types
- type_success = defaultdict(int)
- for pattern in self.successful_patterns:
- for constraint_id in pattern["constraints"]:
- constraint = next(
- (c for c in self.constraints if c.id == constraint_id),
- None,
- )
- if constraint:
- type_success[constraint.type] += pattern[
- "candidates_found"
- ]
-
- # Sort by success rate
- priority_order = sorted(
- priority_order,
- key=lambda t: type_success.get(t, 0),
- reverse=True,
- )
-
- # Sort constraints by adjusted priority
- sorted_constraints = sorted(
- self.constraints,
- key=lambda c: (priority_order.index(c.type), -c.weight),
- )
-
- return sorted_constraints[:5]
diff --git a/src/local_deep_research/advanced_search_system/strategies/llm_driven_modular_strategy.py b/src/local_deep_research/advanced_search_system/strategies/llm_driven_modular_strategy.py
deleted file mode 100644
index 74b0f89829..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/llm_driven_modular_strategy.py
+++ /dev/null
@@ -1,821 +0,0 @@
-"""
-LLM-Driven Modular Strategy with intelligent constraint processing and early rejection.
-"""
-
-import asyncio
-import json
-from dataclasses import dataclass
-from typing import Dict, List, Optional, Tuple
-
-from loguru import logger
-
-from ...database.thread_local_session import thread_cleanup
-from ...utilities.json_utils import extract_json
-
-from ..candidate_exploration import AdaptiveExplorer
-from ..constraint_checking import DualConfidenceChecker
-from ..constraints import ConstraintAnalyzer
-from ..questions import StandardQuestionGenerator
-from .base_strategy import BaseSearchStrategy
-
-
-@dataclass
-class CandidateConfidence:
- """Track candidate confidence levels for early rejection"""
-
- candidate: object
- positive_confidence: float
- negative_confidence: float
- rejection_reason: Optional[str] = None
- should_continue: bool = True
-
-
-class LLMConstraintProcessor:
- """LLM-driven intelligent constraint processing"""
-
- def __init__(self, model):
- self.model = model
-
- async def decompose_constraints_intelligently(self, constraints):
- """Let LLM intelligently break down constraints into searchable elements"""
- constraint_text = "\n".join([f"- {c.description}" for c in constraints])
-
- prompt = f"""
- I have these constraints from a search query:
- {constraint_text}
-
- Please intelligently decompose these constraints into atomic, searchable elements that can be combined in different ways.
-
- For each constraint, provide:
- 1. **Atomic elements** - Break it into smallest meaningful parts
- 2. **Variations** - Different ways to express the same concept
- 3. **Granular specifics** - Specific values, years, numbers, etc.
-
- Example for "TV show aired between 1960s and 1980s":
- - Atomic elements: ["TV show", "television", "series", "program"]
- - Time variations: ["1960s", "1970s", "1980s", "60s", "70s", "80s"]
- - Granular years: ["1960", "1961", "1962", "1963", "1964", "1965", "1966", "1967", "1968", "1969", "1970", "1971", "1972", "1973", "1974", "1975", "1976", "1977", "1978", "1979", "1980", "1981", "1982", "1983", "1984", "1985", "1986", "1987", "1988", "1989"]
-
- Example for "fewer than 50 episodes":
- - Atomic elements: ["episodes", "installments", "parts"]
- - Quantity variations: ["under 50", "less than 50", "limited run", "short series"]
- - Granular numbers: ["13 episodes", "26 episodes", "39 episodes", "single season"]
-
- Return as valid JSON format:
- {{
- "constraint_1": {{
- "atomic_elements": [...],
- "variations": [...],
- "granular_specifics": [...]
- }},
- "constraint_2": {{
- "atomic_elements": [...],
- "variations": [...],
- "granular_specifics": [...]
- }}
- }}
- """
-
- response = await self.model.ainvoke(prompt)
- return self._parse_decomposition(response.content)
-
- async def generate_intelligent_combinations(self, decomposed_constraints):
- """LLM generates smart combinations of atomic elements"""
-
- # Flatten all elements for the LLM to see
- all_elements = dict(decomposed_constraints.items())
-
- prompt = f"""
- I have decomposed constraints into these atomic elements:
- {json.dumps(all_elements, indent=2)}
-
- Now intelligently combine these elements to create targeted search queries. Be creative and systematic:
-
- 1. **Year-by-year combinations**: Take specific years and combine with other specifics
- Example: "1960 TV show 13 episodes", "1961 television 26 episodes", etc.
-
- 2. **Cross-constraint combinations**: Mix elements from different constraints
- Example: "humor ascetic 1970s", "fourth wall short series vintage"
-
- 3. **Granular progression**: Create systematic progressions
- Example: "1960 comedy", "1961 comedy", "1962 comedy"...
-
- 4. **Semantic variations**: Same meaning, different words
- Example: "brief TV run 1970s" vs "short television series seventies"
-
- 5. **Contextual combinations**: Add implied context
- Example: "monk-trained character 1978 television"
-
- Generate 60-80 diverse search combinations that would maximize finding the target.
- Focus on being comprehensive yet targeted.
-
- Return as a valid JSON list of search queries:
- ["query1", "query2", "query3"]
- """
-
- response = await self.model.ainvoke(prompt)
- return self._parse_combinations(response.content)
-
- async def generate_creative_search_angles(
- self, original_query, decomposed_constraints
- ):
- """LLM generates completely creative search approaches"""
-
- prompt = f"""
- Original query: "{original_query}"
-
- Now think like a detective - what are ALL the different ways someone might search for this character?
- Be extremely creative and think outside the box:
-
- 1. **Character name guessing**: What names might this character have?
- 2. **Show title guessing**: What might the TV show be called?
- 3. **Cultural context**: What was happening in those decades?
- 4. **Genre searches**: What genre/category would this fit?
- 5. **Indirect searches**: What related topics might lead to this?
- 6. **Reverse searches**: Start from known similar characters
- 7. **Archetype searches**: What type of character is this?
- 8. **Creator/studio searches**: Who might have made this?
-
- Generate 30-40 creative search angles that approach this from completely different directions.
-
- Examples of creative thinking:
- - "1970s cartoon characters who talk to camera"
- - "superhero trained by monks television"
- - "vintage comedy shows cancelled after one season"
- - "fourth wall breaking animation 70s"
- - "spiritual mentor origin story TV characters"
- - "Plastic Man TV show episodes"
- - "elastic superhero television series"
-
- Return as valid JSON list of creative searches:
- ["creative_query1", "creative_query2"]
- """
-
- response = await self.model.ainvoke(prompt)
- return self._parse_creative_searches(response.content)
-
- async def optimize_search_combinations(self, all_combinations):
- """LLM optimizes the search list for maximum effectiveness"""
-
- prompt = f"""
- I have generated {len(all_combinations)} search combinations. Here are the first 20:
- {json.dumps(all_combinations[:20], indent=2)}
-
- Please optimize this search strategy by organizing searches by priority and effectiveness:
-
- 1. **Remove redundant searches** that are too similar
- 2. **Prioritize high-value searches** likely to find results
- 3. **Balance specificity vs breadth**
- 4. **Add missing search angles** you notice
- 5. **Organize by search strategy type**
-
- Return optimized searches organized by category as valid JSON:
- {{
- "high_priority": ["most likely to succeed - top 15 searches"],
- "systematic_granular": ["year-by-year, episode-by-episode combinations - 20 searches"],
- "creative_angles": ["outside-the-box approaches - 15 searches"],
- "contextual_searches": ["time period + cultural context - 15 searches"],
- "fallback_broad": ["broader searches if specifics fail - 10 searches"]
- }}
- """
-
- response = await self.model.ainvoke(prompt)
- return self._parse_optimized_searches(response.content)
-
- def _parse_decomposition(self, content):
- """Parse LLM decomposition response"""
- result = extract_json(content, expected_type=dict)
- if result is not None:
- return result
-
- # Fallback to simple structure
- return {
- "time_constraint": {
- "atomic_elements": ["TV show", "television", "series"],
- "variations": ["1960s", "1970s", "1980s"],
- "granular_specifics": [str(year) for year in range(1960, 1990)],
- }
- }
-
- def _parse_combinations(self, content):
- """Parse LLM combinations response"""
- result = extract_json(content, expected_type=list)
- if result is not None:
- return result
-
- # Fallback
- return [
- "fictional character humor",
- "TV show 1970s",
- "fourth wall breaking",
- ]
-
- def _parse_creative_searches(self, content):
- """Parse LLM creative searches response"""
- result = extract_json(content, expected_type=list)
- if result is not None:
- return result
-
- # Fallback
- return [
- "vintage cartoon character",
- "superhero TV show 1970s",
- "comedy series short run",
- ]
-
- def _parse_optimized_searches(self, content):
- """Parse LLM optimized searches response"""
- result = extract_json(content, expected_type=dict)
- if result is not None:
- return result
-
- # Fallback
- return {
- "high_priority": [
- "fictional character fourth wall humor",
- "1970s TV show limited episodes",
- ],
- "systematic_granular": [
- "1970 TV show",
- "1971 TV show",
- "1972 TV show",
- ],
- "creative_angles": [
- "superhero comedy television",
- "cartoon character talks to audience",
- ],
- "contextual_searches": [
- "vintage TV comedy",
- "classic television humor",
- ],
- "fallback_broad": ["fictional character", "TV show character"],
- }
-
-
-class EarlyRejectionManager:
- """Manages early rejection and confidence tracking"""
-
- def __init__(self, model, positive_threshold=0.6, negative_threshold=0.3):
- self.model = model
- self.positive_threshold = positive_threshold
- self.negative_threshold = negative_threshold
- self.rejected_candidates = set()
-
- async def quick_confidence_check(self, candidate, constraints):
- """Quick confidence assessment for early rejection"""
-
- prompt = f"""
- Quickly assess if this candidate matches the search criteria:
-
- Candidate: {candidate.name}
- Available info: {getattr(candidate, "metadata", {})}
-
- Constraints to match:
- {[c.description for c in constraints]}
-
- Provide:
- 1. **Positive confidence** (0.0-1.0): How likely this candidate matches
- 2. **Negative confidence** (0.0-1.0): How likely this candidate does NOT match
- 3. **Quick reasoning**: Brief explanation
-
- Return as JSON:
- {{
- "positive_confidence": 0.X,
- "negative_confidence": 0.X,
- "reasoning": "brief explanation"
- }}
- """
-
- try:
- response = await self.model.ainvoke(prompt)
- return self._parse_confidence(response.content)
- except Exception:
- logger.exception("Quick confidence check failed")
- return {
- "positive_confidence": 0.5,
- "negative_confidence": 0.3,
- "reasoning": "fallback",
- }
-
- def should_reject_early(self, confidence_result):
- """Determine if candidate should be rejected early"""
- positive = confidence_result.get("positive_confidence", 0.5)
- negative = confidence_result.get("negative_confidence", 0.3)
-
- # Reject if high negative confidence or very low positive confidence
- if negative > 0.7 or positive < 0.1:
- return (
- True,
- f"High negative confidence ({negative:.2f}) or low positive ({positive:.2f})",
- )
-
- return False, None
-
- def should_continue_search(self, all_candidates, high_confidence_count):
- """Determine if we should continue searching"""
- # Stop if we have enough high-confidence candidates
- if high_confidence_count >= 5:
- return False, "Found sufficient high-confidence candidates"
-
- # Stop if we have many candidates but low quality
- if len(all_candidates) > 50 and high_confidence_count == 0:
- return False, "Too many low-quality candidates"
-
- return True, None
-
- def _parse_confidence(self, content):
- """Parse confidence assessment"""
- result = extract_json(content, expected_type=dict)
- if result is not None:
- return result
-
- return {
- "positive_confidence": 0.5,
- "negative_confidence": 0.3,
- "reasoning": "parse_error",
- }
-
-
-class LLMDrivenModularStrategy(BaseSearchStrategy):
- """
- LLM-driven modular strategy with intelligent constraint processing and early rejection.
- """
-
- def __init__(
- self,
- model,
- search,
- all_links_of_system=None,
- constraint_checker_type: str = "dual_confidence",
- exploration_strategy: str = "adaptive",
- early_rejection: bool = True,
- **kwargs,
- ):
- super().__init__(all_links_of_system=all_links_of_system)
-
- self.model = model
- self.search_engine = search
- self.search_engines = getattr(search, "search_engines", [])
-
- # Initialize components
- self.constraint_analyzer = ConstraintAnalyzer(self.model)
- self.llm_processor = LLMConstraintProcessor(self.model)
- self.early_rejection_manager = (
- EarlyRejectionManager(self.model) if early_rejection else None
- )
-
- # Initialize constraint checker
- self.constraint_checker = DualConfidenceChecker(
- model=self.model,
- evidence_gatherer=self._gather_evidence_for_constraint,
- negative_threshold=0.25,
- positive_threshold=0.4,
- uncertainty_penalty=0.2,
- negative_weight=2.0,
- )
-
- # Initialize candidate explorer
- self.candidate_explorer = AdaptiveExplorer(
- search_engine=self.search_engine,
- model=self.model,
- learning_rate=0.1,
- max_search_time=45.0, # Reduced since we have more searches
- max_candidates=30, # Increased since we filter early
- )
-
- # Initialize question generator
- self.question_generator = StandardQuestionGenerator(model=self.model)
-
- # Strategy configuration
- self.constraint_checker_type = constraint_checker_type
- self.exploration_strategy = exploration_strategy
- self.early_rejection = early_rejection
-
- logger.info(
- f"Initialized LLMDrivenModularStrategy with {constraint_checker_type} checker, "
- f"{exploration_strategy} explorer, early_rejection={early_rejection}"
- )
-
- def analyze_topic(self, query: str) -> Dict:
- """Main entry point - sync wrapper for async search"""
- try:
- import asyncio
-
- # Run async search — detect whether we're inside an event loop
- try:
- asyncio.get_running_loop()
- # Inside a running loop — run in a thread to avoid nesting
- import concurrent.futures
-
- with concurrent.futures.ThreadPoolExecutor() as executor:
- future = executor.submit(
- thread_cleanup(lambda: asyncio.run(self.search(query)))
- )
- answer, metadata = future.result()
- except RuntimeError:
- # No running event loop — safe to use asyncio.run() directly
- answer, metadata = asyncio.run(self.search(query))
-
- return {
- "findings": [{"content": answer}],
- "iterations": 1,
- "final_answer": answer,
- "metadata": metadata,
- "links": getattr(self, "all_links_of_system", []),
- "questions_by_iteration": getattr(
- self, "questions_by_iteration", []
- ),
- }
-
- except Exception as e:
- logger.exception("Error in analyze_topic")
- return {
- "findings": [],
- "iterations": 0,
- "final_answer": f"Analysis failed: {e!s}",
- "metadata": {"error": str(e)},
- "links": [],
- "questions_by_iteration": [],
- }
-
- async def search(
- self,
- query: str,
- search_engines: List[str] = None,
- progress_callback=None,
- **kwargs,
- ) -> Tuple[str, Dict]:
- """Execute the LLM-driven modular search strategy"""
- try:
- logger.info(f"Starting LLM-driven modular search for: {query}")
-
- # Phase 1: Extract base constraints
- if progress_callback:
- progress_callback(
- {
- "phase": "constraint_analysis",
- "progress": 5,
- "message": "Analyzing query constraints",
- }
- )
-
- base_constraints = self.constraint_analyzer.extract_constraints(
- query
- )
- logger.info(f"Extracted {len(base_constraints)} base constraints")
-
- # Phase 2: LLM intelligent decomposition
- if progress_callback:
- progress_callback(
- {
- "phase": "llm_decomposition",
- "progress": 15,
- "message": "LLM decomposing constraints intelligently",
- }
- )
-
- decomposed = (
- await self.llm_processor.decompose_constraints_intelligently(
- base_constraints
- )
- )
- logger.info(
- f"LLM decomposed constraints into {len(decomposed)} groups"
- )
-
- # Phase 3: LLM intelligent combinations
- if progress_callback:
- progress_callback(
- {
- "phase": "llm_combinations",
- "progress": 25,
- "message": "LLM generating intelligent search combinations",
- }
- )
-
- intelligent_combinations = (
- await self.llm_processor.generate_intelligent_combinations(
- decomposed
- )
- )
- logger.info(
- f"LLM generated {len(intelligent_combinations)} intelligent combinations"
- )
-
- # Phase 4: LLM creative search angles
- if progress_callback:
- progress_callback(
- {
- "phase": "llm_creative",
- "progress": 35,
- "message": "LLM generating creative search angles",
- }
- )
-
- creative_searches = (
- await self.llm_processor.generate_creative_search_angles(
- query, decomposed
- )
- )
- logger.info(
- f"LLM generated {len(creative_searches)} creative searches"
- )
-
- # Phase 5: LLM optimization
- if progress_callback:
- progress_callback(
- {
- "phase": "llm_optimization",
- "progress": 45,
- "message": "LLM optimizing search strategy",
- }
- )
-
- all_searches = intelligent_combinations + creative_searches
- optimized_searches = (
- await self.llm_processor.optimize_search_combinations(
- all_searches
- )
- )
- total_searches = sum(
- len(searches) for searches in optimized_searches.values()
- )
- logger.info(
- f"LLM optimized to {total_searches} total searches across categories"
- )
-
- # Phase 6: Execute searches by priority with early rejection
- all_candidates = []
- high_confidence_count = 0
- search_progress = 50
-
- for category, searches in optimized_searches.items():
- if not searches:
- continue
-
- logger.info(
- f"Executing {category} searches: {len(searches)} queries"
- )
-
- if progress_callback:
- progress_callback(
- {
- "phase": f"search_{category}",
- "progress": search_progress,
- "message": f"Searching with {category} strategy",
- }
- )
-
- # Execute in parallel batches
- batch_size = 3 if category == "high_priority" else 5
- category_candidates = []
-
- for i in range(0, len(searches), batch_size):
- batch = searches[i : i + batch_size]
-
- # Execute batch searches in parallel
- batch_tasks = []
- for search_query in batch:
- task = self.candidate_explorer._execute_search(
- search_query
- )
- batch_tasks.append(task)
-
- # Wait for batch completion
- batch_results = await asyncio.gather(
- *batch_tasks, return_exceptions=True
- )
-
- # Process batch results
- for j, result in enumerate(batch_results):
- if isinstance(result, Exception):
- logger.error(
- f"Search failed: {batch[j]} - {result}"
- )
- continue
-
- candidates = self.candidate_explorer._extract_candidates_from_results(
- result, entity_type="fictional character"
- )
-
- # Early rejection if enabled
- if self.early_rejection_manager:
- for candidate in candidates:
- confidence = await self.early_rejection_manager.quick_confidence_check(
- candidate, base_constraints
- )
-
- should_reject, reason = (
- self.early_rejection_manager.should_reject_early(
- confidence
- )
- )
- if should_reject:
- logger.debug(
- f"Early rejected {candidate.name}: {reason}"
- )
- continue
-
- if (
- confidence.get("positive_confidence", 0)
- > 0.6
- ):
- high_confidence_count += 1
-
- category_candidates.append(candidate)
- else:
- category_candidates.extend(candidates)
-
- logger.info(
- f"{category} batch {i // batch_size + 1}: found {len(category_candidates)} candidates"
- )
-
- # Early stopping check
- if self.early_rejection_manager:
- should_continue, stop_reason = (
- self.early_rejection_manager.should_continue_search(
- all_candidates + category_candidates,
- high_confidence_count,
- )
- )
- if not should_continue:
- logger.info(f"Early stopping: {stop_reason}")
- break
-
- all_candidates.extend(category_candidates)
- search_progress += 8 # Distribute remaining progress
-
- # Stop if we have enough high-confidence candidates
- if high_confidence_count >= 5:
- logger.info(
- "Found sufficient high-confidence candidates, stopping search"
- )
- break
-
- logger.info(
- f"Search completed: {len(all_candidates)} total candidates, {high_confidence_count} high-confidence"
- )
-
- # Phase 7: Constraint checking on remaining candidates
- if progress_callback:
- progress_callback(
- {
- "phase": "constraint_evaluation",
- "progress": 85,
- "message": f"Evaluating {len(all_candidates)} candidates",
- }
- )
-
- if not all_candidates:
- return "No valid candidates found", {
- "strategy": "llm_driven_modular",
- "total_searches": total_searches,
- "candidates_found": 0,
- "high_confidence_count": 0,
- }
-
- # Evaluate top candidates (limit to avoid long processing)
- candidates_to_evaluate = all_candidates[:20] # Top 20 candidates
- evaluated_candidates = []
-
- for i, candidate in enumerate(candidates_to_evaluate):
- try:
- result = self.constraint_checker.check_candidate(
- candidate, base_constraints
- )
-
- candidate.evaluation_results = result.detailed_results
- candidate.score = result.total_score
- candidate.should_reject = result.should_reject
-
- if not result.should_reject:
- evaluated_candidates.append(candidate)
-
- except Exception:
- logger.exception(
- f"Error evaluating candidate {candidate.name}"
- )
- continue
-
- if not evaluated_candidates:
- return "No valid candidates passed constraint evaluation", {
- "strategy": "llm_driven_modular",
- "total_searches": total_searches,
- "candidates_found": len(all_candidates),
- "candidates_evaluated": len(candidates_to_evaluate),
- "high_confidence_count": high_confidence_count,
- }
-
- # Select best candidate
- evaluated_candidates.sort(key=lambda x: x.score, reverse=True)
- best_candidate = evaluated_candidates[0]
-
- logger.info(
- f"Best candidate: {best_candidate.name} with score {best_candidate.score:.2%}"
- )
-
- # Generate final answer
- if progress_callback:
- progress_callback(
- {
- "phase": "final_answer",
- "progress": 95,
- "message": "Generating final answer",
- }
- )
-
- answer = await self._generate_final_answer(
- query, best_candidate, base_constraints
- )
-
- metadata = {
- "strategy": "llm_driven_modular",
- "constraint_checker": self.constraint_checker_type,
- "exploration_strategy": self.exploration_strategy,
- "early_rejection_enabled": self.early_rejection,
- "total_searches_generated": total_searches,
- "candidates_found": len(all_candidates),
- "candidates_evaluated": len(candidates_to_evaluate),
- "candidates_valid": len(evaluated_candidates),
- "high_confidence_count": high_confidence_count,
- "best_candidate": best_candidate.name,
- "best_score": best_candidate.score,
- }
-
- return answer, metadata
-
- except Exception:
- logger.exception("Error in LLM-driven search")
- return "Search failed", {"error": "Search failed"}
-
- async def _generate_final_answer(self, query, best_candidate, constraints):
- """Generate comprehensive final answer"""
- constraint_info = "\n".join([f"- {c.description}" for c in constraints])
-
- evaluation_info = ""
- if hasattr(best_candidate, "evaluation_results"):
- evaluation_info = "\n".join(
- [
- f"- {result.get('constraint', 'Unknown')}: {result.get('score', 0):.0%}"
- for result in best_candidate.evaluation_results
- ]
- )
-
- prompt = f"""Based on the search results, provide a comprehensive answer to: {query}
-
-Best candidate found: {best_candidate.name}
-Score: {best_candidate.score:.0%}
-
-Constraints analyzed:
-{constraint_info}
-
-Constraint evaluation results:
-{evaluation_info}
-
-Evidence summary: {getattr(best_candidate, "summary", "No summary available")}
-
-Provide a clear, factual answer that addresses the original question and explains how the candidate satisfies the constraints."""
-
- response = await self.model.ainvoke(prompt)
- return response.content
-
- def _gather_evidence_for_constraint(self, candidate, constraint):
- """Gather evidence for a constraint using actual search"""
- try:
- # Create a focused search query
- query = f"{candidate.name} {constraint.description}"
-
- # Use the search engine properly
- if hasattr(self.search_engine, "run"):
- results = self.search_engine.run(query)
- else:
- logger.warning("Search engine doesn't have run method")
- return []
-
- # Handle different result formats
- if isinstance(results, list):
- result_list = results[:3] # Top 3 results
- elif isinstance(results, dict):
- result_list = results.get("results", [])[:3] # Top 3 results
- else:
- logger.warning(f"Unknown search result format: {type(results)}")
- return []
-
- # Extract evidence from search results
- evidence = []
- for result in result_list:
- evidence.append(
- {
- "text": result.get("snippet", "")
- or result.get("content", ""),
- "source": result.get("url", "search_result"),
- "confidence": 0.7,
- "title": result.get("title", ""),
- }
- )
-
- return evidence
-
- except Exception:
- logger.exception("Error gathering evidence")
- return []
diff --git a/tests/advanced_search_system/strategies/test_improved_evidence_high_value.py b/tests/advanced_search_system/strategies/test_improved_evidence_high_value.py
deleted file mode 100644
index 3864c852cc..0000000000
--- a/tests/advanced_search_system/strategies/test_improved_evidence_high_value.py
+++ /dev/null
@@ -1,336 +0,0 @@
-"""High-value tests for ImprovedEvidenceBasedStrategy pure logic methods."""
-
-import pytest
-from unittest.mock import MagicMock, patch
-from collections import defaultdict
-
-from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
-)
-from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
-)
-from local_deep_research.advanced_search_system.evidence.base_evidence import (
- Evidence,
- EvidenceType,
-)
-from local_deep_research.advanced_search_system.strategies.improved_evidence_based_strategy import (
- ImprovedEvidenceBasedStrategy,
- SearchAttempt,
-)
-
-
-def make_constraint(ctype, value, weight=1.0, cid=None):
- return Constraint(
- id=cid or f"c_{value[:8]}",
- type=ctype,
- description=value,
- value=value,
- weight=weight,
- )
-
-
-def make_evidence(
- etype=EvidenceType.DIRECT_STATEMENT, confidence=0.8, source="web"
-):
- ev = MagicMock(spec=Evidence)
- ev.type = etype
- ev.confidence = confidence
- ev.source = source
- return ev
-
-
-def strategy():
- """Create strategy with mocked parent init."""
- with patch.object(
- ImprovedEvidenceBasedStrategy, "__init__", lambda self, *a, **kw: None
- ):
- s = ImprovedEvidenceBasedStrategy.__new__(ImprovedEvidenceBasedStrategy)
- s.model = MagicMock()
- s.search = MagicMock()
- s.all_links_of_system = []
- s.max_iterations = 20
- s.confidence_threshold = 0.85
- s.candidate_limit = 15
- s.evidence_threshold = 0.6
- s.max_search_iterations = 3
- s.questions_per_iteration = 3
- s.min_source_diversity = 3
- s.adaptive_query_count = 3
- s.constraints = []
- s.candidates = []
- s.search_history = []
- s.search_attempts = []
- s.failed_queries = set()
- s.successful_patterns = []
- s.source_types = defaultdict(set)
- s.iteration = 0
- s.progress_callback = None
- return s
-
-
-# --- SearchAttempt dataclass ---
-
-
-class TestSearchAttempt:
- def test_fields(self):
- attempt = SearchAttempt(
- query="test query",
- constraint_ids=["c1", "c2"],
- results_count=5,
- candidates_found=3,
- timestamp="2024-01-01T00:00:00",
- strategy_type="single",
- )
- assert attempt.query == "test query"
- assert attempt.constraint_ids == ["c1", "c2"]
- assert attempt.results_count == 5
- assert attempt.candidates_found == 3
- assert attempt.strategy_type == "single"
-
- def test_strategy_types(self):
- for stype in ["single", "combined", "exploratory"]:
- attempt = SearchAttempt(
- query="q",
- constraint_ids=[],
- results_count=0,
- candidates_found=0,
- timestamp="",
- strategy_type=stype,
- )
- assert attempt.strategy_type == stype
-
-
-# --- _generate_constraint_combinations ---
-
-
-class TestGenerateConstraintCombinations:
- def test_single_constraint(self, strategy):
- c = [make_constraint(ConstraintType.PROPERTY, "A")]
- combos = strategy._generate_constraint_combinations(c, max_size=3)
- assert len(combos) == 1
- assert combos[0] == [c[0]]
-
- def test_two_constraints(self, strategy):
- constraints = [
- make_constraint(ConstraintType.PROPERTY, "A"),
- make_constraint(ConstraintType.PROPERTY, "B"),
- ]
- combos = strategy._generate_constraint_combinations(
- constraints, max_size=3
- )
- # Singles: [A], [B] + Pairs: [A,B] = 3
- assert len(combos) == 3
-
- def test_three_constraints(self, strategy):
- constraints = [
- make_constraint(ConstraintType.PROPERTY, "A"),
- make_constraint(ConstraintType.PROPERTY, "B"),
- make_constraint(ConstraintType.PROPERTY, "C"),
- ]
- combos = strategy._generate_constraint_combinations(
- constraints, max_size=3
- )
- # Singles: 3 + Pairs: 3 + Triples: 1 = 7
- assert len(combos) == 7
-
- def test_max_size_limits(self, strategy):
- constraints = [
- make_constraint(ConstraintType.PROPERTY, "A"),
- make_constraint(ConstraintType.PROPERTY, "B"),
- make_constraint(ConstraintType.PROPERTY, "C"),
- ]
- combos = strategy._generate_constraint_combinations(
- constraints, max_size=2
- )
- # Singles: 3 + Pairs: 3 = 6 (no triples)
- assert len(combos) == 6
- assert all(len(c) <= 2 for c in combos)
-
- def test_empty_constraints(self, strategy):
- combos = strategy._generate_constraint_combinations([], max_size=3)
- assert combos == []
-
-
-# --- _format_constraints_for_prompt ---
-
-
-class TestFormatConstraintsForPrompt:
- def test_single_constraint(self, strategy):
- constraints = [
- make_constraint(ConstraintType.PROPERTY, "scenic view", weight=0.75)
- ]
- result = strategy._format_constraints_for_prompt(constraints)
- assert "property" in result
- assert "scenic view" in result
- assert "0.75" in result
-
- def test_multiple_constraints(self, strategy):
- constraints = [
- make_constraint(ConstraintType.PROPERTY, "scenic", weight=0.5),
- make_constraint(ConstraintType.TEMPORAL, "in 2020", weight=0.8),
- ]
- result = strategy._format_constraints_for_prompt(constraints)
- assert "property" in result
- assert "temporal" in result
- lines = result.strip().split("\n")
- assert len(lines) == 2
-
- def test_empty_constraints(self, strategy):
- result = strategy._format_constraints_for_prompt([])
- assert result == ""
-
-
-# --- _needs_diversity ---
-
-
-class TestNeedsDiversity:
- def test_few_candidates_needs_diversity(self, strategy):
- strategy.candidates = [Candidate(name="A")]
- assert strategy._needs_diversity() is True
-
- def test_three_or_more_with_sources(self, strategy):
- strategy.candidates = [
- Candidate(name="A"),
- Candidate(name="B"),
- Candidate(name="C"),
- ]
- strategy.source_types["A"] = {"s1", "s2", "s3"}
- assert strategy._needs_diversity() is False
-
- def test_three_candidates_few_sources(self, strategy):
- strategy.candidates = [
- Candidate(name="A"),
- Candidate(name="B"),
- Candidate(name="C"),
- ]
- strategy.source_types["A"] = {"s1"}
- assert strategy._needs_diversity() is True
-
- def test_empty_candidates(self, strategy):
- strategy.candidates = []
- assert strategy._needs_diversity() is True
-
-
-# --- _calculate_diversity_score ---
-
-
-class TestCalculateDiversityScore:
- def test_no_evidence(self, strategy):
- c = Candidate(name="Empty")
- assert strategy._calculate_diversity_score(c) == 0.0
-
- def test_single_source_type(self, strategy):
- c = Candidate(name="Test")
- c.evidence = {"c1": make_evidence(EvidenceType.DIRECT_STATEMENT, 0.8)}
- strategy.source_types["Test"] = {"web"}
- score = strategy._calculate_diversity_score(c)
- assert 0.0 < score < 1.0
-
- def test_multiple_sources_higher_score(self, strategy):
- c1 = Candidate(name="Few")
- c1.evidence = {"c1": make_evidence()}
- strategy.source_types["Few"] = {"web"}
-
- c2 = Candidate(name="Many")
- c2.evidence = {
- "c1": make_evidence(EvidenceType.DIRECT_STATEMENT),
- "c2": make_evidence(EvidenceType.NEWS_REPORT),
- }
- strategy.source_types["Many"] = {"web", "academic", "news"}
-
- score1 = strategy._calculate_diversity_score(c1)
- score2 = strategy._calculate_diversity_score(c2)
- assert score2 > score1
-
-
-# --- _adds_diversity ---
-
-
-class TestAddsDiversity:
- def test_new_source_adds_diversity(self, strategy):
- c = Candidate(name="New")
- strategy.source_types["New"] = {"unique_source"}
-
- existing = [Candidate(name="Old")]
- strategy.source_types["Old"] = {"web"}
-
- assert strategy._adds_diversity(c, existing) is True
-
- def test_same_source_no_diversity(self, strategy):
- c = Candidate(name="New")
- c.evidence = {}
- strategy.source_types["New"] = {"web"}
-
- existing = [Candidate(name="Old")]
- existing[0].evidence = {}
- strategy.source_types["Old"] = {"web"}
-
- assert strategy._adds_diversity(c, existing) is False
-
- def test_new_constraint_adds_diversity(self, strategy):
- c = Candidate(name="New")
- c.evidence = {"c_new": make_evidence()}
- strategy.source_types["New"] = set() # Same sources
-
- existing = [Candidate(name="Old")]
- existing[0].evidence = {"c_old": make_evidence()}
- strategy.source_types["Old"] = set()
-
- assert strategy._adds_diversity(c, existing) is True
-
- def test_empty_existing(self, strategy):
- c = Candidate(name="New")
- c.evidence = {}
- strategy.source_types["New"] = set()
- assert strategy._adds_diversity(c, []) is False
-
-
-# --- _prune_with_diversity ---
-
-
-class TestPruneWithDiversity:
- def test_no_pruning_if_under_limit(self, strategy):
- strategy.candidate_limit = 10
- strategy.candidates = [Candidate(name=f"C{i}") for i in range(5)]
- for c in strategy.candidates:
- c.evidence = {}
- strategy._prune_with_diversity()
- assert len(strategy.candidates) == 5
-
- def test_pruning_keeps_limit(self, strategy):
- strategy.candidate_limit = 4
- strategy.candidates = [Candidate(name=f"C{i}") for i in range(10)]
- for c in strategy.candidates:
- c.evidence = {}
- strategy._prune_with_diversity()
- assert len(strategy.candidates) == 4
-
- def test_top_half_kept(self, strategy):
- strategy.candidate_limit = 4
- candidates = [Candidate(name=f"C{i}") for i in range(10)]
- for c in candidates:
- c.evidence = {}
- strategy.candidates = candidates
- strategy._prune_with_diversity()
- # Top half (2) should be kept
- assert strategy.candidates[0].name == "C0"
- assert strategy.candidates[1].name == "C1"
-
- def test_diverse_candidates_preferred(self, strategy):
- strategy.candidate_limit = 3
- c0 = Candidate(name="Top1")
- c0.evidence = {}
- c1 = Candidate(name="Diverse")
- c1.evidence = {"unique_constraint": make_evidence()}
- c2 = Candidate(name="Regular")
- c2.evidence = {}
-
- strategy.candidates = [c0, c1, c2]
- strategy.source_types["Diverse"] = {"unique_source"}
-
- strategy._prune_with_diversity()
- names = [c.name for c in strategy.candidates]
- assert "Diverse" in names
diff --git a/tests/advanced_search_system/strategies/test_improved_evidence_pure_logic.py b/tests/advanced_search_system/strategies/test_improved_evidence_pure_logic.py
deleted file mode 100644
index 9ce777f5eb..0000000000
--- a/tests/advanced_search_system/strategies/test_improved_evidence_pure_logic.py
+++ /dev/null
@@ -1,150 +0,0 @@
-"""
-Pure-logic tests for ImprovedEvidenceBasedStrategy._get_adaptive_distinctive_constraints.
-
-Tests priority ordering based on successful patterns, constraint sorting by
-type priority and weight, and edge cases — no LLM or search calls.
-"""
-
-from unittest.mock import Mock
-
-from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
-)
-from local_deep_research.advanced_search_system.strategies.improved_evidence_based_strategy import (
- ImprovedEvidenceBasedStrategy,
-)
-
-
-def _constraint(cid, ctype, weight=1.0):
- return Constraint(
- id=cid,
- type=ctype,
- description=f"desc_{cid}",
- value=f"val_{cid}",
- weight=weight,
- )
-
-
-def _make_strategy(constraints=None, successful_patterns=None):
- """Build a minimal Mock for ImprovedEvidenceBasedStrategy."""
- s = Mock(spec=[])
- s.constraints = constraints or []
- s.successful_patterns = successful_patterns or []
- return s
-
-
-# ---------------------------------------------------------------------------
-# _get_adaptive_distinctive_constraints
-# ---------------------------------------------------------------------------
-
-
-class TestGetAdaptiveDistinctiveConstraints:
- """Verify adaptive constraint prioritization."""
-
- def test_default_priority_order(self):
- """Without successful patterns, uses default priority order."""
- c_prop = _constraint("c1", ConstraintType.PROPERTY)
- c_name = _constraint("c2", ConstraintType.NAME_PATTERN)
- c_event = _constraint("c3", ConstraintType.EVENT)
- s = _make_strategy(constraints=[c_prop, c_name, c_event])
- result = (
- ImprovedEvidenceBasedStrategy._get_adaptive_distinctive_constraints(
- s
- )
- )
- # NAME_PATTERN has highest default priority, then EVENT, then PROPERTY
- assert result[0].type == ConstraintType.NAME_PATTERN
- assert result[1].type == ConstraintType.EVENT
-
- def test_successful_patterns_reorder_priority(self):
- """Successful patterns boost constraint type priority."""
- c_prop = _constraint("c1", ConstraintType.PROPERTY)
- c_temp = _constraint("c2", ConstraintType.TEMPORAL)
- # Temporal had success
- patterns = [
- {"constraints": ["c2"], "candidates_found": 5},
- ]
- s = _make_strategy(
- constraints=[c_prop, c_temp], successful_patterns=patterns
- )
- result = (
- ImprovedEvidenceBasedStrategy._get_adaptive_distinctive_constraints(
- s
- )
- )
- # TEMPORAL should be boosted above PROPERTY
- assert result[0].type == ConstraintType.TEMPORAL
-
- def test_weight_tiebreak(self):
- """Equal-priority constraints sorted by weight descending."""
- c1 = _constraint("c1", ConstraintType.PROPERTY, weight=0.5)
- c2 = _constraint("c2", ConstraintType.PROPERTY, weight=0.9)
- s = _make_strategy(constraints=[c1, c2])
- result = (
- ImprovedEvidenceBasedStrategy._get_adaptive_distinctive_constraints(
- s
- )
- )
- assert result[0].weight >= result[1].weight
-
- def test_empty_constraints(self):
- """Empty constraints returns empty list."""
- s = _make_strategy(constraints=[])
- result = (
- ImprovedEvidenceBasedStrategy._get_adaptive_distinctive_constraints(
- s
- )
- )
- assert result == []
-
- def test_no_successful_patterns(self):
- """No patterns uses default order."""
- c = _constraint("c1", ConstraintType.EXISTENCE)
- s = _make_strategy(constraints=[c], successful_patterns=[])
- result = (
- ImprovedEvidenceBasedStrategy._get_adaptive_distinctive_constraints(
- s
- )
- )
- assert len(result) == 1
-
- def test_multiple_patterns_accumulate(self):
- """Multiple successful patterns accumulate candidates_found."""
- c_loc = _constraint("c1", ConstraintType.LOCATION)
- c_stat = _constraint("c2", ConstraintType.STATISTIC)
- patterns = [
- {"constraints": ["c1"], "candidates_found": 3},
- {
- "constraints": ["c1"],
- "candidates_found": 2,
- }, # Total: 5 for LOCATION
- {
- "constraints": ["c2"],
- "candidates_found": 4,
- }, # Total: 4 for STATISTIC
- ]
- s = _make_strategy(
- constraints=[c_loc, c_stat], successful_patterns=patterns
- )
- result = (
- ImprovedEvidenceBasedStrategy._get_adaptive_distinctive_constraints(
- s
- )
- )
- # LOCATION (5) should rank above STATISTIC (4)
- assert result[0].type == ConstraintType.LOCATION
-
- def test_unknown_constraint_id_in_pattern_ignored(self):
- """Pattern referencing unknown constraint ID is safely ignored."""
- c = _constraint("c1", ConstraintType.PROPERTY)
- patterns = [
- {"constraints": ["c_nonexistent"], "candidates_found": 10},
- ]
- s = _make_strategy(constraints=[c], successful_patterns=patterns)
- result = (
- ImprovedEvidenceBasedStrategy._get_adaptive_distinctive_constraints(
- s
- )
- )
- assert len(result) == 1
diff --git a/tests/advanced_search_system/strategies/test_llm_driven_modular_high_value.py b/tests/advanced_search_system/strategies/test_llm_driven_modular_high_value.py
deleted file mode 100644
index 58b2fa0477..0000000000
--- a/tests/advanced_search_system/strategies/test_llm_driven_modular_high_value.py
+++ /dev/null
@@ -1,214 +0,0 @@
-"""High-value tests for llm_driven_modular_strategy.py pure logic."""
-
-import unittest
-from unittest.mock import MagicMock
-
-from local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy import (
- CandidateConfidence,
- EarlyRejectionManager,
- LLMConstraintProcessor,
-)
-
-
-class TestCandidateConfidence(unittest.TestCase):
- def test_required_fields(self):
- cc = CandidateConfidence(
- candidate="test", positive_confidence=0.8, negative_confidence=0.2
- )
- assert cc.candidate == "test"
- assert cc.positive_confidence == 0.8
- assert cc.negative_confidence == 0.2
-
- def test_default_should_continue(self):
- cc = CandidateConfidence(
- candidate="x", positive_confidence=0.5, negative_confidence=0.5
- )
- assert cc.should_continue is True
-
- def test_default_rejection_reason(self):
- cc = CandidateConfidence(
- candidate="x", positive_confidence=0.5, negative_confidence=0.5
- )
- assert cc.rejection_reason is None
-
- def test_override_defaults(self):
- cc = CandidateConfidence(
- candidate="x",
- positive_confidence=0.1,
- negative_confidence=0.9,
- should_continue=False,
- rejection_reason="too negative",
- )
- assert cc.should_continue is False
- assert cc.rejection_reason == "too negative"
-
-
-class TestLLMConstraintProcessorParsing(unittest.TestCase):
- def setUp(self):
- self.processor = LLMConstraintProcessor(model=MagicMock())
-
- def test_parse_decomposition_valid_json(self):
- content = '{"c1": {"atomic_elements": ["a"], "variations": ["b"], "granular_specifics": ["c"]}}'
- result = self.processor._parse_decomposition(content)
- assert "c1" in result
- assert result["c1"]["atomic_elements"] == ["a"]
-
- def test_parse_decomposition_invalid_json_fallback(self):
- result = self.processor._parse_decomposition("not json at all")
- assert "time_constraint" in result
- assert "atomic_elements" in result["time_constraint"]
-
- def test_parse_decomposition_with_code_fence(self):
- content = '```json\n{"key": {"atomic_elements": ["x"]}}\n```'
- result = self.processor._parse_decomposition(content)
- assert "key" in result
-
- def test_parse_combinations_valid_list(self):
- content = '["query1", "query2", "query3"]'
- result = self.processor._parse_combinations(content)
- assert result == ["query1", "query2", "query3"]
-
- def test_parse_combinations_invalid_fallback(self):
- result = self.processor._parse_combinations("no json here")
- assert isinstance(result, list)
- assert len(result) > 0
- assert all(isinstance(q, str) for q in result)
-
- def test_parse_creative_searches_valid(self):
- content = '["creative1", "creative2"]'
- result = self.processor._parse_creative_searches(content)
- assert result == ["creative1", "creative2"]
-
- def test_parse_creative_searches_fallback(self):
- result = self.processor._parse_creative_searches("bad")
- assert isinstance(result, list)
- assert len(result) > 0
- assert all(isinstance(q, str) for q in result)
-
- def test_parse_optimized_searches_valid(self):
- content = '{"high_priority": ["q1"], "fallback_broad": ["q2"]}'
- result = self.processor._parse_optimized_searches(content)
- assert "high_priority" in result
-
- def test_parse_optimized_searches_fallback(self):
- result = self.processor._parse_optimized_searches("invalid")
- assert isinstance(result, dict)
- assert "high_priority" in result
- assert "systematic_granular" in result
- assert "creative_angles" in result
- assert "contextual_searches" in result
- assert "fallback_broad" in result
-
-
-class TestEarlyRejectionManagerInit(unittest.TestCase):
- def test_default_thresholds(self):
- mgr = EarlyRejectionManager(model=MagicMock())
- assert mgr.positive_threshold == 0.6
- assert mgr.negative_threshold == 0.3
-
- def test_custom_thresholds(self):
- mgr = EarlyRejectionManager(
- model=MagicMock(), positive_threshold=0.8, negative_threshold=0.1
- )
- assert mgr.positive_threshold == 0.8
- assert mgr.negative_threshold == 0.1
-
- def test_rejected_candidates_empty(self):
- mgr = EarlyRejectionManager(model=MagicMock())
- assert mgr.rejected_candidates == set()
-
-
-class TestShouldRejectEarly(unittest.TestCase):
- def setUp(self):
- self.mgr = EarlyRejectionManager(model=MagicMock())
-
- def test_high_negative_rejects(self):
- reject, reason = self.mgr.should_reject_early(
- {"positive_confidence": 0.5, "negative_confidence": 0.8}
- )
- assert reject is True
-
- def test_very_low_positive_rejects(self):
- reject, reason = self.mgr.should_reject_early(
- {"positive_confidence": 0.05, "negative_confidence": 0.3}
- )
- assert reject is True
-
- def test_boundary_negative_0_7_no_reject(self):
- reject, reason = self.mgr.should_reject_early(
- {"positive_confidence": 0.5, "negative_confidence": 0.7}
- )
- assert reject is False
-
- def test_boundary_positive_0_1_no_reject(self):
- reject, reason = self.mgr.should_reject_early(
- {"positive_confidence": 0.1, "negative_confidence": 0.3}
- )
- assert reject is False
-
- def test_moderate_no_reject(self):
- reject, reason = self.mgr.should_reject_early(
- {"positive_confidence": 0.5, "negative_confidence": 0.5}
- )
- assert reject is False
-
- def test_missing_keys_use_defaults(self):
- reject, reason = self.mgr.should_reject_early({})
- # defaults: positive=0.5, negative=0.3 -> no reject
- assert reject is False
-
-
-class TestShouldContinueSearch(unittest.TestCase):
- def setUp(self):
- self.mgr = EarlyRejectionManager(model=MagicMock())
-
- def test_enough_high_confidence_stops(self):
- cont, reason = self.mgr.should_continue_search(
- all_candidates=list(range(10)), high_confidence_count=5
- )
- assert cont is False
-
- def test_4_high_confidence_continues(self):
- cont, reason = self.mgr.should_continue_search(
- all_candidates=list(range(10)), high_confidence_count=4
- )
- assert cont is True
-
- def test_many_low_quality_stops(self):
- cont, reason = self.mgr.should_continue_search(
- all_candidates=list(range(51)), high_confidence_count=0
- )
- assert cont is False
-
- def test_50_candidates_0_quality_continues(self):
- cont, reason = self.mgr.should_continue_search(
- all_candidates=list(range(50)), high_confidence_count=0
- )
- assert cont is True
-
- def test_normal_continues(self):
- cont, reason = self.mgr.should_continue_search(
- all_candidates=list(range(20)), high_confidence_count=2
- )
- assert cont is True
-
-
-class TestParseConfidence(unittest.TestCase):
- def setUp(self):
- self.mgr = EarlyRejectionManager(model=MagicMock())
-
- def test_valid_json(self):
- content = '{"positive_confidence": 0.8, "negative_confidence": 0.1, "reasoning": "good match"}'
- result = self.mgr._parse_confidence(content)
- assert result["positive_confidence"] == 0.8
- assert result["negative_confidence"] == 0.1
-
- def test_invalid_json_fallback(self):
- result = self.mgr._parse_confidence("not json")
- assert result["positive_confidence"] == 0.5
- assert result["negative_confidence"] == 0.3
- assert result["reasoning"] == "parse_error"
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/tests/strategies/conftest.py b/tests/strategies/conftest.py
index bb19431e76..533025b0ab 100644
--- a/tests/strategies/conftest.py
+++ b/tests/strategies/conftest.py
@@ -280,7 +280,6 @@ STRATEGY_IMPORTS = [
("browsecomp_optimized_strategy", "BrowseCompOptimizedStrategy"),
("evidence_based_strategy_v2", "EnhancedEvidenceBasedStrategy"),
("evidence_based_strategy", "EvidenceBasedStrategy"),
- ("improved_evidence_based_strategy", "ImprovedEvidenceBasedStrategy"),
("constrained_search_strategy", "ConstrainedSearchStrategy"),
("parallel_constrained_strategy", "ParallelConstrainedStrategy"),
("early_stop_constrained_strategy", "EarlyStopConstrainedStrategy"),
@@ -290,11 +289,9 @@ STRATEGY_IMPORTS = [
("concurrent_dual_confidence_strategy", "ConcurrentDualConfidenceStrategy"),
("constraint_parallel_strategy", "ConstraintParallelStrategy"),
("modular_strategy", "ModularStrategy"),
- ("llm_driven_modular_strategy", "LLMDrivenModularStrategy"),
("browsecomp_entity_strategy", "BrowseCompEntityStrategy"),
("topic_organization_strategy", "TopicOrganizationStrategy"),
("iterative_refinement_strategy", "IterativeRefinementStrategy"),
("standard_strategy", "StandardSearchStrategy"),
("langgraph_agent_strategy", "LangGraphAgentStrategy"),
- ("direct_search_strategy", "DirectSearchStrategy"),
]