~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(citations): warn when a langgraph answer is saved without inline citations (#5047)
LearningCircuitb6edd1db7b02
diff --git a/changelog.d/4969.misc.md b/changelog.d/4969.misc.mdnew file mode 100644index 0000000000..12d52a69ce--- /dev/null+++ b/changelog.d/4969.misc.md@@ -0,0 +1 @@+Missing inline citations in `langgraph-agent` answers are now diagnosable from the server log: a warning fires when a call skips the citation pass despite accumulated sources (the detailed-report subsection case behind #4969), and when a completed synthesis contains no inline `[N]` markers despite available sources. Report content is unchanged.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 f772dce4ee..941e207107 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@@ -8,6 +8,7 @@ questions can be decomposed into subtopics researched in parallel by subagents.from __future__ import annotations+import reimport threadingfrom concurrent.futures import ThreadPoolExecutor, TimeoutError, as_completedfrom datetime import UTC, datetime@@ -34,6 +35,12 @@ DEFAULT_MAX_ITERATIONS = ()MIN_ITERATIONS = 10 # below this the agent can barely do anything usefulSUBAGENT_TIMEOUT_SECONDS = 1800 # 30 minutes per subagent+# User-facing sentinel for "the agent produced nothing". _finalize must+# not run the accumulated-sources citation pass over it — that would+# dress the failure up as a cited synthesis instead of surfacing it.+NO_RESULTS_MESSAGE = (+ "Research could not produce results. Try a different query."+)MAX_SUBTOPICS = 5 # must match the "pass 2-5" contract in the lead prompt# and the research_subtopic tool docstring. Values above this are dropped# at the call site, with the dropped subtopics named in the tool's reply@@ -1233,9 +1240,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):if self.collector.results:final_content = self._synthesize_from_collector(query)else:- final_content = (- "Research could not produce results. Try a different query."- )+ final_content = NO_RESULTS_MESSAGEreturn self._finalize(query, final_content, iteration, nr_of_links, agent_messages@@ -1281,13 +1286,38 @@ class LangGraphAgentStrategy(BaseSearchStrategy):agent_messages: list,) -> Dict[str, Any]:"""Apply citation handling and build the return dict."""+ all_search_results = self.collector.results++ # A subsection call in detailed-report mode can answer purely+ # from previously-written sections without running new searches,+ # leaving the per-call collector empty. The citation pass below+ # is then skipped and the section is saved as raw agent prose+ # with no inline [N] markers even though ## Sources renders the+ # full accumulated bibliography (#4969). Running the pass against+ # all_links_of_system instead is NOT safe as-is: the widened+ # prompt overflows default local-model context windows, the+ # rewrite has no structure-preservation guarantees, and the+ # empty-collector condition is also reachable from chat+ # follow-ups. Until that is redesigned, make the skip loud so+ # affected runs are diagnosable from the server log.+ if (+ not all_search_results+ and self.all_links_of_system+ and final_answer != NO_RESULTS_MESSAGE+ ):+ logger.warning(+ f"Citation pass skipped: no new sources collected in this "+ f"call although {len(self.all_links_of_system)} are "+ f"accumulated — this answer will have no inline [N] "+ f"citations (#4969, query '{query[:80]}')"+ )+self._update_progress(- f"Synthesizing {len(self.collector.results)} sources with citations",+ f"Synthesizing {len(all_search_results)} sources with citations",90,{"phase": "synthesis", "type": "milestone"},)- all_search_results = self.collector.resultssynthesized_content = final_answerdocuments: list = []@@ -1310,6 +1340,14 @@ class LangGraphAgentStrategy(BaseSearchStrategy):"Citation handler failed, using raw agent answer")+ if not re.search(r"\[\d", synthesized_content or ""):+ logger.warning(+ f"Synthesis produced no inline [N] citation markers "+ f"despite {len(all_search_results)} available sources — "+ f"the report body will show no citations for this "+ f"query ('{query[:80]}')"+ )+# Format sources — delegate to base helperformatted_output = self._format_citations(synthesized_content, all_search_resultsdiff --git a/tests/strategies/test_langgraph_agent_strategy.py b/tests/strategies/test_langgraph_agent_strategy.pyindex 2aad615ff8..3ab8c448b9 100644--- a/tests/strategies/test_langgraph_agent_strategy.py+++ b/tests/strategies/test_langgraph_agent_strategy.py@@ -2122,3 +2122,168 @@ class TestResearchSubtopicToolTruncation:assert "\r" not in tail# The escaped form (literal backslash-n) is present instead.assert "\\n" in tail+++# ---------------------------------------------------------------------------+# _finalize citation gating (#4969)+# ---------------------------------------------------------------------------+++class TestFinalizeCitationLogging:+ """#4969 observability: a call whose agent ran no new searches skips+ the citation pass (unchanged behavior — widening it is unsafe for+ local-model context windows and chat follow-ups until redesigned),+ but the skip and any marker-free synthesis must be loud in the log+ instead of silently saving uncited prose."""++ _LOGGER_PATH = (+ "local_deep_research.advanced_search_system.strategies."+ "langgraph_agent_strategy.logger"+ )++ def _make_strategy(self, all_links=None, citation_handler=None):+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (+ LangGraphAgentStrategy,+ )++ return LangGraphAgentStrategy(+ model=MagicMock(),+ search=MagicMock(),+ all_links_of_system=all_links if all_links is not None else [],+ settings_snapshot={"search.tool": {"value": "duckduckgo"}},+ citation_handler=citation_handler,+ )++ @staticmethod+ def _link(idx, url):+ return {+ "index": str(idx),+ "title": f"Source {idx}",+ "link": url,+ "snippet": "snippet",+ }++ def _warnings(self, mock_logger):+ return [str(c.args[0]) for c in mock_logger.warning.call_args_list]++ def test_empty_collector_skips_pass_and_warns(self):+ """Empty per-call collector + accumulated sources → the pass is+ skipped (raw answer kept, handler untouched) and the skip is+ logged as a warning naming the accumulated count."""+ handler = MagicMock()+ links = [self._link(1, "https://a.example/x")]+ strategy = self._make_strategy(+ all_links=links, citation_handler=handler+ )+ assert strategy.collector.results == []++ with patch(self._LOGGER_PATH) as mock_logger:+ result = strategy._finalize("q", "Uncited raw answer.", 1, 0, [])++ handler.analyze_followup.assert_not_called()+ assert result["current_knowledge"] == "Uncited raw answer."+ assert any(+ "Citation pass skipped" in w for w in self._warnings(mock_logger)+ )++ def test_no_results_sentinel_does_not_warn_about_skip(self):+ """An agent that produced nothing returns NO_RESULTS_MESSAGE —+ that is an agent failure, not a missing-citations case, so the+ skip warning must stay quiet."""+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (+ NO_RESULTS_MESSAGE,+ )++ handler = MagicMock()+ links = [self._link(1, "https://a.example/x")]+ strategy = self._make_strategy(+ all_links=links, citation_handler=handler+ )++ with patch(self._LOGGER_PATH) as mock_logger:+ result = strategy._finalize("q", NO_RESULTS_MESSAGE, 1, 0, [])++ handler.analyze_followup.assert_not_called()+ assert result["current_knowledge"] == NO_RESULTS_MESSAGE+ assert not any(+ "Citation pass skipped" in w for w in self._warnings(mock_logger)+ )++ def test_both_empty_does_not_warn(self):+ """No sources anywhere → nothing to cite, no warning noise."""+ handler = MagicMock()+ strategy = self._make_strategy(all_links=[], citation_handler=handler)++ with patch(self._LOGGER_PATH) as mock_logger:+ result = strategy._finalize("q", "Raw answer.", 1, 0, [])++ handler.analyze_followup.assert_not_called()+ assert result["current_knowledge"] == "Raw answer."+ assert not any(+ "Citation pass skipped" in w for w in self._warnings(mock_logger)+ )++ def test_populated_collector_runs_pass_unchanged(self):+ """Per-call results present → citation pass runs exactly as+ before, with the per-call list."""+ handler = MagicMock()+ handler.analyze_followup.return_value = {+ "content": "Cited [2].",+ "documents": [],+ }+ links = [self._link(1, "https://a.example/x")]+ strategy = self._make_strategy(+ all_links=links, citation_handler=handler+ )+ strategy.collector.add_results(+ [{"title": "New", "link": "https://b.example/y", "snippet": "s"}],+ engine_name="web",+ )++ result = strategy._finalize("q", "raw", 1, 1, [])++ passed_sources = handler.analyze_followup.call_args.args[1]+ assert [r["link"] for r in passed_sources] == ["https://b.example/y"]+ assert result["current_knowledge"] == "Cited [2]."++ def test_zero_marker_synthesis_logs_warning(self):+ """If the citation pass ran but its output carries no [N]+ markers, that must be visible in the server log."""+ handler = MagicMock()+ handler.analyze_followup.return_value = {+ "content": "Still no markers at all.",+ "documents": [],+ }+ strategy = self._make_strategy(all_links=[], citation_handler=handler)+ strategy.collector.add_results(+ [{"title": "New", "link": "https://b.example/y", "snippet": "s"}],+ engine_name="web",+ )++ with patch(self._LOGGER_PATH) as mock_logger:+ strategy._finalize("q", "raw", 1, 0, [])++ assert any(+ "no inline [N] citation markers" in w+ for w in self._warnings(mock_logger)+ )++ def test_marker_bearing_synthesis_does_not_warn(self):+ handler = MagicMock()+ handler.analyze_followup.return_value = {+ "content": "Cited [1] properly.",+ "documents": [],+ }+ strategy = self._make_strategy(all_links=[], citation_handler=handler)+ strategy.collector.add_results(+ [{"title": "New", "link": "https://b.example/y", "snippet": "s"}],+ engine_name="web",+ )++ with patch(self._LOGGER_PATH) as mock_logger:+ strategy._finalize("q", "raw", 1, 0, [])++ assert not any(+ "no inline [N] citation markers" in w+ for w in self._warnings(mock_logger)+ )