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(strategies): centralize the content-or-response predicate in first_usable_text (#6953)

LearningCircuit12d9a11819ba
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.py
index f97c1beeb6..860240f56f 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
@@ -90,6 +90,30 @@ class BaseSearchStrategy(ABC):
return unwrap_setting(self.settings_snapshot[key])
return default
+ @staticmethod
+ def first_usable_text(
+ citation_result: dict[str, Any], default: str | None = None
+ ) -> str | None:
+ """Return the first usable text field of a citation result.
+
+ Centralizes the assembly predicate the strategy sites share: a
+ candidate from ``content`` / ``response`` counts only when it is a
+ non-empty, non-whitespace ``str`` (think-only model replies
+ stringify to ``""``), so a blank one cannot hide a valid sibling
+ field. Returns ``default`` when neither field is usable (#6941).
+ """
+ return next(
+ (
+ candidate
+ for candidate in (
+ citation_result.get("content"),
+ citation_result.get("response"),
+ )
+ if isinstance(candidate, str) and candidate.strip()
+ ),
+ default,
+ )
+
def set_progress_callback(
self, callback: Callable[[str, int | None, dict[str, Any]], None]
) -> None:
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.py
index 742b18c1b4..d5daa2ea22 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
@@ -385,16 +385,8 @@ class FocusedIterationStrategy(BaseSearchStrategy):
)
if final_result:
- synthesized_content = next(
- (
- candidate
- for candidate in (
- final_result.get("content"),
- final_result.get("response"),
- )
- if isinstance(candidate, str) and candidate.strip()
- ),
- "No relevant results found.",
+ synthesized_content = self.first_usable_text(
+ final_result, "No relevant results found."
)
documents = final_result.get("documents", [])
elif citation_failed:
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.py
index ebd4b2fc42..75218e10ee 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
@@ -3304,14 +3304,12 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
or "response" in citation_result
):
# Prefer the first usable text field. Empty, whitespace,
- # or malformed content must not hide a valid response.
- for candidate in (
- citation_result.get("content"),
- citation_result.get("response"),
- ):
- if isinstance(candidate, str) and candidate.strip():
- synthesized_content = candidate
- break
+ # or malformed content must not hide a valid response
+ # (the base-class predicate the sibling strategies use,
+ # centralized as first_usable_text — #6941).
+ usable = self.first_usable_text(citation_result)
+ if usable is not None:
+ synthesized_content = usable
else:
raw_fallback_markers = CITATION_MARKER_RE.findall(
final_answer or ""
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 f6c0dcc19b..f89deff45a 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
@@ -555,15 +555,8 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
# Null check — synthesis can fail on empty/malformed results
if final_citation_result:
- synthesized_content = next(
- (
- candidate
- for candidate in (
- final_citation_result.get("content"),
- final_citation_result.get("response"),
- )
- if isinstance(candidate, str) and candidate.strip()
- ),
+ synthesized_content = self.first_usable_text(
+ final_citation_result,
"No relevant results found in final synthesis.",
)
documents = final_citation_result.get("documents", [])
diff --git a/tests/advanced_search_system/strategies/test_base_strategy.py b/tests/advanced_search_system/strategies/test_base_strategy.py
index a92f3744c9..672e6f64fa 100644
--- a/tests/advanced_search_system/strategies/test_base_strategy.py
+++ b/tests/advanced_search_system/strategies/test_base_strategy.py
@@ -10,6 +10,7 @@ Tests cover:
"""
import pytest
+from types import MappingProxyType
from unittest.mock import Mock
from typing import Dict
@@ -379,3 +380,93 @@ class TestStrategySubclassing:
assert strategy.custom_param == "test_value"
result = strategy.analyze_topic("query")
assert result["param"] == "test_value"
+
+
+class TestFirstUsableText:
+ """#6941: the centralized content-or-response predicate the three
+ strategy assembly sites share."""
+
+ def test_prefers_content_when_usable(self):
+ strategy = ConcreteStrategy()
+ assert (
+ strategy.first_usable_text({"content": "Synthesized"})
+ == "Synthesized"
+ )
+
+ def test_content_wins_over_a_usable_response(self):
+ # Both fields usable: only the candidate order decides, so this is
+ # the test that fails if content and response are swapped.
+ strategy = ConcreteStrategy()
+ assert (
+ strategy.first_usable_text(
+ {"content": "From content", "response": "From response"},
+ "fallback",
+ )
+ == "From content"
+ )
+
+ def test_content_wins_regardless_of_key_insertion_order(self):
+ # Precedence is the candidate tuple, not the mapping's key order.
+ strategy = ConcreteStrategy()
+ assert (
+ strategy.first_usable_text(
+ {"response": "From response", "content": "From content"}
+ )
+ == "From content"
+ )
+
+ def test_content_wins_for_non_dict_mappings_and_static_calls(self):
+ # A read-only mapping, called both through the class (it is a
+ # staticmethod) and through an instance.
+ result = MappingProxyType(
+ {"content": "From content", "response": "From response"}
+ )
+ assert ConcreteStrategy.first_usable_text(result) == "From content"
+ assert ConcreteStrategy().first_usable_text(result) == "From content"
+
+ @pytest.mark.parametrize(
+ "content",
+ ["", " ", " \n\t", None],
+ ids=["empty", "spaces", "whitespace", "none"],
+ )
+ def test_response_is_used_when_content_is_empty_blank_or_none(
+ self, content
+ ):
+ strategy = ConcreteStrategy()
+ assert (
+ strategy.first_usable_text(
+ {"content": content, "response": "From response"},
+ "fallback",
+ )
+ == "From response"
+ )
+
+ def test_falls_back_to_response_when_content_is_unusable(self):
+ strategy = ConcreteStrategy()
+ result = strategy.first_usable_text(
+ {"content": " \n\t", "response": "From response"}
+ )
+ assert result == "From response"
+
+ def test_blank_or_non_string_candidates_do_not_hide_a_valid_sibling(
+ self,
+ ):
+ strategy = ConcreteStrategy()
+ assert (
+ strategy.first_usable_text(
+ {"content": ["unexpected"], "response": "From response"}
+ )
+ == "From response"
+ )
+ assert strategy.first_usable_text({"content": 7}) is None
+
+ def test_returns_the_default_when_neither_field_is_usable(self):
+ strategy = ConcreteStrategy()
+ assert strategy.first_usable_text({}, "fallback") == "fallback"
+ assert (
+ strategy.first_usable_text(
+ {"content": "", "response": None}, "fallback"
+ )
+ == "fallback"
+ )
+ assert strategy.first_usable_text({}) is None
diff --git a/tests/advanced_search_system/strategies/test_citation_handler_failure_keeps_sources.py b/tests/advanced_search_system/strategies/test_citation_handler_failure_keeps_sources.py
index 3f337cd6fa..dfc1519f84 100644
--- a/tests/advanced_search_system/strategies/test_citation_handler_failure_keeps_sources.py
+++ b/tests/advanced_search_system/strategies/test_citation_handler_failure_keeps_sources.py
@@ -97,6 +97,30 @@ def test_response_is_used_when_content_is_unusable(factory):
assert result["findings"][-1]["documents"] == documents
+ "factory",
+ [_focused, _source_based],
+ ids=["focused-iteration", "source-based"],
+)
+def test_content_wins_over_response_when_both_are_usable(factory):
+ """Order pin (#6941): both fields usable, so only the precedence decides.
+ Every other call-site test leaves one field unusable and passes with the
+ candidate order reversed."""
+ documents = [{"title": "T", "link": "https://example.test/a"}]
+
+ result = _analyze_with_citation_result(
+ factory(),
+ {
+ "content": "Synthesized from content",
+ "response": "Synthesized from response",
+ "documents": documents,
+ },
+ )
+
+ assert result["current_knowledge"] == "Synthesized from content"
+ assert result["findings"][-1]["documents"] == documents
+
+
@pytest.mark.parametrize(
"factory,content,expected",
[