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.

fix(strategy): preserve agent final_answer when citation handler returns empty content (#4754)

LearningCircuit486f59be8da5
diff --git a/changelog.d/4754.bugfix.md b/changelog.d/4754.bugfix.md
new file mode 100644
index 0000000000..ddabb6fae3
--- /dev/null
+++ b/changelog.d/4754.bugfix.md
@@ -0,0 +1 @@
+Fixed reports collapsing to just a `## Sources` list when citation synthesis returned empty or unusable text (for example, a reasoning model's citation pass producing only a `<think>` block). The agent's original answer is now preserved beneath a short notice instead of being silently discarded.
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 ec2c9c3ba8..dd64ed6a95 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
@@ -87,6 +87,11 @@ NO_RESULTS_MESSAGE = (
NO_SYNTHESIS_MESSAGE = (
"Research could not be completed within the iteration limit."
)
+# Prefixed onto the raw agent answer when citation synthesis returns no
+# usable text; byte-exact text is pinned by several test assertions.
+CITATION_FALLBACK_NOTICE = (
+ "Citation synthesis returned no response; showing the agent answer.\n\n"
+)
MAX_SUBTOPICS = 5 # preferred batch size; must match the "pass 2-5" contract
# in the lead prompt and research_subtopic tool description. A bounded
# overflow is queued through the existing worker pool instead of discarded.
@@ -2978,9 +2983,35 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
"content" in citation_result
or "response" in citation_result
):
- synthesized_content = citation_result.get(
- "content", citation_result.get("response", final_answer)
- )
+ # 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
+ else:
+ raw_fallback_markers = CITATION_MARKER_RE.findall(
+ final_answer or ""
+ )
+ citation_failed = True
+ logger.warning(
+ f"Citation synthesis returned no usable text; "
+ f"using raw agent answer ({len(raw_fallback_markers)} "
+ f"inline [N]/【N】 marker(s) present, query "
+ f"'{query[:80]}')"
+ )
+ if not (final_answer or "").strip():
+ # Nothing to show — leave the content exactly as
+ # the siblings do, instead of shipping a banner
+ # with no answer behind it.
+ synthesized_content = final_answer
+ else:
+ synthesized_content = (
+ CITATION_FALLBACK_NOTICE + final_answer
+ )
documents = citation_result.get("documents", [])
elif isinstance(citation_result, dict):
# An empty dict (or one carrying neither text key)
diff --git a/tests/strategies/test_langgraph_agent_strategy.py b/tests/strategies/test_langgraph_agent_strategy.py
index 2bcd54552b..1bff2ce6bf 100644
--- a/tests/strategies/test_langgraph_agent_strategy.py
+++ b/tests/strategies/test_langgraph_agent_strategy.py
@@ -1740,6 +1740,245 @@ class TestLangGraphAgentStrategy:
assert hasattr(strategy, "analyze_topic")
assert hasattr(strategy, "collector")
+ def test_finalize_preserves_final_answer_on_empty_citation_content(self):
+ """A blank citation ``content`` must prefix the raw answer with a warning."""
+ strategy = self._make_strategy()
+ strategy.collector.add_results(
+ [{"title": "S", "link": "https://e.com", "snippet": "x"}]
+ )
+ strategy.citation_handler = MagicMock()
+ strategy.citation_handler.analyze_followup.return_value = {
+ "content": "", # blank synthesis — must not clobber the answer
+ "documents": [],
+ }
+
+ result = strategy._finalize(
+ query="why",
+ final_answer="THE REAL AGENT ANSWER",
+ iteration=1,
+ nr_of_links=10,
+ agent_messages=[],
+ )
+
+ expected = (
+ "Citation synthesis returned no response; showing the agent "
+ "answer.\n\nTHE REAL AGENT ANSWER"
+ )
+ assert result["current_knowledge"] == expected
+ assert result["findings"][0]["content"] == expected
+ # The rendered report keeps the warning lead and the Sources bibliography.
+ assert result["formatted_findings"].startswith(
+ "Citation synthesis returned no response; showing the agent answer"
+ )
+ assert "## Sources" in result["formatted_findings"]
+
+ def test_finalize_falls_back_to_final_answer_when_content_and_response_empty(
+ self,
+ ):
+ # Given
+ strategy = self._make_strategy()
+ strategy.collector.add_results(
+ [{"title": "S", "link": "https://e.com", "snippet": "x"}]
+ )
+ strategy.citation_handler = MagicMock()
+ strategy.citation_handler.analyze_followup.return_value = {
+ "content": "",
+ "response": "",
+ "documents": [],
+ }
+
+ # When
+ result = strategy._finalize(
+ query="why",
+ final_answer="THE REAL AGENT ANSWER",
+ iteration=1,
+ nr_of_links=10,
+ agent_messages=[],
+ )
+
+ # Then
+ expected = (
+ "Citation synthesis returned no response; showing the agent "
+ "answer.\n\nTHE REAL AGENT ANSWER"
+ )
+ assert result["current_knowledge"] == expected
+ assert result["findings"][0]["content"] == expected
+
+ def test_finalize_uses_citation_content_when_present(self):
+ """Positive control: a non-empty citation ``content`` IS used — the
+ fix must not blindly fall through to final_answer."""
+ strategy = self._make_strategy()
+ strategy.collector.add_results(
+ [{"title": "S", "link": "https://e.com", "snippet": "x"}]
+ )
+ strategy.citation_handler = MagicMock()
+ strategy.citation_handler.analyze_followup.return_value = {
+ "content": "CITED SYNTHESIS",
+ "documents": [],
+ }
+
+ result = strategy._finalize(
+ query="why",
+ final_answer="raw agent answer",
+ iteration=1,
+ nr_of_links=10,
+ agent_messages=[],
+ )
+
+ assert result["current_knowledge"] == "CITED SYNTHESIS"
+
+ def test_finalize_uses_response_when_content_is_empty(self):
+ # Given — content blank, response carries the synthesis. Valid-response
+ # control: response MUST be used verbatim, with no warning prefix.
+ strategy = self._make_strategy()
+ strategy.collector.add_results(
+ [{"title": "S", "link": "https://e.com", "snippet": "x"}]
+ )
+ strategy.citation_handler = MagicMock()
+ strategy.citation_handler.analyze_followup.return_value = {
+ "content": "",
+ "response": "CITED RESPONSE",
+ "documents": [],
+ }
+
+ # When
+ result = strategy._finalize(
+ query="why",
+ final_answer="raw agent answer",
+ iteration=1,
+ nr_of_links=10,
+ agent_messages=[],
+ )
+
+ # Then — no warning prefix when response is usable
+ assert result["current_knowledge"] == "CITED RESPONSE"
+ assert result["findings"][0]["content"] == "CITED RESPONSE"
+
+ @pytest.mark.parametrize(
+ "content,response,expected",
+ [
+ (" \n\t", None, None),
+ (" ", "CITED RESPONSE", "CITED RESPONSE"),
+ ({"unexpected": True}, "CITED RESPONSE", "CITED RESPONSE"),
+ (["unexpected"], "CITED RESPONSE", "CITED RESPONSE"),
+ (7, None, None),
+ (" CITED CONTENT ", "RESPONSE", " CITED CONTENT "),
+ ],
+ )
+ def test_finalize_selects_first_usable_citation_text(
+ self, content, response, expected
+ ):
+ strategy = self._make_strategy()
+ strategy.collector.add_results(
+ [{"title": "S", "link": "https://e.com", "snippet": "x"}]
+ )
+ strategy.citation_handler = MagicMock()
+ strategy.citation_handler.analyze_followup.return_value = {
+ "content": content,
+ "response": response,
+ "documents": [],
+ }
+ result = strategy._finalize(
+ query="why",
+ final_answer="ORIGINAL ANSWER",
+ iteration=1,
+ nr_of_links=10,
+ agent_messages=[],
+ )
+ if expected is None:
+ expected = (
+ "Citation synthesis returned no response; "
+ "showing the agent answer.\n\nORIGINAL ANSWER"
+ )
+ assert result["current_knowledge"] == expected
+ assert result["findings"][0]["content"] == expected
+ assert expected in result["formatted_findings"]
+ assert "## Sources" in result["formatted_findings"]
+
+ def test_finalize_empty_content_warns_with_marker_census_and_suppresses_zero_marker_warning(
+ self,
+ ):
+ """The empty-content/response fallback must carry the same
+ diagnostics as its sibling fallback branches (marker census +
+ query), and its ``citation_failed = True`` must suppress the
+ separate 'no inline markers' warning — the same logging
+ contract ``test_handler_empty_dict_result_warns_distinctly``
+ pins for the keyless-dict fallback branch."""
+ strategy = self._make_strategy()
+ strategy.collector.add_results(
+ [{"title": "S", "link": "https://e.com", "snippet": "x"}]
+ )
+ strategy.citation_handler = MagicMock()
+ strategy.citation_handler.analyze_followup.return_value = {
+ "content": "",
+ "documents": [],
+ }
+ logger_path = (
+ "local_deep_research.advanced_search_system.strategies."
+ "langgraph_agent_strategy.logger"
+ )
+
+ with patch(logger_path) as mock_logger:
+ result = strategy._finalize(
+ query="q",
+ final_answer="THE REAL AGENT ANSWER",
+ iteration=1,
+ nr_of_links=10,
+ agent_messages=[],
+ )
+
+ warnings = [str(c.args[0]) for c in mock_logger.warning.call_args_list]
+ matching = [
+ w
+ for w in warnings
+ if "Citation synthesis returned no usable text" in w
+ ]
+ assert len(matching) == 1
+ assert matching[0] == (
+ "Citation synthesis returned no usable text; using raw "
+ "agent answer (0 inline [N]/【N】 marker(s) present, "
+ "query 'q')"
+ )
+ assert not any("Synthesis produced no inline" in w for w in warnings)
+ expected = (
+ "Citation synthesis returned no response; showing the agent "
+ "answer.\n\nTHE REAL AGENT ANSWER"
+ )
+ assert result["current_knowledge"] == expected
+ assert result["findings"][0]["content"] == expected
+
+ def test_finalize_blank_final_answer_with_empty_content_has_no_banner(
+ self,
+ ):
+ """When there is no answer to show, the fallback must leave the
+ content blank instead of prefixing the banner onto nothing —
+ that would claim an answer exists when the body is empty."""
+ strategy = self._make_strategy()
+ strategy.collector.add_results(
+ [{"title": "S", "link": "https://e.com", "snippet": "x"}]
+ )
+ strategy.citation_handler = MagicMock()
+ strategy.citation_handler.analyze_followup.return_value = {
+ "content": "",
+ "documents": [],
+ }
+
+ result = strategy._finalize(
+ query="q",
+ final_answer="",
+ iteration=1,
+ nr_of_links=10,
+ agent_messages=[],
+ )
+
+ assert result["current_knowledge"] == ""
+ assert result["findings"][0]["content"] == ""
+ assert (
+ "Citation synthesis returned no response"
+ not in (result["formatted_findings"])
+ )
+ assert "## Sources" in result["formatted_findings"]
+
def test_format_agent_error_scrubs_credentials(self):
"""_format_agent_error is rendered to the user, so it must scrub
credentials from the exception text — while keeping the