~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(strategy): route the topic-organization model calls through one helper — tranche 4 of #5854 (#6268)
LearningCircuit8f48d8859998
diff --git a/changelog.d/6268.misc.md b/changelog.d/6268.misc.mdnew file mode 100644index 0000000000..90c37792aa--- /dev/null+++ b/changelog.d/6268.misc.md@@ -0,0 +1 @@+The topic-organization research strategy now routes its eight model calls (topic extraction, lead selection, relevance filtering, reorganization, refinement questions, text and summary synthesis) through a single `_invoke_model` helper on the synchronous client, so response normalization happens in one place; an additive `_ainvoke_model` twin awaits `ainvoke` for the future single-loop async runner (#6293). Fourth tranche of #5854.diff --git a/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.py b/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.pyindex 64a2a8e8d4..55a4546493 100644--- a/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.py@@ -152,6 +152,42 @@ class TopicOrganizationStrategy(BaseSearchStrategy):# Topic graph to store organized topicsself.topic_graph = TopicGraph()+ def _invoke_model(self, prompt: str) -> str:+ """Invoke the model and return normalized text.++ The single place the strategy talks to the LLM: every one of the+ eight call sites routes through here, giving them one call path.+ ``get_llm_response_text`` preserves the existing normalization:+ it joins text from non-string content blocks, removes ``<think>``+ tags and trims whitespace. Wrapped production responses may already+ be normalized by ``ProcessingLLMWrapper``; retaining this helper+ also preserves behavior for injected or unwrapped models.++ This method runs synchronously in its caller's thread. It must not+ create a temporary event loop to drive the async twin: cached async+ HTTP clients can retain connections bound to an earlier loop+ (#6293). An async runner must manage that client and loop lifetime+ before switching production callers to :meth:`_ainvoke_model`.+ """+ return get_llm_response_text(self.model.invoke(prompt))++ async def _ainvoke_model(self, prompt: str) -> str:+ """Async counterpart of :meth:`_invoke_model`.++ Additive: no production caller awaits it yet. It exists for the+ research-runner tranche of #5854, which will drive the strategy from+ a single long-lived event loop; only then does the async LangChain+ API become safe here (#6293), and the token-usage callback needs to+ become async-aware first or the usage row loses its call-site+ attribution and can be dropped entirely (#6294).++ Every LLM object the strategy is constructed with in production+ exposes ``ainvoke`` — ``get_llm`` returns a processing wrapper+ — so there is no sync fallback here. Only the call line differs from+ :meth:`_invoke_model`.+ """+ return get_llm_response_text(await self.model.ainvoke(prompt))+def set_progress_callback(self, callback) -> None:"""Set progress callback for both this strategy and its delegate.@@ -313,8 +349,7 @@ Response:""") # Log full prompttry:- response = self.model.invoke(source_prompt)- response_text = get_llm_response_text(response).strip()+ response_text = self._invoke_model(source_prompt).strip()# Parse the compact response formatis_potential_lead = False@@ -509,8 +544,7 @@ Which source number (0-{len(all_sources) - 1}) should be the lead? (most comprehResponse (just the number):"""try:- response = self.model.invoke(selection_prompt)- response_text = get_llm_response_text(response).strip()+ response_text = self._invoke_model(selection_prompt).strip()# Parse the numbernew_lead_idx = int(response_text)@@ -615,8 +649,7 @@ Respond with only "yes" or "no".try:# Call model directly with prompt- response = self.model.invoke(relevance_prompt)- response_text = get_llm_response_text(response)+ response_text = self._invoke_model(relevance_prompt)# Check if response indicates relevanceif "yes" in response_text.lower().strip():@@ -689,8 +722,7 @@ Respond with only the number."""try:- response = self.model.invoke(selection_prompt)- response_text = get_llm_response_text(response).strip()+ response_text = self._invoke_model(selection_prompt).strip()# Parse the numbernew_lead_idx = int(response_text)@@ -781,8 +813,7 @@ Consider similarity to lead sources when deciding."""try:- response = self.model.invoke(reorganize_prompt)- response_text = get_llm_response_text(response)+ response_text = self._invoke_model(reorganize_prompt)reassignments = extract_json(response_text, expected_type=list)if reassignments is None:@@ -934,8 +965,7 @@ Otherwise, respond with only the follow-up question, nothing else."""try:- response = self.model.invoke(refinement_prompt)- response_text = get_llm_response_text(response).strip()+ response_text = self._invoke_model(refinement_prompt).strip()if "none" in response_text.lower() or not response_text:logger.info("Model determined no refinement needed")@@ -1701,8 +1731,7 @@ Remember: These are snippets, not full articles.RESEARCH QUESTION TO ANSWER: {query}"""try:- topic_response = self.model.invoke(topic_prompt)- topic_text = get_llm_response_text(topic_response)+ topic_text = self._invoke_model(topic_prompt)# Store section for summary generationtopic_sections.append(f"{topic.title}: {topic_text}")@@ -1745,8 +1774,7 @@ IMPORTANT: Focus on ANSWERING THE QUESTION directly using the information from tRESEARCH QUESTION TO ANSWER: {query}"""try:- summary_response = self.model.invoke(summary_prompt)- summary_text = get_llm_response_text(summary_response)+ summary_text = self._invoke_model(summary_prompt)# Insert summary at the beginninggenerated_texts.insert(0, summary_text)except Exception:diff --git a/tests/advanced_search_system/strategies/test_topic_organization_strategy.py b/tests/advanced_search_system/strategies/test_topic_organization_strategy.pyindex 7862f63ecf..3b943a4879 100644--- a/tests/advanced_search_system/strategies/test_topic_organization_strategy.py+++ b/tests/advanced_search_system/strategies/test_topic_organization_strategy.py@@ -11,7 +11,10 @@ Tests cover:- Error handling"""-from unittest.mock import Mock, patch+import asyncio+from unittest.mock import AsyncMock, Mock, patch++import pytestclass TestTopicOrganizationStrategyInit:@@ -356,8 +359,14 @@ class TestRelevanceFiltering:assert result == []- def test_filter_topics_by_relevance_keeps_relevant(self):- """Filter topics keeps relevant topics."""+ def test_filter_topics_by_relevance_follows_per_topic_verdict(self):+ """Each topic is kept or dropped according to its own verdict.++ A per-topic split is the only assertion that separates the happy+ path from the ``except`` path: on an error the handler keeps every+ topic, so a test that only checks a "yes" topic survives passes+ even when the model call blows up.+ """from local_deep_research.advanced_search_system.strategies.topic_organization_strategy import (TopicOrganizationStrategy,)@@ -367,14 +376,17 @@ class TestRelevanceFiltering:mock_search = Mock()mock_model = Mock()- mock_model.invoke.return_value = Mock(content="yes")+ mock_model.invoke.side_effect = [+ Mock(content="yes"),+ Mock(content="no"),+ ]strategy = TopicOrganizationStrategy(search=mock_search,model=mock_model,)- topic = Topic(+ keep = Topic(id="t1",title="Relevant Topic",lead_source={@@ -383,10 +395,23 @@ class TestRelevanceFiltering:"link": "http://test.com",},)+ drop = Topic(+ id="t2",+ title="Irrelevant Topic",+ lead_source={+ "title": "Lead",+ "snippet": "Content",+ "link": "http://other.com",+ },+ )+ strategy.topic_graph.topics = {"t1": keep, "t2": drop}- result = strategy._filter_topics_by_relevance([topic], "test query")+ result = strategy._filter_topics_by_relevance([keep, drop], "q")- assert len(result) == 1+ assert [topic.id for topic in result] == ["t1"]+ # The rejected topic is also evicted from the graph; the error+ # path would have left both entries in place.+ assert set(strategy.topic_graph.topics) == {"t1"}def test_filter_topics_by_relevance_removes_irrelevant(self):"""Filter topics removes irrelevant topics."""@@ -498,8 +523,14 @@ class TestRefinementQuestions:assert result is not Noneassert "?" in result or len(result) > 0- def test_generate_refinement_question_returns_none_for_complete(self):- """Generate refinement question returns None when model says NONE."""+ def test_generate_refinement_question_none_verdict_records_nothing(self):+ """A "NONE" verdict suppresses the question and records nothing.++ The follow-up call in the same test is what separates this from+ the ``except`` path, which also returns ``None``: after the+ suppressed round the strategy must still produce and record a+ question when the model offers one.+ """from local_deep_research.advanced_search_system.strategies.topic_organization_strategy import (TopicOrganizationStrategy,)@@ -509,7 +540,10 @@ class TestRefinementQuestions:mock_search = Mock()mock_model = Mock()- mock_model.invoke.return_value = Mock(content="NONE")+ mock_model.invoke.side_effect = [+ Mock(content="NONE"),+ Mock(content="Which regions are affected?"),+ ]strategy = TopicOrganizationStrategy(search=mock_search,@@ -527,9 +561,14 @@ class TestRefinementQuestions:},)- result = strategy._generate_refinement_question([topic], "test query")+ assert strategy._generate_refinement_question([topic], "q") is None+ assert strategy.refinement_questions == []- assert result is None+ assert (+ strategy._generate_refinement_question([topic], "q")+ == "Which regions are affected?"+ )+ assert strategy.refinement_questions == ["Which regions are affected?"]class TestTopicReorganization:@@ -871,3 +910,174 @@ class TestTextGeneration:result = strategy._generate_topic_based_text([topic], "test query")assert len(result) > 0+++class _SyncOnlyLLM:+ """LLM stub exposing ``invoke`` and a non-functional ``ainvoke``.++ ``ainvoke`` records every call it receives to ``self.async_prompts``+ but always raises ``AttributeError``, so it still fails the async path+ the same way a genuinely sync-only object would -- while leaving a+ trail (``async_prompts``) that tests can assert against to catch a+ regression that bridges to the async side through a shape other than+ ``ainvoke`` being missing entirely (e.g. ``run_until_complete`` /+ ``get_event_loop``).+ """++ def __init__(self, body: str):+ self.body = body+ self.prompts: list[str] = []+ self.async_prompts: list[str] = []++ def invoke(self, prompt, *args, **kwargs):+ self.prompts.append(str(prompt))+ return Mock(content=self.body)++ async def ainvoke(self, prompt, *args, **kwargs):+ self.async_prompts.append(str(prompt))+ raise AttributeError(+ "_SyncOnlyLLM.ainvoke is a recording stub, not a usable async path"+ )+++class TestModelInvocation:+ """Tests for the shared ``_invoke_model`` / ``_ainvoke_model`` pair."""++ @staticmethod+ def _strategy(model):+ from local_deep_research.advanced_search_system.strategies.topic_organization_strategy import (+ TopicOrganizationStrategy,+ )++ return TopicOrganizationStrategy(+ search=Mock(), model=model, enable_refinement=True+ )++ @staticmethod+ def _topic():+ from local_deep_research.advanced_search_system.findings.topic import (+ Topic,+ )++ return Topic(+ id="t1",+ title="Topic",+ lead_source={+ "title": "Lead",+ "snippet": "Content",+ "link": "http://test.com",+ },+ )++ def test_invoke_model_normalizes_and_stays_synchronous(self):+ """``_invoke_model`` calls ``invoke`` and extracts ``.content``."""+ model = _SyncOnlyLLM(" answer ")+ strategy = self._strategy(model)++ assert strategy._invoke_model("prompt").strip() == "answer"+ assert model.prompts == ["prompt"]++ def test_invoke_model_propagates_errors(self):+ """Call-site ``except`` blocks still see the model's exception."""+ model = Mock()+ model.invoke.side_effect = RuntimeError("boom")+ strategy = self._strategy(model)++ with pytest.raises(RuntimeError, match="boom"):+ strategy._invoke_model("prompt")++ def test_converted_site_never_starts_an_event_loop(self):+ """A converted call site runs without creating an event loop.++ langchain's async httpx client is process-cached and loop-bound,+ so a per-call throwaway loop breaks or re-sends every request+ after the first (#6293). ``asyncio.run`` and+ ``asyncio.new_event_loop`` are patched to raise -- but+ ``_generate_refinement_question`` wraps the call in a bare+ ``except Exception``, so a regression that reaches for either+ patched function is swallowed rather than propagated to the test.+ The real discriminator is ``len(model.prompts)``: it is 1 only if+ ``_invoke_model`` reached ``model.invoke`` directly, with no event+ loop in between.+ """+ model = _SyncOnlyLLM("Which regions are affected?")+ strategy = self._strategy(model)++ def _no_loop(*args, **kwargs):+ raise AssertionError("the sync path must not start an event loop")++ with (+ patch.object(asyncio, "run", _no_loop),+ patch.object(asyncio, "new_event_loop", _no_loop),+ ):+ question = strategy._generate_refinement_question(+ [self._topic()], "test query"+ )++ assert question == "Which regions are affected?"+ assert len(model.prompts) == 1+ assert model.async_prompts == []++ def test_extract_topics_site_never_starts_an_event_loop(self):+ """The per-source extraction loop stays synchronous too.++ ``asyncio.run`` and ``asyncio.new_event_loop`` are patched to+ raise, but the per-source loop wraps each call in a bare+ ``except Exception`` and, on failure, creates a recovery topic for+ that source -- so ``assert len(topics) == 2`` alone would pass+ under the regression too, since one recovery topic per source+ looks the same as the two "real" topics this test expects. The+ real discriminator is ``len(model.prompts)``: it can only be 2 if+ ``_invoke_model`` reached ``model.invoke`` for both sources, with+ no event loop in between.+ """+ model = _SyncOnlyLLM("-")+ strategy = self._strategy(model)++ def _no_loop(*args, **kwargs):+ raise AssertionError("the sync path must not start an event loop")++ sources = [+ {+ "title": "Source A",+ "snippet": "Content A",+ "link": "http://a.test",+ },+ {+ "title": "Source B",+ "snippet": "Content B",+ "link": "http://b.test",+ },+ ]++ with (+ patch.object(asyncio, "run", _no_loop),+ patch.object(asyncio, "new_event_loop", _no_loop),+ ):+ topics = strategy._extract_topics_from_sources(+ sources, "test query"+ )++ # "-" means "new topic" for each source.+ assert len(topics) == 2+ assert len(model.prompts) == 2+ assert model.async_prompts == []++ @pytest.mark.asyncio+ async def test_ainvoke_model_awaits_ainvoke(self):+ """The async twin awaits ``ainvoke`` and never touches ``invoke``."""+ model = Mock()+ model.ainvoke = AsyncMock(return_value=Mock(content="async answer"))+ strategy = self._strategy(model)++ assert await strategy._ainvoke_model("prompt") == "async answer"+ model.ainvoke.assert_awaited_once_with("prompt")+ model.invoke.assert_not_called()++ @pytest.mark.asyncio+ async def test_ainvoke_model_requires_ainvoke(self):+ """No sync fallback: a sync-only object is a programming error."""+ strategy = self._strategy(_SyncOnlyLLM("answer"))++ with pytest.raises(AttributeError):+ await strategy._ainvoke_model("prompt")