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: Replace programmatic_mode setting with explicit argument (#627) (#633)

LearningCircuit94291ea5ed94
diff --git a/examples/api_usage/programmatic/README.md b/examples/api_usage/programmatic/README.md
index c5395c9806..d6ac613fc7 100644
--- a/examples/api_usage/programmatic/README.md
+++ b/examples/api_usage/programmatic/README.md
@@ -11,15 +11,16 @@ from local_deep_research.api import quick_summary, detailed_research
from local_deep_research.api.settings_utils import create_settings_snapshot
# Create settings for programmatic mode
-settings = create_settings_snapshot(
- overrides={
- "programmatic_mode": True,
- "search.tool": "wikipedia"
- }
-)
+settings = create_settings_snapshot({
+ "search.tool": "wikipedia"
+})
# Run research
-result = quick_summary("your topic", settings_snapshot=settings)
+result = quick_summary(
+ "your topic",
+ settings_snapshot=settings,
+ programmatic_mode=True
+)
```
## Examples Overview
@@ -89,9 +90,13 @@ result = quick_summary("your topic", settings_snapshot=settings)
## Key Concepts
### Programmatic Mode
-All examples use `programmatic_mode: True` in settings to bypass authentication:
+All examples use `programmatic_mode=True` as an explicit parameter to bypass authentication:
```python
-settings = create_settings_snapshot(overrides={"programmatic_mode": True})
+result = quick_summary(
+ query="your topic",
+ settings_snapshot=settings,
+ programmatic_mode=True
+)
```
### Search Strategies
@@ -113,7 +118,8 @@ result = quick_summary(
query="topic",
retrievers={"my_docs": custom_retriever},
search_tool="my_docs",
- settings_snapshot=settings
+ settings_snapshot=settings,
+ programmatic_mode=True
)
```
@@ -125,12 +131,13 @@ Generate a quick research summary:
from local_deep_research.api import quick_summary
from local_deep_research.api.settings_utils import create_settings_snapshot
-settings = create_settings_snapshot(overrides={"programmatic_mode": True})
+settings = create_settings_snapshot({})
result = quick_summary(
query="Your research question",
settings_snapshot=settings,
search_tool="wikipedia",
- iterations=2
+ iterations=2,
+ programmatic_mode=True
)
```
@@ -144,7 +151,8 @@ result = detailed_research(
settings_snapshot=settings,
search_strategy="source-based",
iterations=3,
- questions_per_iteration=5
+ questions_per_iteration=5,
+ programmatic_mode=True
)
```
@@ -194,10 +202,14 @@ result = generate_report(
## Troubleshooting
### "No settings context available" Error
-Make sure to pass `settings_snapshot` to all API functions:
+Make sure to pass `settings_snapshot` and `programmatic_mode` to all API functions:
```python
-settings = create_settings_snapshot(overrides={"programmatic_mode": True})
-result = quick_summary("topic", settings_snapshot=settings)
+settings = create_settings_snapshot({})
+result = quick_summary(
+ "topic",
+ settings_snapshot=settings,
+ programmatic_mode=True
+)
```
### Ollama Connection Error
diff --git a/examples/api_usage/programmatic/custom_llm_retriever_example.py b/examples/api_usage/programmatic/custom_llm_retriever_example.py
index 5e85f6a3ef..d9703fc1c2 100644
--- a/examples/api_usage/programmatic/custom_llm_retriever_example.py
+++ b/examples/api_usage/programmatic/custom_llm_retriever_example.py
@@ -129,9 +129,8 @@ def main():
print("2. Setting up custom retriever...")
custom_retriever = CustomRetriever()
- # 3. Create settings for programmatic mode
+ # 3. Create settings
settings = {
- "programmatic_mode": True, # Essential for avoiding database dependencies
"search.iterations": 2,
"search.questions_per_iteration": 3,
"search.strategy": "source-based",
@@ -144,8 +143,12 @@ def main():
# 5. Initialize the search system
print("4. Initializing AdvancedSearchSystem with custom components...")
+ # Pass programmatic_mode=True to avoid database dependencies
search_system = AdvancedSearchSystem(
- llm=llm, search=search_engine, settings_snapshot=settings
+ llm=llm,
+ search=search_engine,
+ settings_snapshot=settings,
+ programmatic_mode=True,
)
# 6. Run research queries
diff --git a/examples/api_usage/programmatic/hybrid_search_example.py b/examples/api_usage/programmatic/hybrid_search_example.py
index 5ce89c5f15..cdbde3d302 100644
--- a/examples/api_usage/programmatic/hybrid_search_example.py
+++ b/examples/api_usage/programmatic/hybrid_search_example.py
@@ -129,8 +129,7 @@ Each provides different perspectives on the same topic.
# Configure settings
settings = create_settings_snapshot(
- overrides={
- "programmatic_mode": True,
+ {
"search.tool": "auto", # Will use all provided retrievers
}
)
@@ -147,6 +146,7 @@ Each provides different perspectives on the same topic.
search_tool="auto", # Use all retrievers
iterations=2,
questions_per_iteration=2,
+ programmatic_mode=True,
)
print("\nResearch Summary (first 400 chars):")
@@ -189,8 +189,7 @@ This provides both specific and general information.
# Configure settings to use both retriever and web
settings = create_settings_snapshot(
- overrides={
- "programmatic_mode": True,
+ {
"search.tool": "wikipedia", # Also use Wikipedia
}
)
@@ -206,6 +205,7 @@ This provides both specific and general information.
search_strategy="source-based",
iterations=2,
questions_per_iteration=3,
+ programmatic_mode=True,
)
print(f"\nResearch ID: {result['research_id']}")
@@ -255,8 +255,7 @@ Analyzing source quality and relevance:
business_retriever = BusinessDocsRetriever()
settings = create_settings_snapshot(
- overrides={
- "programmatic_mode": True,
+ {
"search.tool": "wikipedia",
}
)
@@ -272,6 +271,7 @@ Analyzing source quality and relevance:
search_tool="wikipedia", # Also use web search
iterations=2,
questions_per_iteration=2,
+ programmatic_mode=True,
)
# Detailed source analysis
@@ -327,11 +327,7 @@ Using meta search for sophisticated search strategies:
# Create retrievers
tech_retriever = TechnicalDocsRetriever()
- settings = create_settings_snapshot(
- overrides={
- "programmatic_mode": True,
- }
- )
+ settings = create_settings_snapshot({})
# Advanced meta search configuration
result = quick_summary(
@@ -350,6 +346,7 @@ Using meta search for sophisticated search strategies:
},
iterations=2,
questions_per_iteration=3,
+ programmatic_mode=True,
)
print("\nMeta search results:")
diff --git a/examples/api_usage/programmatic/minimal_working_example.py b/examples/api_usage/programmatic/minimal_working_example.py
index 37b15578b3..b15782d21b 100644
--- a/examples/api_usage/programmatic/minimal_working_example.py
+++ b/examples/api_usage/programmatic/minimal_working_example.py
@@ -54,9 +54,8 @@ def main():
# 2. Create minimal search engine
print("2. Creating minimal search engine...")
- # IMPORTANT: Set programmatic_mode to avoid database dependencies
+ # Settings for search system (without programmatic_mode)
settings = {
- "programmatic_mode": True,
"search.iterations": 1,
"search.strategy": "direct",
}
@@ -65,8 +64,12 @@ def main():
# 3. Create search system
print("3. Creating AdvancedSearchSystem...")
+ # IMPORTANT: Pass programmatic_mode=True to avoid database dependencies
system = AdvancedSearchSystem(
- llm=llm, search=search, settings_snapshot=settings
+ llm=llm,
+ search=search,
+ settings_snapshot=settings,
+ programmatic_mode=True,
)
# 4. Run a search
diff --git a/examples/api_usage/programmatic/search_strategies_example.py b/examples/api_usage/programmatic/search_strategies_example.py
index 0852857b56..7b59c3d2c5 100644
--- a/examples/api_usage/programmatic/search_strategies_example.py
+++ b/examples/api_usage/programmatic/search_strategies_example.py
@@ -33,8 +33,7 @@ This strategy:
# Configure settings for programmatic mode
settings = create_settings_snapshot(
- overrides={
- "programmatic_mode": True,
+ {
"search.tool": "wikipedia", # Using Wikipedia for demonstration
}
)
@@ -46,6 +45,7 @@ This strategy:
search_strategy="source-based", # Explicitly set strategy
iterations=2, # Number of research iterations
questions_per_iteration=3, # Questions to explore per iteration
+ programmatic_mode=True,
)
print(f"Research ID: {result['research_id']}")
@@ -91,8 +91,7 @@ This strategy:
# Configure settings
settings = create_settings_snapshot(
- overrides={
- "programmatic_mode": True,
+ {
"search.tool": "wikipedia",
}
)
@@ -105,6 +104,7 @@ This strategy:
iterations=3, # More iterations for deeper exploration
questions_per_iteration=2, # Fewer but more focused questions
temperature=0.7, # Slightly higher for creative question generation
+ programmatic_mode=True,
)
print("\nSummary (first 500 chars):")
@@ -147,8 +147,7 @@ def compare_strategies():
)
settings = create_settings_snapshot(
- overrides={
- "programmatic_mode": True,
+ {
"search.tool": "wikipedia",
}
)
@@ -163,6 +162,7 @@ def compare_strategies():
search_strategy="source-based",
iterations=2,
questions_per_iteration=3,
+ programmatic_mode=True,
)
print(f" - Sources found: {len(source_result.get('sources', []))}")
print(f" - Summary length: {len(source_result.get('summary', ''))} chars")
@@ -175,6 +175,7 @@ def compare_strategies():
search_strategy="focused-iteration",
iterations=2,
questions_per_iteration=3,
+ programmatic_mode=True,
)
print(f" - Sources found: {len(focused_result.get('sources', []))}")
print(
diff --git a/examples/api_usage/programmatic/searxng_example.py b/examples/api_usage/programmatic/searxng_example.py
index 9be7fd07a1..87a0050e72 100644
--- a/examples/api_usage/programmatic/searxng_example.py
+++ b/examples/api_usage/programmatic/searxng_example.py
@@ -37,9 +37,8 @@ def main():
print("1. Setting up Ollama LLM...")
llm = ChatOllama(model="gemma3:12b", temperature=0.3)
- # 2. Configure settings for programmatic mode
+ # 2. Configure settings
settings = {
- "programmatic_mode": True,
"search.iterations": 2,
"search.questions_per_iteration": 3,
"search.strategy": "source-based",
@@ -95,8 +94,12 @@ def main():
# 4. Create the search system
print("3. Creating AdvancedSearchSystem...")
+ # Pass programmatic_mode=True to disable database dependencies
search_system = AdvancedSearchSystem(
- llm=llm, search=search_engine, settings_snapshot=settings
+ llm=llm,
+ search=search_engine,
+ settings_snapshot=settings,
+ programmatic_mode=True,
)
# 5. Run research queries
diff --git a/examples/api_usage/programmatic/simple_programmatic_example.py b/examples/api_usage/programmatic/simple_programmatic_example.py
index d8c9d17b35..b2723658a9 100755
--- a/examples/api_usage/programmatic/simple_programmatic_example.py
+++ b/examples/api_usage/programmatic/simple_programmatic_example.py
@@ -18,19 +18,19 @@ from local_deep_research.api.settings_utils import (
# This provides all necessary settings with sensible defaults
settings_snapshot = create_settings_snapshot(
overrides={
- "programmatic_mode": True,
"search.tool": "wikipedia", # Use Wikipedia for this example
}
)
# Alternative: Use completely default settings
# settings_snapshot = get_default_settings_snapshot()
-# Note: You may want to set programmatic_mode in the snapshot
# Example 1: Quick Summary
print("=== Quick Summary ===")
result = quick_summary(
- "What is machine learning?", settings_snapshot=settings_snapshot
+ "What is machine learning?",
+ settings_snapshot=settings_snapshot,
+ programmatic_mode=True,
)
print(f"Summary: {result['summary'][:300]}...")
print(f"Found {len(result.get('findings', []))} findings")
@@ -43,6 +43,7 @@ result = detailed_research(
search_tool="wikipedia",
search_strategy="source_based",
settings_snapshot=settings_snapshot,
+ programmatic_mode=True,
)
print(f"Research ID: {result['research_id']}")
print(f"Summary length: {len(result['summary'])} characters")
@@ -59,6 +60,7 @@ result = quick_summary(
provider="openai_endpoint", # Specify LLM provider
model_name="llama-3.3-70b-instruct", # Specify model
settings_snapshot=settings_snapshot,
+ programmatic_mode=True,
)
print(f"Completed {result['iterations']} iterations")
print(
diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.py
index d23593e203..cc08661efb 100644
--- a/src/local_deep_research/api/research_functions.py
+++ b/src/local_deep_research/api/research_functions.py
@@ -32,6 +32,7 @@ def _init_search_system(
username: Optional[str] = None,
research_id: Optional[Union[int, str]] = None,
research_context: Optional[Dict[str, Any]] = None,
+ programmatic_mode: bool = True,
**kwargs: Any,
) -> AdvancedSearchSystem:
"""
@@ -54,6 +55,7 @@ def _init_search_system(
search_strategy: The name of the search strategy to use.
retrievers: Optional dictionary of {name: retriever} pairs to use as search engines
llms: Optional dictionary of {name: llm} pairs to use as language models
+ programmatic_mode: If True, disables database operations and metrics tracking
Returns:
AdvancedSearchSystem: An instance of the configured AdvancedSearchSystem.
@@ -104,6 +106,7 @@ def _init_search_system(
llm_instance=llm,
username=username,
settings_snapshot=settings_snapshot,
+ programmatic_mode=programmatic_mode,
)
if search_engine is None:
logger.warning(
@@ -120,6 +123,7 @@ def _init_search_system(
research_id=research_id,
research_context=research_context,
settings_snapshot=settings_snapshot,
+ programmatic_mode=programmatic_mode,
)
# Override default settings with user-provided values
diff --git a/src/local_deep_research/config/search_config.py b/src/local_deep_research/config/search_config.py
index 9de29d3596..3533e13eb8 100644
--- a/src/local_deep_research/config/search_config.py
+++ b/src/local_deep_research/config/search_config.py
@@ -32,7 +32,11 @@ def get_search_snippets_only_setting(username=None, settings_snapshot=None):
# Expose get_search function
def get_search(
- search_tool=None, llm_instance=None, username=None, settings_snapshot=None
+ search_tool=None,
+ llm_instance=None,
+ username=None,
+ settings_snapshot=None,
+ programmatic_mode=False,
):
"""
Helper function to get search engine
@@ -42,6 +46,7 @@ def get_search(
llm_instance: Override the LLM instance
username: Optional username for thread context (e.g., background research threads)
settings_snapshot: Settings snapshot from thread context
+ programmatic_mode: If True, disables database operations and metrics tracking
"""
# Use specified tool or default from settings
@@ -123,7 +128,9 @@ def get_search(
# Create search engine
search_engine = factory_get_search(
- settings_snapshot=settings_snapshot, **params
+ settings_snapshot=settings_snapshot,
+ programmatic_mode=programmatic_mode,
+ **params,
)
# Log the created engine type
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index a3abc9c11e..849f9f08f1 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -75,6 +75,7 @@ class AdvancedSearchSystem:
settings_snapshot: dict | None = None,
research_id: str | None = None,
research_context: dict | None = None,
+ programmatic_mode: bool = False,
):
"""Initialize the advanced search system.
@@ -110,6 +111,8 @@ class AdvancedSearchSystem:
each iteration. Will be read from the settings if not specified.
use_atomic_facts: Whether to use atomic fact decomposition for
complex queries when using the source-based strategy.
+ programmatic_mode: If True, disables database operations and metrics tracking.
+ This is useful for running searches without database dependencies.
"""
# Store research context for strategies
@@ -124,8 +127,11 @@ class AdvancedSearchSystem:
# Store settings snapshot
self.settings_snapshot = settings_snapshot or {}
+ # Store programmatic mode
+ self.programmatic_mode = programmatic_mode
+
# Log if running in programmatic mode
- if self.settings_snapshot.get("programmatic_mode", False):
+ if self.programmatic_mode:
logger.warning(
"Running in programmatic mode - database operations and metrics tracking disabled. "
"Rate limiting, search metrics, and persistence features will not be available."
diff --git a/src/local_deep_research/web_search_engines/engines/meta_search_engine.py b/src/local_deep_research/web_search_engines/engines/meta_search_engine.py
index 7790ff4d20..0e1fb7ef51 100644
--- a/src/local_deep_research/web_search_engines/engines/meta_search_engine.py
+++ b/src/local_deep_research/web_search_engines/engines/meta_search_engine.py
@@ -24,6 +24,7 @@ class MetaSearchEngine(BaseSearchEngine):
max_filtered_results: Optional[int] = None,
engine_selection_callback=None,
settings_snapshot: Optional[Dict[str, Any]] = None,
+ programmatic_mode: bool = False,
**kwargs,
):
"""
@@ -36,6 +37,7 @@ class MetaSearchEngine(BaseSearchEngine):
max_engines_to_try: Maximum number of engines to try before giving up
max_filtered_results: Maximum number of results to keep after filtering
settings_snapshot: Settings snapshot for thread context
+ programmatic_mode: If True, disables database operations and metrics tracking
**kwargs: Additional parameters (ignored but accepted for compatibility)
"""
# Initialize the BaseSearchEngine with the LLM, max_filtered_results, and max_results
@@ -43,6 +45,8 @@ class MetaSearchEngine(BaseSearchEngine):
llm=llm,
max_filtered_results=max_filtered_results,
max_results=max_results,
+ settings_snapshot=settings_snapshot,
+ programmatic_mode=programmatic_mode,
)
self.use_api_key_services = use_api_key_services
@@ -509,6 +513,7 @@ Example output: searxng,wikipedia,brave"""
engine = create_search_engine(
engine_name,
settings_snapshot=self.settings_snapshot,
+ programmatic_mode=self.programmatic_mode,
**common_params,
)
except Exception:
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_local_all.py b/src/local_deep_research/web_search_engines/engines/search_engine_local_all.py
index 0dce0ebc1b..adec1d59d3 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_local_all.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_local_all.py
@@ -24,6 +24,8 @@ class LocalAllSearchEngine(BaseSearchEngine):
llm: Optional[BaseLLM] = None,
max_results: int = 10,
max_filtered_results: Optional[int] = None,
+ settings_snapshot: Optional[Dict[str, Any]] = None,
+ programmatic_mode: bool = False,
**kwargs,
):
"""
@@ -33,6 +35,8 @@ class LocalAllSearchEngine(BaseSearchEngine):
llm: Language model for relevance filtering
max_results: Maximum number of search results
max_filtered_results: Maximum results after filtering
+ settings_snapshot: Settings snapshot for thread context
+ programmatic_mode: If True, disables database operations and metrics tracking
**kwargs: Additional parameters passed to LocalSearchEngine instances
"""
# Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
@@ -40,6 +44,8 @@ class LocalAllSearchEngine(BaseSearchEngine):
llm=llm,
max_filtered_results=max_filtered_results,
max_results=max_results,
+ settings_snapshot=settings_snapshot,
+ programmatic_mode=programmatic_mode,
)
# Find all local collection search engines
@@ -52,6 +58,8 @@ class LocalAllSearchEngine(BaseSearchEngine):
collection_id,
llm=llm,
max_filtered_results=max_filtered_results,
+ settings_snapshot=settings_snapshot,
+ programmatic_mode=programmatic_mode,
)
engine = cast(LocalSearchEngine, engine)
diff --git a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
index 979ee70140..9aa64056db 100644
--- a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
+++ b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
@@ -47,71 +47,43 @@ class AdaptiveRateLimitTracker:
Persists learned patterns to the main application database using SQLAlchemy.
"""
- def __init__(self, settings_snapshot=None):
+ def __init__(self, settings_snapshot=None, programmatic_mode=False):
self.settings_snapshot = settings_snapshot or {}
- self.programmatic_mode = self.settings_snapshot.get(
- "programmatic_mode", False
- )
-
- # Try to get settings, with explicit fallback for programmatic mode
- try:
- self.memory_window = int(
- get_setting_from_snapshot(
- "rate_limiting.memory_window",
- settings_snapshot=self.settings_snapshot,
- )
- )
- except NoSettingsContextError:
- self.memory_window = 100 # Explicit default
-
- try:
- self.exploration_rate = float(
- get_setting_from_snapshot(
- "rate_limiting.exploration_rate",
- settings_snapshot=self.settings_snapshot,
- )
- )
- except NoSettingsContextError:
- self.exploration_rate = 0.1 # Explicit default
+ self.programmatic_mode = programmatic_mode
- try:
- self.learning_rate = float(
- get_setting_from_snapshot(
- "rate_limiting.learning_rate",
+ # Helper function to get settings with defaults
+ def get_setting_or_default(key, default, type_fn=None):
+ try:
+ value = get_setting_from_snapshot(
+ key,
settings_snapshot=self.settings_snapshot,
)
- )
- except NoSettingsContextError:
- self.learning_rate = 0.3 # Explicit default
+ return type_fn(value) if type_fn else value
+ except NoSettingsContextError:
+ return default
- try:
- self.decay_per_day = float(
- get_setting_from_snapshot(
- "rate_limiting.decay_per_day",
- settings_snapshot=self.settings_snapshot,
- )
- )
- except NoSettingsContextError:
- self.decay_per_day = 0.95 # Explicit default
+ # Get settings with explicit defaults
+ self.memory_window = get_setting_or_default(
+ "rate_limiting.memory_window", 100, int
+ )
+ self.exploration_rate = get_setting_or_default(
+ "rate_limiting.exploration_rate", 0.1, float
+ )
+ self.learning_rate = get_setting_or_default(
+ "rate_limiting.learning_rate", 0.3, float
+ )
+ self.decay_per_day = get_setting_or_default(
+ "rate_limiting.decay_per_day", 0.95, float
+ )
- try:
- self.enabled = bool(
- get_setting_from_snapshot(
- "rate_limiting.enabled",
- settings_snapshot=self.settings_snapshot,
- )
- )
- except NoSettingsContextError:
- # In programmatic mode, default to disabled
- self.enabled = not self.programmatic_mode # Explicit default
+ # In programmatic mode, default to disabled
+ self.enabled = get_setting_or_default(
+ "rate_limiting.enabled",
+ not self.programmatic_mode, # Default based on mode
+ bool,
+ )
- try:
- profile = get_setting_from_snapshot(
- "rate_limiting.profile",
- settings_snapshot=self.settings_snapshot,
- )
- except NoSettingsContextError:
- profile = "balanced" # Explicit default
+ profile = get_setting_or_default("rate_limiting.profile", "balanced")
if self.programmatic_mode and self.enabled:
logger.info(
@@ -187,23 +159,20 @@ class AdaptiveRateLimitTracker:
def _ensure_estimates_loaded(self) -> None:
"""Load estimates from user's encrypted database if not already loaded."""
- if self._estimates_loaded:
- return
-
- # Skip in programmatic mode
- if self.programmatic_mode:
- self._estimates_loaded = True
+ # Early return if already loaded or should skip
+ if self._estimates_loaded or self.programmatic_mode:
+ if not self._estimates_loaded:
+ self._estimates_loaded = True
return
# Get database imports
db_imports = _get_db_imports()
- if not db_imports:
- # Database not available
- self._estimates_loaded = True
- return
+ RateLimitEstimate = (
+ db_imports.get("RateLimitEstimate") if db_imports else None
+ )
- RateLimitEstimate = db_imports.get("RateLimitEstimate")
- if not RateLimitEstimate:
+ if not db_imports or not RateLimitEstimate:
+ # Database not available
self._estimates_loaded = True
return
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 e923960128..bc5561322d 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
@@ -46,6 +46,7 @@ class BaseSearchEngine(ABC):
content_filters: List[BaseFilter] | None = None,
search_snippets_only: bool = True, # New parameter with default
settings_snapshot: Optional[Dict[str, Any]] = None,
+ programmatic_mode: bool = False,
**kwargs,
):
"""
@@ -61,6 +62,7 @@ class BaseSearchEngine(ABC):
produced by the search engine, after relevancy checks.
search_snippets_only: Whether to return only snippets or full content
settings_snapshot: Settings snapshot for configuration
+ programmatic_mode: If True, disables database operations and uses memory-only tracking
**kwargs: Additional engine-specific parameters
"""
if max_filtered_results is None:
@@ -85,15 +87,17 @@ 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.settings_snapshot.get("programmatic_mode", False):
+ if self.programmatic_mode:
from .rate_limiting.tracker import AdaptiveRateLimitTracker
self.rate_tracker = AdaptiveRateLimitTracker(
- settings_snapshot=self.settings_snapshot
+ settings_snapshot=self.settings_snapshot,
+ programmatic_mode=self.programmatic_mode,
)
else:
self.rate_tracker = get_tracker()
@@ -169,7 +173,7 @@ class BaseSearchEngine(ABC):
"""
# Track search call for metrics (if available and not in programmatic mode)
tracker = None
- if not self.settings_snapshot.get("programmatic_mode", False):
+ if not self.programmatic_mode:
try:
from ..metrics.search_tracker import get_search_tracker
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 d69ec96b3c..794dabe1c8 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
@@ -14,6 +14,7 @@ def create_search_engine(
llm=None,
username: str = None,
settings_snapshot: Dict[str, Any] = None,
+ programmatic_mode: bool = False,
**kwargs,
) -> Optional[BaseSearchEngine]:
"""
@@ -22,6 +23,7 @@ def create_search_engine(
Args:
engine_name: Name of the search engine to create
llm: Language model instance (required for some engines like meta)
+ programmatic_mode: If True, disables database operations and metrics tracking
**kwargs: Additional parameters to override defaults
Returns:
@@ -184,6 +186,10 @@ def create_search_engine(
if "settings_snapshot" in engine_init_params[1:] and settings_snapshot:
filtered_params["settings_snapshot"] = settings_snapshot
+ # Pass programmatic_mode if the engine accepts it
+ if "programmatic_mode" in engine_init_params[1:]:
+ filtered_params["programmatic_mode"] = programmatic_mode
+
# Add LLM if required
if engine_config.get("requires_llm", False):
filtered_params["llm"] = llm
@@ -397,6 +403,7 @@ def get_search(
search_language: str = "English",
max_filtered_results: Optional[int] = None,
settings_snapshot: Dict[str, Any] = None,
+ programmatic_mode: bool = False,
):
"""
Get search tool instance based on the provided parameters.
@@ -411,6 +418,7 @@ def get_search(
search_snippets_only: Whether to return just snippets (vs. full content)
search_language: Language for search results
max_filtered_results: Maximum number of results to keep after filtering
+ programmatic_mode: If True, disables database operations and metrics tracking
Returns:
Initialized search engine instance
@@ -451,7 +459,10 @@ def get_search(
logger.info(f"Params being passed to create_search_engine: {params}")
engine = create_search_engine(
- search_tool, settings_snapshot=settings_snapshot, **params
+ search_tool,
+ settings_snapshot=settings_snapshot,
+ programmatic_mode=programmatic_mode,
+ **params,
)
# Add debugging to check if engine is None
diff --git a/tests/programmatic_access/test_programmatic_access.py b/tests/programmatic_access/test_programmatic_access.py
index cf23f213b3..c65db9bb63 100644
--- a/tests/programmatic_access/test_programmatic_access.py
+++ b/tests/programmatic_access/test_programmatic_access.py
@@ -16,22 +16,25 @@ def test_import_without_database():
llm = Mock()
search = Mock()
- # Create settings snapshot with programmatic_mode flag
+ # Create settings snapshot without programmatic_mode
settings_snapshot = {
- "programmatic_mode": True,
"search.iterations": 1,
"search.questions_per_iteration": 2,
"search.strategy": "direct",
}
+ # Pass programmatic_mode as explicit parameter
system = AdvancedSearchSystem(
- llm=llm, search=search, settings_snapshot=settings_snapshot
+ llm=llm,
+ search=search,
+ settings_snapshot=settings_snapshot,
+ programmatic_mode=True,
)
assert system is not None
assert system.model == llm
assert system.search == search
- assert system.settings_snapshot["programmatic_mode"] is True
+ assert system.programmatic_mode is True
def test_analyze_topic_without_database():
@@ -56,17 +59,19 @@ def test_analyze_topic_without_database():
}
]
- # Create settings snapshot with programmatic_mode
+ # Create settings snapshot without programmatic_mode
settings_snapshot = {
- "programmatic_mode": True,
"search.iterations": 1,
"search.questions_per_iteration": 2,
"search.strategy": "direct",
}
- # Create system
+ # Create system with programmatic_mode as parameter
system = AdvancedSearchSystem(
- llm=llm, search=search, settings_snapshot=settings_snapshot
+ llm=llm,
+ search=search,
+ settings_snapshot=settings_snapshot,
+ programmatic_mode=True,
)
# Should be able to call analyze_topic
@@ -130,9 +135,8 @@ def test_search_with_retriever():
llm = Mock()
llm.invoke.return_value = Mock(content="Summary about machine learning.")
- # Create settings with programmatic_mode
+ # Create settings without programmatic_mode
settings_snapshot = {
- "programmatic_mode": True,
"search.iterations": 1,
"search.strategy": "direct",
}
@@ -140,9 +144,12 @@ def test_search_with_retriever():
# Create search wrapper with settings
search = SimpleRetrieverWrapper(retriever, settings_snapshot)
- # Create system
+ # Create system with programmatic_mode as parameter
system = AdvancedSearchSystem(
- llm=llm, search=search, settings_snapshot=settings_snapshot
+ llm=llm,
+ search=search,
+ settings_snapshot=settings_snapshot,
+ programmatic_mode=True,
)
# Run a search