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 dead entity_aware_source_strategy + clean stale conftest (#3205)

LearningCircuitf4fad9196cad
diff --git a/docs/strategies/deleted/pr-3205-entity-aware.md b/docs/strategies/deleted/pr-3205-entity-aware.md
new file mode 100644
index 0000000000..e7eec82651
--- /dev/null
+++ b/docs/strategies/deleted/pr-3205-entity-aware.md
@@ -0,0 +1,88 @@
+# PR #3205 — delete dead entity-aware strategy + orphaned question generator
+
+Components deleted in PR #3205 (see that PR for the full pre-deletion code —
+this file only summarises what was novel).
+
+Both components were unreachable from `search_system_factory.py` at
+deletion; the question generator had no callers outside the strategy
+class, so removing the strategy orphaned it.
+
+---
+
+## Component: `EntityAwareSourceStrategy`
+
+- File deleted: `src/local_deep_research/advanced_search_system/strategies/entity_aware_source_strategy.py` (139 LOC at deletion).
+- Reachability: not in `search_system_factory.py`; not exported from `strategies/__init__.py`; only referenced by its own pure-logic test and `STRATEGY_IMPORTS`.
+- Closest reachable successor: `BrowseCompEntityStrategy` (`src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py`, factory key `"browsecomp-entity"`) for constraint-driven entity research. For plain-string entity-ID queries, the fallback is `SourceBasedSearchStrategy` with `StandardQuestionGenerator` or `BrowseCompQuestionGenerator`.
+
+### Useful ideas from the pre-deletion version
+
+- **17-keyword entity-query classifier** — the strategy and its question
+ generator both classified a query as entity-seeking if any of `who /
+ what / which / identify / name / character / person / place /
+ organization / company / author / scientist / inventor / city /
+ country / book / movie` appeared in lowercase. High false-positive
+ rate in practice (`who` / `what` / `which` match most research
+ queries), but the list is a starting point if someone builds a proper
+ classifier later.
+- **Naive capitalised-word NER** — `_format_search_results_as_context`
+ treated every capitalised token of length > 2 as a candidate entity
+ with a ±2-word context window. The file's own TODO flagged this as
+ a placeholder. Documented here only so the next person who reaches
+ for this shortcut knows it was tried and found inadequate
+ (matches section headings, sentence-initial words, title-cased junk).
+
+### Why deletion was safe
+
+Zero user-facing path. The strategy added only a question-generator
+swap and the naive NER over its parent `SourceBasedSearchStrategy` —
+no algorithmic novelty. The real prompt engineering lived in the
+question generator (next section).
+
+### Interface gap worth noting
+
+`BrowseCompEntityStrategy` requires pre-built `Constraint` objects.
+`EntityAwareSourceStrategy` was the only (unreachable) path that
+accepted plain-string entity-ID queries. That gap is already unserved
+in production; if it matters, it's a future feature request, not a
+revert.
+
+### Recovery path
+
+Do not restore this 139-LOC wrapper. If plain-string entity-ID queries
+matter, add a helper that extracts `Constraint` objects from a free-form
+query (reuse `ConstraintAnalyzer`) and routes to `BrowseCompEntityStrategy`.
+
+---
+
+## Component: `EntityAwareQuestionGenerator`
+
+- File deleted: `src/local_deep_research/advanced_search_system/questions/entity_aware_question.py` (178 LOC at deletion).
+- Reachability: only consumer was `EntityAwareSourceStrategy`; orphaned once that was removed. Also dropped from `questions/__init__.py`'s `__all__`.
+- Closest reachable successor: `BrowseCompQuestionGenerator` (`src/local_deep_research/advanced_search_system/questions/browsecomp_question.py`). It covers entity-combination queries algorithmically (extract entities, progressively combine 2–3 of them, quote when beneficial) rather than through the explicit prompt templates below.
+
+### Useful ideas from the pre-deletion version
+
+- **Prompt templates teaching multi-constraint quoted searches** —
+ `generate_questions` and `generate_sub_questions` are the only
+ prompts in the codebase that explicitly tell the model to combine
+ multiple identifying constraints into a single quoted search, with
+ a concrete worked example (a fictional 1960s-1980s TV character who
+ breaks the fourth wall). If you need to prompt for entity-ID
+ queries later, start from these rather than re-deriving — they're a
+ reasonable first cut, just never validated.
+- **Liability to avoid on revival** — `generate_questions` returned
+ an empty list whenever the 17-keyword gate didn't match, which
+ halted follow-up research entirely for non-entity queries. Don't
+ reintroduce that fallback.
+
+### Why deletion was safe
+
+Zero remaining consumers after `EntityAwareSourceStrategy` was removed.
+
+### Recovery path
+
+If the prompt engineering proves useful, subclass
+`BrowseCompQuestionGenerator` (or add an optional mode to it) rather
+than restoring a parallel generator class. Drop the empty-list
+fallback if you do.
diff --git a/src/local_deep_research/advanced_search_system/questions/__init__.py b/src/local_deep_research/advanced_search_system/questions/__init__.py
index 1818663f08..89d06b746e 100644
--- a/src/local_deep_research/advanced_search_system/questions/__init__.py
+++ b/src/local_deep_research/advanced_search_system/questions/__init__.py
@@ -4,7 +4,6 @@ from .atomic_fact_question import AtomicFactQuestionGenerator
from .base_question import BaseQuestionGenerator
from .browsecomp_question import BrowseCompQuestionGenerator
from .decomposition_question import DecompositionQuestionGenerator
-from .entity_aware_question import EntityAwareQuestionGenerator
from .news_question import NewsQuestionGenerator
from .standard_question import StandardQuestionGenerator
@@ -13,7 +12,6 @@ __all__ = [
"BaseQuestionGenerator",
"BrowseCompQuestionGenerator",
"DecompositionQuestionGenerator",
- "EntityAwareQuestionGenerator",
"NewsQuestionGenerator",
"StandardQuestionGenerator",
]
diff --git a/src/local_deep_research/advanced_search_system/questions/entity_aware_question.py b/src/local_deep_research/advanced_search_system/questions/entity_aware_question.py
deleted file mode 100644
index f9075c871f..0000000000
--- a/src/local_deep_research/advanced_search_system/questions/entity_aware_question.py
+++ /dev/null
@@ -1,178 +0,0 @@
-"""
-Entity-aware question generation for improved entity identification.
-"""
-
-from datetime import datetime, UTC
-
-from loguru import logger
-
-from .base_question import BaseQuestionGenerator
-
-
-class EntityAwareQuestionGenerator(BaseQuestionGenerator):
- """Question generator that creates more targeted searches for entity identification."""
-
- def generate_questions(
- self,
- current_knowledge: str,
- query: str,
- questions_per_iteration: int = 2,
- questions_by_iteration: dict[int, list[str]] | None = None,
- ) -> list[str]:
- """Generate questions with entity-aware search patterns."""
- now = datetime.now(UTC)
- current_time = now.strftime("%Y-%m-%d")
- questions_by_iteration = questions_by_iteration or {}
-
- logger.info("Generating entity-aware follow-up questions...")
-
- # Detect if this is likely an entity identification query
- entity_keywords = [
- "who",
- "what",
- "which",
- "identify",
- "name",
- "character",
- "person",
- "place",
- "organization",
- "company",
- "author",
- "scientist",
- "inventor",
- "city",
- "country",
- "book",
- "movie",
- ]
-
- is_entity_query = any(
- keyword in query.lower() for keyword in entity_keywords
- )
-
- if is_entity_query:
- # Use more direct entity-focused prompt
- if questions_by_iteration:
- prompt = f"""Generate {questions_per_iteration} targeted search queries to identify the specific entity in the query.
-
-Query: {query}
-Today: {current_time}
-Past questions: {questions_by_iteration!s}
-Current knowledge: {current_knowledge}
-
-Create direct search queries that combine the key identifying features to find the specific name/entity.
-Focus on:
-1. Combining multiple constraints in a single search
-2. Using quotation marks for exact phrases
-3. Including specific details that narrow down results
-
-Format: One question per line, e.g.
-Q: "fictional character" "breaks fourth wall" "TV show" 1960s 1980s
-Q: character name ascetics humor television fewer than 50 episodes
-"""
- else:
- prompt = f"""Generate {questions_per_iteration} direct search queries to identify the specific entity in: {query}
-
-Today: {current_time}
-
-Create search queries that:
-1. Combine multiple identifying features
-2. Target the specific entity name/identification
-3. Use variations of key terms
-
-Format: One question per line, e.g.
-Q: question1
-Q: question2
-"""
- else:
- # Fall back to empty list for non-entity queries
- # (base class method is abstract; subclasses handle their own generation)
- return []
-
- response = self.model.invoke(prompt)
-
- # Handle both string responses and responses with .content attribute
- response_text = ""
- if hasattr(response, "content"):
- response_text = response.content
- else:
- response_text = str(response)
-
- questions = [
- q.replace("Q:", "").strip()
- for q in response_text.split("\n")
- if q.strip().startswith("Q:")
- ][:questions_per_iteration]
-
- logger.info(f"Generated {len(questions)} entity-aware questions")
-
- return questions
-
- def generate_sub_questions(
- self, query: str, context: str = ""
- ) -> list[str]:
- """Generate sub-questions with entity focus when appropriate."""
- # Check if this is an entity identification query
- entity_keywords = [
- "who",
- "what",
- "which",
- "identify",
- "name",
- "character",
- "person",
- "place",
- "organization",
- "company",
- ]
-
- is_entity_query = any(
- keyword in query.lower() for keyword in entity_keywords
- )
-
- if is_entity_query:
- prompt = f"""Break down this entity identification query into targeted sub-questions.
-
-Original Question: {query}
-{context}
-
-Generate 2-5 sub-questions that will help identify the specific entity.
-Focus on:
-1. Combining constraints to narrow down results
-2. Finding the actual name/identity
-3. Verifying the entity matches all criteria
-
-Format your response as:
-1. First sub-question
-2. Second sub-question
-...
-
-Only provide the numbered sub-questions."""
- else:
- return []
-
- try:
- response = self.model.invoke(prompt)
- content = ""
- if hasattr(response, "content"):
- content = response.content
- else:
- content = str(response)
-
- # Extract numbered questions
- questions = []
- for line in content.strip().split("\n"):
- line = line.strip()
- if line and (line[0].isdigit() or line.startswith("-")):
- # Remove the number/bullet and clean up
- question = line.split(".", 1)[-1].strip()
- question = question.lstrip("- ").strip()
- if question:
- questions.append(question)
-
- return questions
-
- except Exception:
- logger.exception("Error generating sub-questions")
- return []
diff --git a/src/local_deep_research/advanced_search_system/strategies/entity_aware_source_strategy.py b/src/local_deep_research/advanced_search_system/strategies/entity_aware_source_strategy.py
deleted file mode 100644
index 19f61bdfdc..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/entity_aware_source_strategy.py
+++ /dev/null
@@ -1,139 +0,0 @@
-"""
-Entity-aware source-based search strategy for improved entity identification.
-"""
-
-from typing import Dict
-
-from loguru import logger
-
-from ..questions.entity_aware_question import EntityAwareQuestionGenerator
-from .source_based_strategy import SourceBasedSearchStrategy
-
-
-class EntityAwareSourceStrategy(SourceBasedSearchStrategy):
- """
- Enhanced source-based strategy that better handles entity identification queries.
-
- This strategy:
- 1. Detects when queries are seeking specific entities (names, places, etc.)
- 2. Generates more targeted search queries for entity identification
- 3. Focuses on extracting entity names from search results
- """
-
- 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,
- use_atomic_facts: bool = False,
- ):
- """Initialize with entity-aware components."""
- # Initialize parent class
- super().__init__(
- search=search,
- model=model,
- citation_handler=citation_handler,
- include_text_content=include_text_content,
- use_cross_engine_filter=use_cross_engine_filter,
- filter_reorder=filter_reorder,
- filter_reindex=filter_reindex,
- cross_engine_max_results=cross_engine_max_results,
- all_links_of_system=all_links_of_system,
- use_atomic_facts=use_atomic_facts,
- )
-
- # Replace the question generator with entity-aware version
- self.question_generator = EntityAwareQuestionGenerator(self.model)
-
- def _format_search_results_as_context(self, search_results):
- """Format search results with emphasis on entity extraction."""
- context_snippets = []
- entity_mentions = []
-
- for i, result in enumerate(search_results):
- title = result.get("title", "Untitled")
- snippet = result.get("snippet", "")
- url = result.get("link", "")
-
- if snippet:
- context_snippets.append(
- f"Source {i + 1}: {title}\nURL: {url}\nSnippet: {snippet}"
- )
-
- # Extract potential entity names (basic approach)
- # In production, this could use NER or more sophisticated extraction
- words = snippet.split()
- for j, word in enumerate(words):
- # Look for capitalized words that might be names
- if word and word[0].isupper() and len(word) > 2:
- # Get some context around the word
- context_start = max(0, j - 2)
- context_end = min(len(words), j + 3)
- entity_context = " ".join(
- words[context_start:context_end]
- )
- if entity_context not in entity_mentions:
- entity_mentions.append(entity_context)
-
- # Add entity mentions to context if found
- if entity_mentions:
- context_snippets.append(
- "\nPotential Entity Mentions:\n"
- + "\n".join(f"- {mention}" for mention in entity_mentions[:10])
- )
-
- return "\n\n".join(context_snippets)
-
- def analyze_topic(self, query: str) -> Dict:
- """Analyze topic with enhanced entity identification."""
- logger.info(
- f"Starting entity-aware source-based research on topic: {query}"
- )
-
- # Detect if this is an entity identification query
- entity_keywords = [
- "who",
- "what",
- "which",
- "identify",
- "name",
- "character",
- "person",
- "place",
- "organization",
- "company",
- "author",
- "scientist",
- "inventor",
- "city",
- "country",
- "book",
- "movie",
- ]
-
- is_entity_query = any(
- keyword in query.lower() for keyword in entity_keywords
- )
-
- if is_entity_query:
- logger.info(
- "Detected entity identification query - using enhanced search patterns"
- )
- self._update_progress(
- "Detected entity identification query - optimizing search strategy",
- 3,
- {
- "phase": "init",
- "query_type": "entity_identification",
- "strategy": "entity_aware_source",
- },
- )
-
- # Use parent's analyze_topic with our enhanced components
- return super().analyze_topic(query)
diff --git a/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py b/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py
index 8b95d0c0d1..cbb718112e 100644
--- a/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py
@@ -54,11 +54,6 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
Previous sections' results are never touched or re-filtered — they persist safely.
The final report's Sources section is generated from this list at report_generator.py:494.
-
- ## Subclasses:
-
- - `EntityAwareSourceStrategy`: overrides `_format_search_results_as_context()` to add
- entity extraction. Does NOT override `analyze_topic()`, so the flow above applies.
"""
def __init__(
@@ -146,8 +141,6 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
The caller controls how many results are passed (typically sliced with
[-question_context_limit:]). This method processes whatever it receives.
-
- Overridden by EntityAwareSourceStrategy to add entity extraction.
"""
context_snippets = []
diff --git a/tests/advanced_search_system/questions/test_entity_aware_question.py b/tests/advanced_search_system/questions/test_entity_aware_question.py
deleted file mode 100644
index 9527e6c563..0000000000
--- a/tests/advanced_search_system/questions/test_entity_aware_question.py
+++ /dev/null
@@ -1,458 +0,0 @@
-"""
-Tests for EntityAwareQuestionGenerator.
-
-Tests cover:
-- Entity detection with various keywords
-- Entity-focused prompt generation with/without past questions
-- Response parsing for Q: prefixed lines
-- Non-entity query fallback to parent class
-- Sub-question generation for entity queries
-- Error handling for exceptions
-"""
-
-from datetime import datetime, UTC
-from unittest.mock import Mock, patch
-
-import pytest
-
-from local_deep_research.advanced_search_system.questions.entity_aware_question import (
- EntityAwareQuestionGenerator,
-)
-
-
-class TestEntityAwareQuestionGeneratorInit:
- """Tests for EntityAwareQuestionGenerator initialization."""
-
- def test_init_stores_model(self):
- """Generator stores the model reference."""
- mock_model = Mock()
- generator = EntityAwareQuestionGenerator(mock_model)
- assert generator.model is mock_model
-
-
-class TestEntityDetection:
- """Tests for entity keyword detection."""
-
- @pytest.fixture
- def mock_model(self):
- """Create mock model."""
- mock = Mock()
- mock.invoke.return_value = Mock(content="Q: query1\nQ: query2")
- return mock
-
- @pytest.fixture
- def generator(self, mock_model):
- """Create generator instance."""
- return EntityAwareQuestionGenerator(mock_model)
-
- def test_detect_who_keyword(self, generator):
- """Detect 'who' as entity keyword."""
- generator.generate_questions("", "Who is the president?", 2)
- # Entity query uses entity-focused prompt, check model was called
- assert generator.model.invoke.called
- call_args = generator.model.invoke.call_args[0][0]
- assert "entity" in call_args.lower() or "identify" in call_args.lower()
-
- def test_detect_what_keyword(self, generator):
- """Detect 'what' as entity keyword."""
- generator.generate_questions("", "What character is this?", 2)
- assert generator.model.invoke.called
-
- def test_detect_which_keyword(self, generator):
- """Detect 'which' as entity keyword."""
- generator.generate_questions("", "Which movie won the award?", 2)
- assert generator.model.invoke.called
-
- def test_detect_identify_keyword(self, generator):
- """Detect 'identify' as entity keyword."""
- generator.generate_questions("", "Identify the person", 2)
- assert generator.model.invoke.called
-
- def test_detect_name_keyword(self, generator):
- """Detect 'name' as entity keyword."""
- generator.generate_questions("", "Name the scientist", 2)
- assert generator.model.invoke.called
-
- def test_detect_character_keyword(self, generator):
- """Detect 'character' as entity keyword."""
- generator.generate_questions("", "The character from TV", 2)
- assert generator.model.invoke.called
-
- def test_detect_person_keyword(self, generator):
- """Detect 'person' as entity keyword."""
- generator.generate_questions("", "The person responsible", 2)
- assert generator.model.invoke.called
-
- def test_detect_company_keyword(self, generator):
- """Detect 'company' as entity keyword."""
- generator.generate_questions("", "The company that made it", 2)
- assert generator.model.invoke.called
-
- def test_detect_author_keyword(self, generator):
- """Detect 'author' as entity keyword."""
- generator.generate_questions("", "The author of the book", 2)
- assert generator.model.invoke.called
-
- def test_case_insensitive_detection(self, generator):
- """Entity detection is case-insensitive."""
- generator.generate_questions("", "WHO is the president?", 2)
- assert generator.model.invoke.called
-
-
-class TestNonEntityQueryFallback:
- """Tests for non-entity query fallback to parent class."""
-
- @pytest.fixture
- def mock_model(self):
- """Create mock model."""
- mock = Mock()
- mock.invoke.return_value = Mock(content="Q: query1\nQ: query2")
- return mock
-
- @pytest.fixture
- def generator(self, mock_model):
- """Create generator instance."""
- return EntityAwareQuestionGenerator(mock_model)
-
- def test_non_entity_query_returns_empty(self, generator):
- """Non-entity query returns empty list without calling the model."""
- result = generator.generate_questions(
- "", "How to learn programming?", 2
- )
- assert result == []
- generator.model.invoke.assert_not_called()
-
- def test_technical_query_uses_parent(self, generator):
- """Technical queries use parent class."""
- with patch.object(
- EntityAwareQuestionGenerator.__bases__[0],
- "generate_questions",
- return_value=["q1", "q2"],
- ):
- generator.generate_questions(
- "", "Explain machine learning algorithms", 2
- )
-
-
-class TestEntityFocusedPromptGeneration:
- """Tests for entity-focused prompt generation."""
-
- @pytest.fixture
- def mock_model(self):
- """Create mock model."""
- mock = Mock()
- mock.invoke.return_value = Mock(content="Q: query1\nQ: query2")
- return mock
-
- @pytest.fixture
- def generator(self, mock_model):
- """Create generator instance."""
- return EntityAwareQuestionGenerator(mock_model)
-
- def test_prompt_includes_query(self, generator):
- """Prompt includes the original query."""
- generator.generate_questions("", "Who is the main character?", 2)
- call_args = generator.model.invoke.call_args[0][0]
- assert "Who is the main character?" in call_args
-
- def test_prompt_includes_current_date(self, generator):
- """Prompt includes current date."""
- generator.generate_questions("", "Who is the president?", 2)
- call_args = generator.model.invoke.call_args[0][0]
- # Should contain date in YYYY-MM-DD format
- today = datetime.now(UTC).strftime("%Y-%m-%d")
- assert today in call_args
-
- def test_prompt_with_past_questions(self, generator):
- """Prompt includes past questions when provided."""
- past = {1: ["Q1", "Q2"], 2: ["Q3"]}
- generator.generate_questions("", "Who is the character?", 2, past)
- call_args = generator.model.invoke.call_args[0][0]
- assert "Past questions:" in call_args
-
- def test_prompt_without_past_questions(self, generator):
- """Prompt format changes when no past questions."""
- generator.generate_questions("", "Who is the inventor?", 2, None)
- call_args = generator.model.invoke.call_args[0][0]
- # Without past questions, uses simpler format
- assert "Past questions:" not in call_args
-
- def test_prompt_includes_current_knowledge(self, generator):
- """Prompt includes current knowledge when with past questions."""
- past = {1: ["Q1"]}
- knowledge = "Some gathered knowledge"
- generator.generate_questions(
- knowledge, "Who is the scientist?", 2, past
- )
- call_args = generator.model.invoke.call_args[0][0]
- assert "Some gathered knowledge" in call_args
-
- def test_questions_per_iteration_in_prompt(self, generator):
- """Prompt requests specific number of questions."""
- generator.generate_questions("", "Who invented it?", 3)
- call_args = generator.model.invoke.call_args[0][0]
- assert "3" in call_args
-
-
-class TestResponseParsing:
- """Tests for parsing LLM responses."""
-
- @pytest.fixture
- def generator(self):
- """Create generator with mock model."""
- mock_model = Mock()
- return EntityAwareQuestionGenerator(mock_model)
-
- def test_parse_q_prefixed_lines(self, generator):
- """Parse lines starting with 'Q:'."""
- generator.model.invoke.return_value = Mock(
- content="Q: First query here\nQ: Second query here\nQ: Third query"
- )
- result = generator.generate_questions("", "Who is it?", 3)
- assert len(result) == 3
- assert "First query here" in result[0]
- assert "Second query here" in result[1]
- assert "Third query" in result[2]
-
- def test_respect_questions_per_iteration(self, generator):
- """Limit results to questions_per_iteration."""
- generator.model.invoke.return_value = Mock(
- content="Q: q1\nQ: q2\nQ: q3\nQ: q4\nQ: q5"
- )
- result = generator.generate_questions("", "Who is it?", 2)
- assert len(result) == 2
-
- def test_skip_non_q_lines(self, generator):
- """Skip lines not starting with 'Q:'."""
- generator.model.invoke.return_value = Mock(
- content="Introduction text\nQ: First query\nMore text\nQ: Second query"
- )
- result = generator.generate_questions("", "Who is it?", 5)
- assert len(result) == 2
-
- def test_handle_content_attribute(self, generator):
- """Handle response with .content attribute."""
- mock_response = Mock()
- mock_response.content = "Q: query1\nQ: query2"
- generator.model.invoke.return_value = mock_response
- result = generator.generate_questions("", "Who is it?", 2)
- assert len(result) == 2
-
- def test_handle_string_response(self, generator):
- """Handle plain string response."""
- generator.model.invoke.return_value = "Q: query1\nQ: query2"
- result = generator.generate_questions("", "Who is it?", 2)
- assert len(result) == 2
-
- def test_strip_q_prefix(self, generator):
- """Strip 'Q:' prefix from results."""
- generator.model.invoke.return_value = Mock(
- content="Q: simple query here"
- )
- result = generator.generate_questions("", "Who is it?", 1)
- assert result[0] == "simple query here"
-
- def test_strip_whitespace(self, generator):
- """Strip whitespace from parsed queries."""
- generator.model.invoke.return_value = Mock(
- content="Q: query with spaces \nQ: another query "
- )
- result = generator.generate_questions("", "Who is it?", 2)
- assert result[0] == "query with spaces"
- assert result[1] == "another query"
-
-
-class TestGenerateSubQuestions:
- """Tests for generate_sub_questions method."""
-
- @pytest.fixture
- def generator(self):
- """Create generator with mock model."""
- mock_model = Mock()
- return EntityAwareQuestionGenerator(mock_model)
-
- def test_entity_query_sub_questions(self, generator):
- """Generate sub-questions for entity queries."""
- generator.model.invoke.return_value = Mock(
- content="1. First sub-question\n2. Second sub-question\n3. Third sub-question"
- )
- result = generator.generate_sub_questions("Who invented the telephone?")
- assert len(result) == 3
-
- def test_parse_numbered_format(self, generator):
- """Parse numbered list format."""
- generator.model.invoke.return_value = Mock(
- content="1. Question one here\n2. Question two here"
- )
- result = generator.generate_sub_questions("Which movie is this?")
- assert "Question one here" in result[0]
- assert "Question two here" in result[1]
-
- def test_parse_bulleted_format(self, generator):
- """Parse bulleted list format."""
- generator.model.invoke.return_value = Mock(
- content="- First question\n- Second question"
- )
- result = generator.generate_sub_questions("Who wrote this book?")
- assert len(result) == 2
-
- def test_context_included_in_prompt(self, generator):
- """Context is included in prompt."""
- generator.model.invoke.return_value = Mock(content="1. Q1\n2. Q2")
- generator.generate_sub_questions(
- "Who is the character?",
- context="Previous findings about the character",
- )
- call_args = generator.model.invoke.call_args[0][0]
- assert "Previous findings about the character" in call_args
-
- def test_non_entity_raises_or_returns_empty(self, generator):
- """Non-entity query attempts parent call (may fail without implementation)."""
- # The base class doesn't have generate_sub_questions, so this tests
- # that the code path is attempted for non-entity queries
- try:
- result = generator.generate_sub_questions(
- "How does machine learning work?"
- )
- # If it doesn't raise, should return empty or valid list
- assert isinstance(result, list)
- except AttributeError:
- # Expected if parent class doesn't implement generate_sub_questions
- pass
-
- def test_handle_content_attribute(self, generator):
- """Handle response with .content attribute."""
- mock_response = Mock()
- mock_response.content = "1. Sub Q1\n2. Sub Q2"
- generator.model.invoke.return_value = mock_response
- result = generator.generate_sub_questions("Who is the scientist?")
- assert len(result) == 2
-
- def test_handle_string_response(self, generator):
- """Handle plain string response."""
- generator.model.invoke.return_value = "1. Sub Q1\n2. Sub Q2"
- result = generator.generate_sub_questions("Who is the author?")
- assert len(result) == 2
-
-
-class TestErrorHandling:
- """Tests for error handling."""
-
- @pytest.fixture
- def generator(self):
- """Create generator with mock model."""
- mock_model = Mock()
- return EntityAwareQuestionGenerator(mock_model)
-
- def test_sub_questions_exception_returns_empty(self, generator):
- """Exception in generate_sub_questions returns empty list."""
- generator.model.invoke.side_effect = RuntimeError("Connection failed")
- result = generator.generate_sub_questions("Who is the inventor?")
- assert result == []
-
- def test_sub_questions_logs_exception(self, generator, caplog):
- """Exception is logged in generate_sub_questions."""
- generator.model.invoke.side_effect = ValueError("Invalid input")
- result = generator.generate_sub_questions("Who is the character?")
- # Exception should be logged
- assert result == []
-
-
-class TestEdgeCases:
- """Tests for edge cases."""
-
- @pytest.fixture
- def generator(self):
- """Create generator with mock model."""
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Q: query")
- return EntityAwareQuestionGenerator(mock_model)
-
- def test_empty_response(self, generator):
- """Handle empty LLM response."""
- generator.model.invoke.return_value = Mock(content="")
- result = generator.generate_questions("", "Who is it?", 2)
- assert result == []
-
- def test_no_valid_q_lines(self, generator):
- """Handle response with no valid Q: lines."""
- generator.model.invoke.return_value = Mock(
- content="Some text\nMore text\nNo Q lines"
- )
- result = generator.generate_questions("", "Who is it?", 2)
- assert result == []
-
- def test_empty_query(self, generator):
- """Handle empty query string."""
- generator.generate_questions("", "", 2)
- # Empty query has no entity keywords, should fall back to parent
- # Just verify it doesn't crash
-
- def test_questions_by_iteration_none(self, generator):
- """Handle questions_by_iteration as None."""
- result = generator.generate_questions("", "Who is it?", 2, None)
- assert isinstance(result, list)
-
- def test_questions_by_iteration_empty(self, generator):
- """Handle questions_by_iteration as empty dict."""
- result = generator.generate_questions("", "Who is it?", 2, {})
- assert isinstance(result, list)
- # Empty dict is falsy, so uses simpler prompt format
-
- def test_sub_questions_empty_content(self, generator):
- """Handle empty content in sub-questions."""
- generator.model.invoke.return_value = Mock(content="")
- result = generator.generate_sub_questions("Who is the inventor?")
- assert result == []
-
- def test_sub_questions_no_numbered_lines(self, generator):
- """Handle response with no numbered lines."""
- generator.model.invoke.return_value = Mock(
- content="Some text without numbers"
- )
- result = generator.generate_sub_questions("Who is the character?")
- assert result == []
-
-
-class TestIntegration:
- """Integration tests."""
-
- @pytest.fixture
- def mock_model(self):
- """Create mock model with realistic responses."""
- mock = Mock()
- mock.invoke.return_value = Mock(
- content="""Q: "fictional character" "fourth wall" TV show
-Q: character name sitcom breaks fourth wall
-Q: TV character speaks to audience directly"""
- )
- return mock
-
- @pytest.fixture
- def generator(self, mock_model):
- """Create generator instance."""
- return EntityAwareQuestionGenerator(mock_model)
-
- def test_full_workflow_entity_query(self, generator):
- """Test complete workflow with entity query."""
- result = generator.generate_questions(
- "Some knowledge about characters",
- "What fictional character breaks the fourth wall?",
- 3,
- {1: ["Previous question"]},
- )
- assert isinstance(result, list)
- assert len(result) == 3
- assert all(isinstance(q, str) for q in result)
-
- def test_full_workflow_sub_questions(self, generator):
- """Test complete workflow for sub-questions."""
- generator.model.invoke.return_value = Mock(
- content="1. Who created this character?\n2. What show features this character?\n3. When did the show air?"
- )
- result = generator.generate_sub_questions(
- "Which character breaks the fourth wall?",
- context="Looking for a TV character",
- )
- assert isinstance(result, list)
- assert len(result) == 3
diff --git a/tests/advanced_search_system/strategies/test_entity_aware_pure_logic.py b/tests/advanced_search_system/strategies/test_entity_aware_pure_logic.py
deleted file mode 100644
index 97706185b0..0000000000
--- a/tests/advanced_search_system/strategies/test_entity_aware_pure_logic.py
+++ /dev/null
@@ -1,176 +0,0 @@
-"""
-Pure-logic tests for EntityAwareSourceStrategy._format_search_results_as_context.
-
-Tests entity extraction (capitalized words), context window, deduplication,
-empty input, and potential-entity-mentions cap — no LLM or search calls.
-"""
-
-from unittest.mock import Mock
-
-from local_deep_research.advanced_search_system.strategies.entity_aware_source_strategy import (
- EntityAwareSourceStrategy,
-)
-
-
-def _make_strategy():
- """Build a minimal Mock with attributes used by _format_search_results_as_context."""
- s = Mock(spec=[])
- return s
-
-
-# ---------------------------------------------------------------------------
-# _format_search_results_as_context
-# ---------------------------------------------------------------------------
-
-
-class TestFormatSearchResultsAsContext:
- """Verify entity extraction and context formatting."""
-
- def test_empty_results(self):
- """Empty results list returns empty string."""
- s = _make_strategy()
- result = EntityAwareSourceStrategy._format_search_results_as_context(
- s, []
- )
- assert result == ""
-
- def test_single_result_with_snippet(self):
- """Single result formats title, URL, and snippet."""
- s = _make_strategy()
- results = [
- {
- "title": "About Mountains",
- "snippet": "Mount Rainier is a volcano",
- "link": "https://example.com",
- }
- ]
- result = EntityAwareSourceStrategy._format_search_results_as_context(
- s, results
- )
- assert "About Mountains" in result
- assert "https://example.com" in result
- assert "Mount Rainier is a volcano" in result
-
- def test_extracts_capitalized_entities(self):
- """Capitalized words > 2 chars are extracted as entity mentions."""
- s = _make_strategy()
- results = [
- {
- "title": "Test",
- "snippet": "Alice visited Paris last summer",
- "link": "",
- }
- ]
- result = EntityAwareSourceStrategy._format_search_results_as_context(
- s, results
- )
- assert "Potential Entity Mentions" in result
- # "Alice" and "Paris" are capitalized and > 2 chars
- assert "Alice" in result
- assert "Paris" in result
-
- def test_short_capitalized_words_excluded(self):
- """Capitalized words <= 2 chars are not extracted as entities."""
- s = _make_strategy()
- results = [
- {
- "title": "Test",
- "snippet": "Al is here An ox",
- "link": "",
- }
- ]
- result = EntityAwareSourceStrategy._format_search_results_as_context(
- s, results
- )
- # "Al" and "An" are <= 2 chars, should not be in entity mentions
- if "Potential Entity Mentions" in result:
- # Check they're not listed as entities (they may appear in the snippet)
- entity_section = result.split("Potential Entity Mentions")[1]
- assert "- Al " not in entity_section
- assert "- An " not in entity_section
-
- def test_entity_mentions_capped_at_ten(self):
- """At most 10 entity mentions are included."""
- s = _make_strategy()
- # Create a snippet with many capitalized words
- words = [f"Entity{i}" for i in range(20)]
- snippet = " ".join(words)
- results = [{"title": "Test", "snippet": snippet, "link": ""}]
- result = EntityAwareSourceStrategy._format_search_results_as_context(
- s, results
- )
- entity_section = result.split("Potential Entity Mentions")[1]
- # Count the "- " list items
- mentions = [
- line for line in entity_section.split("\n") if line.startswith("- ")
- ]
- assert len(mentions) <= 10
-
- def test_no_snippet_excluded(self):
- """Results without snippets are excluded from context."""
- s = _make_strategy()
- results = [{"title": "No Snippet", "snippet": "", "link": ""}]
- result = EntityAwareSourceStrategy._format_search_results_as_context(
- s, results
- )
- assert "Source 1" not in result
-
- def test_no_entity_mentions_section_when_none_found(self):
- """No entity mentions section when no capitalized words found."""
- s = _make_strategy()
- results = [
- {
- "title": "Test",
- "snippet": "all lowercase words here",
- "link": "",
- }
- ]
- result = EntityAwareSourceStrategy._format_search_results_as_context(
- s, results
- )
- assert "Potential Entity Mentions" not in result
-
- def test_deduplication_of_entity_contexts(self):
- """Duplicate entity contexts are not repeated."""
- s = _make_strategy()
- results = [
- {
- "title": "Test",
- "snippet": "Alice walked. Alice walked again",
- "link": "",
- }
- ]
- result = EntityAwareSourceStrategy._format_search_results_as_context(
- s, results
- )
- if "Potential Entity Mentions" in result:
- entity_section = result.split("Potential Entity Mentions")[1]
- mentions = [
- line.strip()
- for line in entity_section.split("\n")
- if line.startswith("- ")
- ]
- # Should have unique mentions only
- assert len(mentions) == len(set(mentions))
-
- def test_multiple_results(self):
- """Multiple results each get a Source N header."""
- s = _make_strategy()
- results = [
- {"title": "First", "snippet": "content one", "link": "url1"},
- {"title": "Second", "snippet": "content two", "link": "url2"},
- ]
- result = EntityAwareSourceStrategy._format_search_results_as_context(
- s, results
- )
- assert "Source 1" in result
- assert "Source 2" in result
-
- def test_missing_title_uses_untitled(self):
- """Missing title defaults to 'Untitled'."""
- s = _make_strategy()
- results = [{"snippet": "some content", "link": "url"}]
- result = EntityAwareSourceStrategy._format_search_results_as_context(
- s, results
- )
- assert "Untitled" in result
diff --git a/tests/strategies/conftest.py b/tests/strategies/conftest.py
index 194be05519..bb19431e76 100644
--- a/tests/strategies/conftest.py
+++ b/tests/strategies/conftest.py
@@ -297,5 +297,4 @@ STRATEGY_IMPORTS = [
("standard_strategy", "StandardSearchStrategy"),
("langgraph_agent_strategy", "LangGraphAgentStrategy"),
("direct_search_strategy", "DirectSearchStrategy"),
- ("entity_aware_source_strategy", "EntityAwareSourceStrategy"),
]