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(search): apply programmatic_mode post-construction in factory (#3644)

LearningCircuit7d7ba926b3a4
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 a5d69a0f66..87abbe522d 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
@@ -149,6 +149,7 @@ def _make_web_search_tool(
model: BaseChatModel,
settings_snapshot: dict,
collector: SearchResultsCollector,
+ programmatic_mode: bool = False,
):
"""Create a ``web_search`` tool that instantiates a fresh engine per call."""
@@ -164,6 +165,7 @@ def _make_web_search_tool(
engine_name=search_engine_name,
llm=model,
settings_snapshot=settings_snapshot,
+ programmatic_mode=programmatic_mode,
)
if engine is None:
return f"Failed to create search engine '{search_engine_name}'."
@@ -230,6 +232,7 @@ def _make_specialized_search_tool(
model: BaseChatModel,
settings_snapshot: dict,
collector: SearchResultsCollector,
+ programmatic_mode: bool = False,
):
"""Create a ``search_{engine}`` tool for a specific search engine."""
@@ -245,6 +248,7 @@ def _make_specialized_search_tool(
engine_name=engine_name,
llm=model,
settings_snapshot=settings_snapshot,
+ programmatic_mode=programmatic_mode,
)
if engine is None:
return f"Failed to create {engine_name} engine."
@@ -273,6 +277,7 @@ def _make_research_subtopic_tool(
collector: SearchResultsCollector,
max_sub_iterations: int,
progress_callback=None,
+ programmatic_mode: bool = False,
):
"""Create the ``research_subtopic`` tool that spawns parallel subagents."""
@@ -310,7 +315,11 @@ def _make_research_subtopic_tool(
def run_subagent(topic: str) -> str:
# Each subagent gets its own tool instances (thread safety)
sub_web_search = _make_web_search_tool(
- search_engine_name, model, settings_snapshot, collector
+ search_engine_name,
+ model,
+ settings_snapshot,
+ collector,
+ programmatic_mode=programmatic_mode,
)
sub_fetch = _make_fetch_content_tool(collector)
try:
@@ -404,6 +413,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
include_sub_research: bool = True,
all_links_of_system: list | None = None,
settings_snapshot: dict | None = None,
+ programmatic_mode: bool = False,
**kwargs,
):
super().__init__(
@@ -413,6 +423,10 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
)
self.model = model
self.search = search
+ # Whether the parent AdvancedSearchSystem is running in programmatic
+ # mode (no DB metrics/rate-limit persistence). Threaded into the
+ # tool factory closures so engines created per tool call inherit it.
+ self.programmatic_mode = programmatic_mode
# search.iterations (typically 1-5) controls pipeline strategies.
# For an agent, each "iteration" is one LLM→tool round-trip, so we
# need many more. Treat any value below the agent minimum as "use
@@ -469,6 +483,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
self.model,
self.settings_snapshot,
self.collector,
+ programmatic_mode=self.programmatic_mode,
)
)
@@ -499,6 +514,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
self.model,
self.settings_snapshot,
self.collector,
+ programmatic_mode=self.programmatic_mode,
)
)
except Exception:
@@ -516,6 +532,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
self.collector,
self.max_sub_iterations,
progress_callback=self.progress_callback,
+ programmatic_mode=self.programmatic_mode,
)
)
diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_service.py b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
index 634e19b4dc..e0f56c09e1 100644
--- a/src/local_deep_research/benchmarks/web_api/benchmark_service.py
+++ b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
@@ -769,6 +769,12 @@ class BenchmarkService:
settings_snapshot=settings_context.snapshot, # Pass settings snapshot for thread safety
username=task.get("username"), # Pass username
user_password=user_password, # Pass password for metrics tracking
+ # The web benchmark runs against the user's encrypted DB
+ # (it has username/password and wants search metrics
+ # persisted). quick_summary's default is programmatic_mode=True
+ # for true library callers; override here so the engine's
+ # metrics path stays active.
+ programmatic_mode=False,
)
processing_time = time.time() - start_time
logger.info(
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index c1d43edaed..4b49cd2d9b 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -212,6 +212,9 @@ class AdvancedSearchSystem:
use_browsecomp_optimization=True,
# Pass search original query parameter
search_original_query=self.search_original_query,
+ # Forwarded so strategies that create engines per tool call
+ # (e.g. langgraph-agent) can match the system's mode.
+ programmatic_mode=self.programmatic_mode,
)
# Log the actual strategy class
diff --git a/src/local_deep_research/search_system_factory.py b/src/local_deep_research/search_system_factory.py
index 0922fb7d35..4fd7bc02e3 100644
--- a/src/local_deep_research/search_system_factory.py
+++ b/src/local_deep_research/search_system_factory.py
@@ -921,6 +921,7 @@ def create_strategy(
True,
),
),
+ programmatic_mode=kwargs.get("programmatic_mode", False),
all_links_of_system=all_links_of_system,
settings_snapshot=settings_snapshot,
)
diff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.py
index e7d5c598f7..0e0536c328 100644
--- a/src/local_deep_research/web_search_engines/search_engine_base.py
+++ b/src/local_deep_research/web_search_engines/search_engine_base.py
@@ -275,24 +275,34 @@ class BaseSearchEngine(ABC):
self.settings_snapshot = (
settings_snapshot or {}
) # Store settings snapshot
- self.programmatic_mode = programmatic_mode
- # Rate limiting attributes
self.engine_type = self.__class__.__name__
- # Create a tracker with our settings if in programmatic mode
- if self.programmatic_mode:
+ self._configure_programmatic_mode(programmatic_mode)
+ self._last_wait_time = (
+ 0.0 # Default to 0 for successful searches without rate limiting
+ )
+ self._last_results_count = 0
+
+ def _configure_programmatic_mode(self, programmatic_mode: bool) -> None:
+ """Set ``programmatic_mode`` and (re)bind the matching rate tracker.
+
+ Called from ``__init__`` and from the factory as a fallback when an
+ engine subclass swallows the ``programmatic_mode`` kwarg without
+ forwarding it to ``super().__init__``. Safe to call after init —
+ rebinding ``rate_tracker`` discards the previous tracker (no
+ resources to release) and the new one starts with empty in-memory
+ caches.
+ """
+ self.programmatic_mode = programmatic_mode
+ if programmatic_mode:
from .rate_limiting.tracker import AdaptiveRateLimitTracker
self.rate_tracker = AdaptiveRateLimitTracker(
settings_snapshot=self.settings_snapshot,
- programmatic_mode=self.programmatic_mode,
+ programmatic_mode=programmatic_mode,
)
else:
self.rate_tracker = get_tracker()
- self._last_wait_time = (
- 0.0 # Default to 0 for successful searches without rate limiting
- )
- self._last_results_count = 0
@property
def max_filtered_results(self) -> int:
diff --git a/src/local_deep_research/web_search_engines/search_engine_factory.py b/src/local_deep_research/web_search_engines/search_engine_factory.py
index 54701b2c44..1fb80c560f 100644
--- a/src/local_deep_research/web_search_engines/search_engine_factory.py
+++ b/src/local_deep_research/web_search_engines/search_engine_factory.py
@@ -44,6 +44,7 @@ def create_search_engine(
llm=llm,
search_mode=SearchMode.SCIENTIFIC,
settings_snapshot=settings_snapshot,
+ programmatic_mode=programmatic_mode,
**kwargs,
)
if engine_name == "parallel":
@@ -54,6 +55,7 @@ def create_search_engine(
llm=llm,
search_mode=SearchMode.ALL,
settings_snapshot=settings_snapshot,
+ programmatic_mode=programmatic_mode,
**kwargs,
)
@@ -67,6 +69,7 @@ def create_search_engine(
retriever=retriever,
name=engine_name,
max_results=kwargs.get("max_results", 10),
+ programmatic_mode=programmatic_mode,
)
# Extract search engine configs from settings snapshot
@@ -263,6 +266,17 @@ def create_search_engine(
# Create the engine instance with filtered parameters
engine = engine_class(**filtered_params)
+ # Most engine subclasses do not name ``programmatic_mode`` in their
+ # signature (or accept it via **kwargs without forwarding to
+ # ``super().__init__``), so the constructor often falls back to the
+ # BaseSearchEngine default of False even when the API caller asked
+ # for True. Apply the requested mode post-construction so the
+ # engine's rate tracker matches.
+ if isinstance(engine, BaseSearchEngine) and (
+ engine.programmatic_mode != programmatic_mode
+ ):
+ engine._configure_programmatic_mode(programmatic_mode)
+
# Determine if this engine should use LLM relevance filtering
# Priority: per-engine setting > needs_llm_relevance_filter > global setting
#
diff --git a/tests/web_search_engines/test_search_engine_factory_coverage.py b/tests/web_search_engines/test_search_engine_factory_coverage.py
index 5dc9ea4d7d..52daa48f77 100644
--- a/tests/web_search_engines/test_search_engine_factory_coverage.py
+++ b/tests/web_search_engines/test_search_engine_factory_coverage.py
@@ -1253,3 +1253,130 @@ class TestPerEngineFilterPlainBool:
assert result is not None
assert getattr(result, "enable_llm_relevance_filter", False) is False
+
+
+# ---------------------------------------------------------------------------
+# Tests: programmatic_mode propagation to engines that swallow **kwargs
+# ---------------------------------------------------------------------------
+
+
+class TestProgrammaticModePostConstructionPatch:
+ """Most concrete engines (Serper, Tavily, Wikipedia, etc.) accept
+ ``**kwargs`` in their constructor but do not forward them to
+ ``BaseSearchEngine.__init__``. As a result, ``programmatic_mode``
+ passed by the factory was silently dropped and the engine ended up
+ with the BaseSearchEngine default (False), mismatching what the API
+ caller asked for. The factory now applies the requested mode
+ post-construction via ``_configure_programmatic_mode``."""
+
+ def _make_kwargs_swallowing_engine(self):
+ """Build a real BaseSearchEngine subclass that mirrors the
+ Serper/Tavily/Wikipedia pattern: accepts ``**kwargs`` without
+ forwarding to ``super().__init__``."""
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class _SwallowingEngine(BaseSearchEngine):
+ def __init__(self, max_results: int = 10, **kwargs):
+ super().__init__(max_results=max_results)
+
+ def _get_previews(self, query):
+ return []
+
+ def _get_full_content(self, items):
+ return items
+
+ return _SwallowingEngine
+
+ def test_engine_swallowing_kwargs_still_gets_programmatic_mode(self):
+ """Engine doesn't forward kwargs -> factory patches it post-construction."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = self._make_kwargs_swallowing_engine()
+
+ with _patches(
+ config_return={"eng": _engine_config()},
+ class_return=EngCls,
+ ):
+ result = create_search_engine(
+ "eng",
+ settings_snapshot={"x": 1},
+ programmatic_mode=True,
+ )
+
+ assert result is not None
+ # Without the post-construction patch this would be False
+ # because _SwallowingEngine.__init__ swallowed programmatic_mode.
+ assert result.programmatic_mode is True
+ # And the rate_tracker should be the per-instance programmatic one,
+ # not the global shared tracker returned by get_tracker().
+ from local_deep_research.web_search_engines.rate_limiting.tracker import (
+ AdaptiveRateLimitTracker,
+ )
+
+ assert isinstance(result.rate_tracker, AdaptiveRateLimitTracker)
+ assert result.rate_tracker.programmatic_mode is True
+
+ def test_engine_swallowing_kwargs_default_mode_unchanged(self):
+ """When programmatic_mode is False (default), no patch is needed
+ and the engine ends up in shared-tracker mode."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = self._make_kwargs_swallowing_engine()
+
+ with _patches(
+ config_return={"eng": _engine_config()},
+ class_return=EngCls,
+ ):
+ result = create_search_engine("eng", settings_snapshot={"x": 1})
+
+ assert result is not None
+ assert result.programmatic_mode is False
+
+ def test_retriever_path_propagates_programmatic_mode(self):
+ """The retriever early-return path returns before the post-construction
+ patch — verify programmatic_mode is passed at construction so the
+ engine still ends up in the requested mode.
+ """
+ from langchain_core.retrievers import BaseRetriever
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ class _DummyRetriever(BaseRetriever):
+ def _get_relevant_documents(self, query, *, run_manager):
+ return []
+
+ retriever = _DummyRetriever()
+
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry"
+ ) as mock_reg:
+ mock_reg.get.return_value = retriever
+ result = create_search_engine("my_rag", programmatic_mode=True)
+
+ assert result is not None
+ assert result.programmatic_mode is True
+
+ def test_parallel_path_propagates_programmatic_mode(self):
+ """The parallel early-return path returns before the post-construction
+ patch — verify programmatic_mode is passed at construction.
+ """
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ result = create_search_engine(
+ "parallel",
+ llm=Mock(),
+ settings_snapshot={"x": 1},
+ programmatic_mode=True,
+ )
+
+ assert result is not None
+ assert result.programmatic_mode is True