~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
refactor(strategies): add base error-response and citation helpers (DRY) (#4711)
LearningCircuit60e35f88a3cd
diff --git a/src/local_deep_research/advanced_search_system/strategies/base_strategy.py b/src/local_deep_research/advanced_search_system/strategies/base_strategy.pyindex 3856755736..8a2f7cb9b8 100644--- a/src/local_deep_research/advanced_search_system/strategies/base_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/base_strategy.py@@ -243,6 +243,52 @@ class BaseSearchStrategy(ABC):},)+ def _create_error_response(self, error: str) -> dict[str, Any]:+ """Build a standardized error result.++ Shared by ``mcp_strategy`` and ``focused_iteration_strategy``.+ Both ``questions`` and ``questions_by_iteration`` keys are+ included because the two consumers read different keys+ historically — keeping both avoids breaking either caller.+ """+ return {+ "findings": [],+ "iterations": 0,+ "questions": {},+ "questions_by_iteration": {},+ "formatted_findings": f"Error: {error}",+ "current_knowledge": "",+ "error": error,+ }++ def _format_citations(+ self, content: str, search_results: list[dict[str, Any]]+ ) -> str:+ """Append a Markdown ``## Sources`` bibliography to ``content``.++ Shared by ``mcp_strategy`` (uses ``self.all_search_results``)+ and ``langgraph_agent_strategy`` (uses ``self.collector.results``).+ Returns ``content`` unchanged when no links can be extracted.+ """+ if not search_results:+ return content+ try:+ from ...utilities.search_utilities import (+ extract_links_from_search_results,+ format_links_to_markdown,+ )++ all_links = extract_links_from_search_results(search_results)+ if not all_links:+ return content+ sources_markdown = format_links_to_markdown(all_links)+ if not sources_markdown:+ return content+ return f"{content}\n\n## Sources\n\n{sources_markdown}"+ except Exception:+ logger.exception("Failed to format source links")+ return content+def _emit_searching_progress(self,iteration: int,diff --git a/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py b/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.pyindex ddd608496e..82466d87ae 100644--- a/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py@@ -462,12 +462,9 @@ class FocusedIterationStrategy(BaseSearchStrategy):return Falsedef _create_error_response(self, error_msg: str) -> Dict:- """Create standardized error response."""- return {- "findings": [],- "iterations": 0,- "questions_by_iteration": {},- "formatted_findings": f"Error: {error_msg}",- "current_knowledge": "",- "error": error_msg,- }+ """Create standardized error response (delegates to base).++ The base method includes both ``questions`` and+ ``questions_by_iteration`` keys to satisfy all consumers.+ """+ return super()._create_error_response(error_msg)diff --git a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.pyindex 7bcbdf5114..afd08bd68b 100644--- a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py@@ -20,10 +20,6 @@ from langgraph.errors import GraphRecursionErrorfrom loguru import loggerfrom ...citation_handler import CitationHandler-from ...utilities.search_utilities import (- extract_links_from_search_results,- format_links_to_markdown,-)from ..tools.fetch import FETCH_MODES, build_fetch_toolfrom .base_strategy import BaseSearchStrategyfrom ...constants import DEFAULT_SEARCH_TOOL@@ -1177,19 +1173,10 @@ class LangGraphAgentStrategy(BaseSearchStrategy):"Citation handler failed, using raw agent answer")- # Format sources- formatted_output = synthesized_content- if all_search_results:- try:- all_links = extract_links_from_search_results(- all_search_results- )- if all_links:- sources_md = format_links_to_markdown(all_links)- if sources_md:- formatted_output = f"{synthesized_content}\n\n## Sources\n\n{sources_md}"- except Exception:- logger.exception("Failed to format source links")+ # Format sources — delegate to base helper+ formatted_output = self._format_citations(+ synthesized_content, all_search_results+ )# Build reasoning trace from agent messagesreasoning_trace = []diff --git a/src/local_deep_research/advanced_search_system/strategies/mcp_strategy.py b/src/local_deep_research/advanced_search_system/strategies/mcp_strategy.pyindex 1a1e0e89f9..a8a04ececc 100644--- a/src/local_deep_research/advanced_search_system/strategies/mcp_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/mcp_strategy.py@@ -19,10 +19,6 @@ from loguru import loggerfrom ...citation_handler import CitationHandlerfrom ...utilities.json_utils import extract_json-from ...utilities.search_utilities import (- extract_links_from_search_results,- format_links_to_markdown,-)from .base_strategy import BaseSearchStrategyfrom ...constants import DEFAULT_SEARCH_TOOL@@ -465,40 +461,15 @@ class MCPSearchStrategy(BaseSearchStrategy):synthesized_content = final_answer# Format sources as markdown bibliography and append to output- formatted_output = synthesized_contentlogger.info(f"MCP Strategy: all_search_results has {len(self.all_search_results)} items")- if self.all_search_results:- try:- all_links = extract_links_from_search_results(- self.all_search_results- )- logger.info(- f"MCP Strategy: extracted {len(all_links)} links from search results"- )- if all_links:- sources_markdown = format_links_to_markdown(all_links)- logger.info(- f"MCP Strategy: sources_markdown length={len(sources_markdown) if sources_markdown else 0}"- )- if sources_markdown:- formatted_output = f"{synthesized_content}\n\n## Sources\n\n{sources_markdown}"- logger.info(- f"MCP Strategy: Appended {len(all_links)} sources to output"- )- else:- logger.warning(- "MCP Strategy: sources_markdown is empty despite having links"- )- else:- logger.warning(- "MCP Strategy: No links extracted from search results"- )- except Exception:- logger.exception("MCP Strategy: Failed to format source links")- else:+ if not self.all_search_results:logger.warning("MCP Strategy: all_search_results is empty")+ # Delegate to base helper; logs only on failure+ formatted_output = self._format_citations(+ synthesized_content, self.all_search_results+ )# Add final finding WITH search_results for research_service.py to extract# This is critical for sources to be saved to database and displayed@@ -1863,14 +1834,3 @@ If some information is missing, note what couldn't be found."""except Exception as e:logger.exception("Failed to synthesize answer")return f"Research completed but synthesis failed: {e}"-- def _create_error_response(self, error: str) -> Dict:- """Create an error response."""- return {- "findings": [],- "iterations": 0,- "questions": {},- "formatted_findings": f"Error: {error}",- "current_knowledge": "",- "error": error,- }diff --git a/tests/advanced_search_system/strategies/test_focused_iteration_high_value.py b/tests/advanced_search_system/strategies/test_focused_iteration_high_value.pyindex afd40866cc..3096f249bb 100644--- a/tests/advanced_search_system/strategies/test_focused_iteration_high_value.py+++ b/tests/advanced_search_system/strategies/test_focused_iteration_high_value.py@@ -205,9 +205,15 @@ class TestCreateErrorResponse:def test_error_response_has_required_keys(self):strategy = _make_strategy()resp = strategy._create_error_response("something broke")+ # The shared base _create_error_response carries BOTH "questions"+ # and "questions_by_iteration" so a single helper satisfies every+ # consumer (mcp_strategy reads "questions", focused reads+ # "questions_by_iteration"). The focused error response therefore+ # now includes both keys.assert set(resp.keys()) == {"findings","iterations",+ "questions","questions_by_iteration","formatted_findings","current_knowledge",@@ -219,6 +225,7 @@ class TestCreateErrorResponse:resp = strategy._create_error_response("timeout")assert resp["findings"] == []assert resp["iterations"] == 0+ assert resp["questions"] == {}assert resp["questions_by_iteration"] == {}assert resp["current_knowledge"] == ""assert resp["error"] == "timeout"