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: Reorganize programmatic examples and add debug logging

LearningCircuit7f70c03d17bb
diff --git a/examples/programmatic_access/README.md b/examples/api_usage/programmatic/README.md
similarity index 100%
rename from examples/programmatic_access/README.md
rename to examples/api_usage/programmatic/README.md
diff --git a/examples/api_usage/programmatic/custom_llm_retriever_example.py b/examples/api_usage/programmatic/custom_llm_retriever_example.py
new file mode 100644
index 0000000000..5e85f6a3ef
--- /dev/null
+++ b/examples/api_usage/programmatic/custom_llm_retriever_example.py
@@ -0,0 +1,204 @@
+#!/usr/bin/env python3
+"""
+Example of using a custom LLM with a custom retriever in Local Deep Research.
+
+This demonstrates how to integrate your own LLM implementation and custom
+retrieval system for programmatic access.
+"""
+
+from typing import List, Dict
+from langchain_ollama import ChatOllama
+from langchain.schema import Document
+from langchain_community.vectorstores import FAISS
+from langchain_community.embeddings import OllamaEmbeddings
+
+# Import the search system
+from local_deep_research.search_system import AdvancedSearchSystem
+
+# Re-enable logging after import
+from loguru import logger
+import sys
+
+logger.remove()
+logger.add(sys.stderr, level="INFO", format="{time} {level} {message}")
+logger.enable("local_deep_research")
+
+
+class CustomRetriever:
+ """Custom retriever that can fetch from multiple sources."""
+
+ def __init__(self):
+ # Initialize with sample documents for demonstration
+ self.documents = [
+ {
+ "content": "Quantum computing uses quantum bits (qubits) that can exist in superposition, "
+ "allowing parallel computation of multiple states simultaneously.",
+ "title": "Quantum Computing Fundamentals",
+ "source": "quantum_basics.pdf",
+ "metadata": {"topic": "quantum", "year": 2024},
+ },
+ {
+ "content": "Machine learning algorithms can be categorized into supervised, unsupervised, "
+ "and reinforcement learning approaches, each suited for different tasks.",
+ "title": "ML Algorithm Categories",
+ "source": "ml_overview.pdf",
+ "metadata": {"topic": "ml", "year": 2024},
+ },
+ {
+ "content": "Neural networks are inspired by biological neurons and consist of interconnected "
+ "nodes that process information through weighted connections.",
+ "title": "Neural Network Architecture",
+ "source": "nn_architecture.pdf",
+ "metadata": {"topic": "neural_networks", "year": 2023},
+ },
+ {
+ "content": "Natural language processing enables computers to understand, interpret, and "
+ "generate human language, powering applications like chatbots and translation.",
+ "title": "NLP Applications",
+ "source": "nlp_apps.pdf",
+ "metadata": {"topic": "nlp", "year": 2024},
+ },
+ ]
+
+ # Create embeddings for similarity search
+ logger.info("Initializing custom retriever with embeddings...")
+ self.embeddings = OllamaEmbeddings(model="nomic-embed-text")
+
+ # Create vector store from documents
+ docs = [
+ Document(
+ page_content=doc["content"],
+ metadata={
+ "title": doc["title"],
+ "source": doc["source"],
+ **doc["metadata"],
+ },
+ )
+ for doc in self.documents
+ ]
+ self.vectorstore = FAISS.from_documents(docs, self.embeddings)
+
+ def retrieve(self, query: str, k: int = 3) -> List[Dict]:
+ """Custom retrieval logic."""
+ logger.info(f"Custom Retriever: Searching for '{query}'")
+
+ # Use vector similarity search
+ similar_docs = self.vectorstore.similarity_search(query, k=k)
+
+ # Convert to expected format
+ results = []
+ for i, doc in enumerate(similar_docs):
+ results.append(
+ {
+ "title": doc.metadata.get("title", f"Document {i + 1}"),
+ "link": doc.metadata.get("source", "custom_source"),
+ "snippet": doc.page_content[:150] + "...",
+ "full_content": doc.page_content,
+ "rank": i + 1,
+ "metadata": doc.metadata,
+ }
+ )
+
+ logger.info(
+ f"Custom Retriever: Found {len(results)} relevant documents"
+ )
+ return results
+
+
+class CustomSearchEngine:
+ """Adapter to integrate custom retriever with the search system."""
+
+ def __init__(self, retriever: CustomRetriever, settings_snapshot=None):
+ self.retriever = retriever
+ self.settings_snapshot = settings_snapshot or {}
+
+ def run(self, query: str, research_context=None) -> List[Dict]:
+ """Execute search using custom retriever."""
+ return self.retriever.retrieve(query, k=5)
+
+
+def main():
+ """Demonstrate custom LLM and retriever integration."""
+ print("=== Custom LLM and Retriever Example ===\n")
+
+ # 1. Create custom LLM (just using regular Ollama for simplicity)
+ print("1. Initializing LLM...")
+ llm = ChatOllama(model="gemma3:12b", temperature=0.7)
+
+ # 2. Create custom retriever
+ print("2. Setting up custom retriever...")
+ custom_retriever = CustomRetriever()
+
+ # 3. Create settings for programmatic mode
+ settings = {
+ "programmatic_mode": True, # Essential for avoiding database dependencies
+ "search.iterations": 2,
+ "search.questions_per_iteration": 3,
+ "search.strategy": "source-based",
+ "rate_limiting.enabled": False, # Disable rate limiting for custom setup
+ }
+
+ # 4. Create search engine adapter
+ print("3. Creating search engine adapter...")
+ search_engine = CustomSearchEngine(custom_retriever, settings)
+
+ # 5. Initialize the search system
+ print("4. Initializing AdvancedSearchSystem with custom components...")
+ search_system = AdvancedSearchSystem(
+ llm=llm, search=search_engine, settings_snapshot=settings
+ )
+
+ # 6. Run research queries
+ queries = [
+ "How do quantum computers differ from classical computers?",
+ "What are the main types of machine learning algorithms?",
+ ]
+
+ for query in queries:
+ print(f"\n{'=' * 60}")
+ print(f"Research Query: {query}")
+ print("=" * 60)
+
+ result = search_system.analyze_topic(query)
+
+ # Display results
+ print("\n=== FINDINGS ===")
+ print(result["formatted_findings"])
+
+ # Show metadata
+ print("\n=== SEARCH METADATA ===")
+ print(f"• Total findings: {len(result['findings'])}")
+ print(f"• Iterations: {result['iterations']}")
+
+ # Get actual sources from all_links_of_system or search_results
+ all_links = result.get("all_links_of_system", [])
+ for finding in result.get("findings", []):
+ if "search_results" in finding and finding["search_results"]:
+ all_links = finding["search_results"]
+ break
+
+ print(f"• Sources found: {len(all_links)}")
+ if all_links and len(all_links) > 0:
+ print("\n=== SOURCES ===")
+ for i, link in enumerate(all_links[:5], 1): # Show first 5
+ if isinstance(link, dict):
+ title = link.get("title", "No title")
+ url = link.get("link", link.get("source", "Unknown"))
+ print(f" [{i}] {title}")
+ print(f" URL: {url}")
+
+ # Show generated questions
+ if result.get("questions_by_iteration"):
+ print("\n=== RESEARCH QUESTIONS GENERATED ===")
+ for iteration, questions in result[
+ "questions_by_iteration"
+ ].items():
+ print(f"\nIteration {iteration}:")
+ for q in questions[:3]: # Show first 3 questions
+ print(f" • {q}")
+
+ print("\n✓ Custom LLM and Retriever integration successful!")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/programmatic_access/example_with_ollama.py b/examples/api_usage/programmatic/example_with_ollama.py
similarity index 88%
rename from examples/programmatic_access/example_with_ollama.py
rename to examples/api_usage/programmatic/example_with_ollama.py
index 5c6c703837..ea86a9816b 100644
--- a/examples/programmatic_access/example_with_ollama.py
+++ b/examples/api_usage/programmatic/example_with_ollama.py
@@ -130,6 +130,22 @@ def main():
f"Questions generated: {sum(len(qs) for qs in result['questions_by_iteration'].values())}"
)
+ # Show actual sources
+ all_links = result.get("all_links_of_system", [])
+ for finding in result.get("findings", []):
+ if "search_results" in finding and finding["search_results"]:
+ all_links = finding["search_results"]
+ break
+
+ if all_links:
+ print(f"\n=== SOURCES (showing first 5 of {len(all_links)}) ===")
+ for i, link in enumerate(all_links[:5], 1):
+ if isinstance(link, dict):
+ title = link.get("title", "No title")
+ url = link.get("link", link.get("source", "local"))
+ print(f"[{i}] {title}")
+ print(f" URL: {url}")
+
# Show the questions that were generated
print("\n=== QUESTIONS BY ITERATION ===")
for iteration, questions in result["questions_by_iteration"].items():
diff --git a/examples/programmatic_access/minimal_working_example.py b/examples/api_usage/programmatic/minimal_working_example.py
similarity index 98%
rename from examples/programmatic_access/minimal_working_example.py
rename to examples/api_usage/programmatic/minimal_working_example.py
index 5ddb2cdb5b..37b15578b3 100644
--- a/examples/programmatic_access/minimal_working_example.py
+++ b/examples/api_usage/programmatic/minimal_working_example.py
@@ -49,7 +49,7 @@ def main():
# 1. Create LLM
print("1. Creating Ollama LLM...")
- llm = ChatOllama(model="mistral:latest")
+ llm = ChatOllama(model="gemma3:12b")
# 2. Create minimal search engine
print("2. Creating minimal search engine...")
diff --git a/examples/api_usage/programmatic/quick_summary_example.py b/examples/api_usage/programmatic/quick_summary_example.py
new file mode 100644
index 0000000000..c84defce24
--- /dev/null
+++ b/examples/api_usage/programmatic/quick_summary_example.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python3
+"""
+Quick topic summary using SearXNG.
+
+Simplest example of getting a quick summary from web search.
+"""
+
+from langchain_ollama import ChatOllama
+from local_deep_research.search_system import AdvancedSearchSystem
+from local_deep_research.web_search_engines.engines.search_engine_searxng import (
+ SearXNGSearchEngine,
+)
+
+
+def main():
+ print("=== Quick Topic Summary with SearXNG ===\n")
+
+ # Setup LLM
+ llm = ChatOllama(model="gemma3:12b", temperature=0)
+
+ # Configure for quick search
+ settings = {
+ "programmatic_mode": True,
+ "search.iterations": 1,
+ "search.questions_per_iteration": 2,
+ "search_engines.searxng.base_url": "http://localhost:8080",
+ }
+
+ # Create SearXNG search engine
+ search = SearXNGSearchEngine(settings_snapshot=settings)
+
+ # Create system
+ system = AdvancedSearchSystem(
+ llm=llm,
+ search=search,
+ settings_snapshot=settings,
+ strategy_name="source-based", # Use source-based for quick summary
+ )
+
+ # Get quick summary
+ topic = "Latest AI developments 2024"
+ print(f"Researching: {topic}\n")
+
+ result = system.analyze_topic(topic)
+
+ print("Summary:")
+ print(result["current_knowledge"])
+
+ print("\n=== SOURCES ===")
+ # Get sources from all_links_of_system which contains the actual search results
+ all_links = result.get("all_links_of_system", [])
+
+ # Also check findings for search_results
+ for finding in result.get("findings", []):
+ if "search_results" in finding and finding["search_results"]:
+ all_links = finding["search_results"]
+ break
+
+ if all_links:
+ for i, link in enumerate(all_links[:10], 1): # Show first 10 sources
+ if isinstance(link, dict):
+ title = link.get("title", "No title")
+ url = link.get("link", link.get("url", "Unknown"))
+ print(f"[{i}] {title}")
+ print(f" URL: {url}")
+ else:
+ print("No sources found in results")
+
+ print(f"\nTotal sources: {len(all_links)}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/api_usage/programmatic/searxng_example.py b/examples/api_usage/programmatic/searxng_example.py
new file mode 100644
index 0000000000..9be7fd07a1
--- /dev/null
+++ b/examples/api_usage/programmatic/searxng_example.py
@@ -0,0 +1,173 @@
+#!/usr/bin/env python3
+"""
+Example of using SearXNG search engine with Local Deep Research.
+
+This demonstrates how to use SearXNG for web search in programmatic mode.
+Note: Requires a running SearXNG instance.
+"""
+
+import os
+from langchain_ollama import ChatOllama
+from local_deep_research.search_system import AdvancedSearchSystem
+from local_deep_research.web_search_engines.engines.search_engine_searxng import (
+ SearXNGSearchEngine,
+)
+
+# Re-enable logging
+from loguru import logger
+import sys
+
+logger.remove()
+logger.add(sys.stderr, level="INFO", format="{time} {level} {message}")
+logger.enable("local_deep_research")
+
+
+def main():
+ """Demonstrate using SearXNG with Local Deep Research."""
+ print("=== SearXNG Search Engine Example ===\n")
+
+ # Check if SearXNG URL is configured
+ searxng_url = os.getenv("SEARXNG_URL", "http://localhost:8080")
+ print(f"Using SearXNG instance at: {searxng_url}")
+ print(
+ "(Set SEARXNG_URL environment variable to use a different instance)\n"
+ )
+
+ # 1. Create LLM
+ print("1. Setting up Ollama LLM...")
+ llm = ChatOllama(model="gemma3:12b", temperature=0.3)
+
+ # 2. Configure settings for programmatic mode
+ settings = {
+ "programmatic_mode": True,
+ "search.iterations": 2,
+ "search.questions_per_iteration": 3,
+ "search.strategy": "source-based",
+ "rate_limiting.enabled": False, # Disable rate limiting for demo
+ # SearXNG specific settings
+ "search_engines.searxng.base_url": searxng_url,
+ "search_engines.searxng.timeout": 30,
+ "search_engines.searxng.categories": ["general", "science"],
+ "search_engines.searxng.engines": ["google", "duckduckgo", "bing"],
+ "search_engines.searxng.language": "en",
+ "search_engines.searxng.time_range": "", # all time
+ "search_engines.searxng.safesearch": 0, # 0=off, 1=moderate, 2=strict
+ }
+
+ # 3. Create SearXNG search engine
+ print("2. Initializing SearXNG search engine...")
+ try:
+ search_engine = SearXNGSearchEngine(settings_snapshot=settings)
+
+ # Test the connection
+ print(" Testing SearXNG connection...")
+ test_results = search_engine.run("test query", research_context={})
+ if test_results:
+ print(
+ f" ✓ SearXNG is working! Got {len(test_results)} test results."
+ )
+ else:
+ print(" ⚠ SearXNG returned no results for test query.")
+ except Exception as e:
+ print(f"\n⚠ Error connecting to SearXNG: {e}")
+ print("\nPlease ensure SearXNG is running. You can start it with:")
+ print(" docker run -p 8888:8080 searxng/searxng")
+ print("\nFalling back to mock search engine for demonstration...")
+
+ # Fallback to mock search engine
+ class MockSearchEngine:
+ def __init__(self, settings_snapshot=None):
+ self.settings_snapshot = settings_snapshot or {}
+
+ def run(self, query, research_context=None):
+ return [
+ {
+ "title": f"Result for: {query}",
+ "link": "https://example.com/result",
+ "snippet": f"This is a mock result for the query: {query}. "
+ "In a real scenario, SearXNG would provide actual web search results.",
+ "full_content": "Full content would be fetched here...",
+ "rank": 1,
+ }
+ ]
+
+ search_engine = MockSearchEngine(settings)
+
+ # 4. Create the search system
+ print("3. Creating AdvancedSearchSystem...")
+ search_system = AdvancedSearchSystem(
+ llm=llm, search=search_engine, settings_snapshot=settings
+ )
+
+ # 5. Run research queries
+ queries = [
+ "What are the latest developments in quantum computing in 2024?",
+ "How does CRISPR gene editing technology work?",
+ ]
+
+ for query in queries:
+ print(f"\n{'=' * 60}")
+ print(f"Research Query: {query}")
+ print("=" * 60)
+
+ try:
+ result = search_system.analyze_topic(query)
+
+ # Display results
+ print("\n=== RESEARCH FINDINGS ===")
+ if result.get("formatted_findings"):
+ print(result["formatted_findings"])
+ else:
+ print(
+ "Summary:", result.get("current_knowledge", "No findings")
+ )
+
+ # Show metadata
+ print("\n=== METADATA ===")
+ print(f"• Iterations completed: {result.get('iterations', 0)}")
+ print(f"• Total findings: {len(result.get('findings', []))}")
+
+ # Show search sources from all_links_of_system or search_results in findings
+ all_links = result.get("all_links_of_system", [])
+
+ # Also check findings for search_results
+ for finding in result.get("findings", []):
+ if "search_results" in finding and finding["search_results"]:
+ all_links = finding["search_results"]
+ break
+
+ if all_links:
+ print(f"• Sources found: {len(all_links)}")
+ for i, link in enumerate(
+ all_links[:5], 1
+ ): # Show first 5 sources
+ if isinstance(link, dict):
+ title = link.get("title", "No title")
+ url = link.get("link", "Unknown")
+ print(f" [{i}] {title}")
+ print(f" {url}")
+
+ # Show generated questions
+ if result.get("questions_by_iteration"):
+ print("\n=== RESEARCH QUESTIONS ===")
+ for iteration, questions in result[
+ "questions_by_iteration"
+ ].items():
+ print(f"Iteration {iteration}:")
+ for q in questions[
+ :2
+ ]: # Show first 2 questions per iteration
+ print(f" • {q}")
+
+ except Exception as e:
+ logger.exception("Error during research")
+ print(f"\n⚠ Error: {e}")
+
+ print("\n✓ SearXNG integration example completed!")
+ print(
+ "\nNote: For best results, ensure SearXNG is properly configured with multiple search engines."
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/programmatic_access/test_direct_import.py b/examples/api_usage/programmatic/test_direct_import.py
similarity index 100%
rename from examples/programmatic_access/test_direct_import.py
rename to examples/api_usage/programmatic/test_direct_import.py
diff --git a/examples/programmatic_access/test_logging.py b/examples/programmatic_access/test_logging.py
deleted file mode 100644
index 12bda2c329..0000000000
--- a/examples/programmatic_access/test_logging.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/env python3
-"""Test to verify logging messages in programmatic mode."""
-
-import sys
-from loguru import logger
-from langchain_ollama import ChatOllama
-from local_deep_research.search_system import AdvancedSearchSystem
-
-# Enable warning logging to see important messages
-logger.remove()
-logger.add(sys.stderr, level="WARNING")
-
-# Enable logging for local_deep_research AFTER configuring logger
-logger.enable("local_deep_research")
-
-
-class MinimalSearchEngine:
- """Minimal search engine that returns hardcoded results."""
-
- def __init__(self, settings_snapshot=None):
- self.settings_snapshot = settings_snapshot or {}
-
- def run(self, query, research_context=None):
- """Return some fake search results."""
- return [
- {
- "title": "Test Result",
- "link": "https://example.com/test",
- "snippet": "Test snippet...",
- "full_content": "Test content...",
- "rank": 1,
- }
- ]
-
-
-def main():
- print("=== Testing Programmatic Mode Logging ===\n")
-
- # Create components
- llm = ChatOllama(model="mistral:latest")
-
- # Settings with programmatic_mode enabled
- settings = {
- "programmatic_mode": True,
- "search.iterations": 1,
- "search.strategy": "direct",
- }
-
- search = MinimalSearchEngine(settings)
-
- print("Creating AdvancedSearchSystem with programmatic_mode=True...")
- print("You should see log messages about disabled features:\n")
-
- # This should trigger logging messages
- system = AdvancedSearchSystem(
- llm=llm, search=search, settings_snapshot=settings
- )
-
- print("\nRunning a search (this may trigger additional log messages)...")
- _ = system.analyze_topic("Test query")
-
- print("\n✓ Test complete! Check the log messages above.")
-
-
-if __name__ == "__main__":
- main()
diff --git a/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py b/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py
index 1aef56824e..0df3c0979c 100644
--- a/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py
+++ b/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py
@@ -36,15 +36,20 @@ class CrossEngineFilter(BaseFilter):
# Get max_results from database settings if not provided
if max_results is None:
# Import from thread_settings to avoid database dependencies
- from ...config.thread_settings import get_setting_from_snapshot
+ from ...config.thread_settings import (
+ get_setting_from_snapshot,
+ NoSettingsContextError,
+ )
- max_results = int(
- get_setting_from_snapshot(
- "search.cross_engine_max_results",
- 100,
- settings_snapshot=settings_snapshot,
+ try:
+ max_results = int(
+ get_setting_from_snapshot(
+ "search.cross_engine_max_results",
+ settings_snapshot=settings_snapshot,
+ )
)
- )
+ except NoSettingsContextError:
+ max_results = 100 # Explicit default
self.max_results = max_results
self.default_reorder = default_reorder
self.default_reindex = default_reindex
diff --git a/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py b/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py
index 70f5fb4f46..79e062be1a 100644
--- a/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py
@@ -107,8 +107,8 @@ class BrowseCompEntityStrategy(BaseSearchStrategy):
def __init__(
self,
- model=None,
- search=None,
+ model,
+ search,
all_links_of_system=None,
settings_snapshot=None,
**kwargs,
diff --git a/src/local_deep_research/advanced_search_system/strategies/direct_search_strategy.py b/src/local_deep_research/advanced_search_system/strategies/direct_search_strategy.py
index 5746f8bab3..71da2c971b 100644
--- a/src/local_deep_research/advanced_search_system/strategies/direct_search_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/direct_search_strategy.py
@@ -32,8 +32,8 @@ class DirectSearchStrategy(BaseSearchStrategy):
def __init__(
self,
- search=None,
- model=None,
+ search,
+ model,
citation_handler=None,
include_text_content: bool = True,
use_cross_engine_filter: bool = True,
diff --git a/src/local_deep_research/advanced_search_system/strategies/entity_aware_source_strategy.py b/src/local_deep_research/advanced_search_system/strategies/entity_aware_source_strategy.py
index 8699da8782..b1cd4377af 100644
--- a/src/local_deep_research/advanced_search_system/strategies/entity_aware_source_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/entity_aware_source_strategy.py
@@ -22,8 +22,8 @@ class EntityAwareSourceStrategy(SourceBasedSearchStrategy):
def __init__(
self,
- search=None,
- model=None,
+ search,
+ model,
citation_handler=None,
include_text_content: bool = True,
use_cross_engine_filter: bool = True,
diff --git a/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py b/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py
index b1376d2443..80323bc3f8 100644
--- a/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py
@@ -48,8 +48,8 @@ class FocusedIterationStrategy(BaseSearchStrategy):
def __init__(
self,
- model=None,
- search=None,
+ model,
+ search,
citation_handler=None,
all_links_of_system=None,
max_iterations: int = 8, # OPTIMAL FOR SIMPLEQA: 90%+ accuracy achieved
diff --git a/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py b/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py
index 7509b6fdb0..539d6db5e6 100644
--- a/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py
@@ -24,8 +24,8 @@ class IterDRAGStrategy(BaseSearchStrategy):
def __init__(
self,
- search=None,
- model=None,
+ search,
+ model,
max_iterations=3,
subqueries_per_iteration=2,
all_links_of_system=None,
diff --git a/src/local_deep_research/advanced_search_system/strategies/news_strategy.py b/src/local_deep_research/advanced_search_system/strategies/news_strategy.py
index c3c1bb6503..bdfc333814 100644
--- a/src/local_deep_research/advanced_search_system/strategies/news_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/news_strategy.py
@@ -19,9 +19,7 @@ class NewsAggregationStrategy(BaseSearchStrategy):
Uses single iteration with multiple parallel searches for broad coverage.
"""
- def __init__(
- self, model=None, search=None, all_links_of_system=None, **kwargs
- ):
+ def __init__(self, model, search, all_links_of_system=None, **kwargs):
super().__init__(all_links_of_system=all_links_of_system)
self.model = model
self.search = search
diff --git a/src/local_deep_research/advanced_search_system/strategies/parallel_search_strategy.py b/src/local_deep_research/advanced_search_system/strategies/parallel_search_strategy.py
index 325b6cc54f..a2a5777b36 100644
--- a/src/local_deep_research/advanced_search_system/strategies/parallel_search_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/parallel_search_strategy.py
@@ -26,8 +26,8 @@ class ParallelSearchStrategy(BaseSearchStrategy):
def __init__(
self,
- search=None,
- model=None,
+ search,
+ model,
citation_handler=None,
include_text_content: bool = True,
use_cross_engine_filter: bool = True,
diff --git a/src/local_deep_research/advanced_search_system/strategies/rapid_search_strategy.py b/src/local_deep_research/advanced_search_system/strategies/rapid_search_strategy.py
index fc4de2a8f9..3523384110 100644
--- a/src/local_deep_research/advanced_search_system/strategies/rapid_search_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/rapid_search_strategy.py
@@ -24,8 +24,8 @@ class RapidSearchStrategy(BaseSearchStrategy):
def __init__(
self,
- search=None,
- model=None,
+ search,
+ model,
citation_handler=None,
all_links_of_system=None,
settings_snapshot=None,
diff --git a/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py b/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py
index 4bddc96511..9f4205d40d 100644
--- a/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py
@@ -24,8 +24,8 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
def __init__(
self,
- search=None,
- model=None,
+ search,
+ model,
citation_handler=None,
include_text_content: bool = True,
use_cross_engine_filter: bool = True,
diff --git a/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py b/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
index ea2070b948..456e365ec7 100644
--- a/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
@@ -20,8 +20,8 @@ class StandardSearchStrategy(BaseSearchStrategy):
def __init__(
self,
- search=None,
- model=None,
+ search,
+ model,
citation_handler=None,
all_links_of_system=None,
settings_snapshot=None,
diff --git a/src/local_deep_research/config/search_config.py b/src/local_deep_research/config/search_config.py
index 07fedd07c6..736c822b19 100644
--- a/src/local_deep_research/config/search_config.py
+++ b/src/local_deep_research/config/search_config.py
@@ -108,6 +108,7 @@ def get_search(
logger.info(
f"Search config: tool={tool}, max_results={params['max_results']}, time_period={params['time_period']}"
)
+ logger.info(f"Full params dict: {params}")
# Create search engine
search_engine = factory_get_search(
diff --git a/src/local_deep_research/config/thread_settings.py b/src/local_deep_research/config/thread_settings.py
index aee7e7d4ee..2c53dd7b39 100644
--- a/src/local_deep_research/config/thread_settings.py
+++ b/src/local_deep_research/config/thread_settings.py
@@ -7,6 +7,13 @@ shared across different modules to maintain settings context in threads.
import os
import threading
+
+class NoSettingsContextError(Exception):
+ """Raised when settings context is not available in a thread."""
+
+ pass
+
+
# Shared thread-local storage for settings context
_thread_local = threading.local()
@@ -69,11 +76,7 @@ def get_setting_from_snapshot(
)
return default
- # If no context and we have a default, return it
- if default is not None:
- return default
-
- # If no context and no default, raise an error - threads should never access database directly
- raise RuntimeError(
+ # Always raise the exception - callers should handle it explicitly if they want fallback behavior
+ raise NoSettingsContextError(
f"No settings context available in thread for key '{key}'. All settings must be passed via settings_snapshot."
)
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index 8d3e4790bf..a3abc9c11e 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -63,11 +63,11 @@ class AdvancedSearchSystem:
def __init__(
self,
+ llm: BaseChatModel,
+ search: BaseSearchEngine,
strategy_name: str = "source-based", # Default to comprehensive research strategy
include_text_content: bool = True,
use_cross_engine_filter: bool = True,
- llm: BaseChatModel | None = None,
- search: BaseSearchEngine | None = None,
max_iterations: int | None = None,
questions_per_iteration: int | None = None,
use_atomic_facts: bool = False,
@@ -79,6 +79,8 @@ class AdvancedSearchSystem:
"""Initialize the advanced search system.
Args:
+ llm: LLM to use for the search strategy.
+ search: Search engine to use for queries.
strategy_name: The name of the search strategy to use. Options:
- "standard": Basic iterative search strategy
- "iterdrag": Iterative Dense Retrieval Augmented Generation
@@ -102,9 +104,6 @@ class AdvancedSearchSystem:
include_text_content: If False, only includes metadata and links in search results
use_cross_engine_filter: Whether to filter results across search
engines.
- llm: LLM to use. If not provided, it will use the default one.
- search: Search engine to use. If not provided, it will use the
- default one.
max_iterations: The maximum number of search iterations to
perform. Will be read from the settings if not specified.
questions_per_iteration: The number of questions to include in
@@ -118,21 +117,8 @@ class AdvancedSearchSystem:
self.research_context = research_context
self.username = username
- # Get configuration
- if llm is None:
- raise ValueError(
- "LLM instance is required for programmatic access. "
- "Please provide an LLM instance (e.g., ChatOllama, ChatOpenAI) "
- "via the 'llm' parameter."
- )
+ # Store required components
self.model = llm
-
- if search is None:
- raise ValueError(
- "Search engine instance is required for programmatic access. "
- "Please provide a search engine instance or use a retriever "
- "via the 'search' parameter."
- )
self.search = search
# Store settings snapshot
diff --git a/src/local_deep_research/storage/factory.py b/src/local_deep_research/storage/factory.py
index e86e3a4aae..402b80cc23 100644
--- a/src/local_deep_research/storage/factory.py
+++ b/src/local_deep_research/storage/factory.py
@@ -6,7 +6,10 @@ from loguru import logger
from .base import ReportStorage
from .database_with_file_backup import DatabaseWithFileBackupStorage
-from ..config.thread_settings import get_setting_from_snapshot
+from ..config.thread_settings import (
+ get_setting_from_snapshot,
+ NoSettingsContextError,
+)
def get_report_storage(
@@ -32,11 +35,14 @@ def get_report_storage(
# Determine if file backup should be enabled
if enable_file_backup is None:
- enable_file_backup = get_setting_from_snapshot(
- "report.enable_file_backup",
- False,
- settings_snapshot=settings_snapshot,
- )
+ try:
+ enable_file_backup = get_setting_from_snapshot(
+ "report.enable_file_backup",
+ settings_snapshot=settings_snapshot,
+ )
+ except NoSettingsContextError:
+ # Fall back to default if no settings context
+ enable_file_backup = False
logger.info(
f"Report storage: Database (primary) with file backup {'enabled' if enable_file_backup else 'disabled'}"
diff --git a/src/local_deep_research/utilities/thread_context.py b/src/local_deep_research/utilities/thread_context.py
index f3bcf5c696..496b182558 100644
--- a/src/local_deep_research/utilities/thread_context.py
+++ b/src/local_deep_research/utilities/thread_context.py
@@ -38,8 +38,8 @@ def preserve_research_context(func: Callable) -> Callable:
Use this decorator on functions that will be executed in ThreadPoolExecutor
to ensure the research context (including research_id) is properly propagated.
- In programmatic mode (when settings_snapshot.programmatic_mode is True),
- this decorator does nothing to avoid database dependencies.
+ When metrics are disabled (e.g., in programmatic mode), this decorator
+ safely does nothing to avoid database dependencies.
Example:
@preserve_research_context
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 93b0637271..979ee70140 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
@@ -10,7 +10,11 @@ from typing import Dict, List, Optional, Tuple
from loguru import logger
-from ...config.thread_settings import get_settings_context
+from ...config.thread_settings import (
+ get_settings_context,
+ get_setting_from_snapshot,
+ NoSettingsContextError,
+)
# Lazy imports to avoid database initialization in programmatic mode
_db_imports = None
@@ -49,91 +53,70 @@ class AdaptiveRateLimitTracker:
"programmatic_mode", False
)
- # Try to get settings from thread context first
- settings_context = get_settings_context()
- if settings_context:
- # Use settings from thread context
+ # Try to get settings, with explicit fallback for programmatic mode
+ try:
self.memory_window = int(
- settings_context.get_setting("rate_limiting.memory_window", 100)
+ 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(
- settings_context.get_setting(
- "rate_limiting.exploration_rate", 0.1
+ get_setting_from_snapshot(
+ "rate_limiting.exploration_rate",
+ settings_snapshot=self.settings_snapshot,
)
)
+ except NoSettingsContextError:
+ self.exploration_rate = 0.1 # Explicit default
+
+ try:
self.learning_rate = float(
- settings_context.get_setting("rate_limiting.learning_rate", 0.3)
+ get_setting_from_snapshot(
+ "rate_limiting.learning_rate",
+ settings_snapshot=self.settings_snapshot,
+ )
)
+ except NoSettingsContextError:
+ self.learning_rate = 0.3 # Explicit default
+
+ try:
self.decay_per_day = float(
- settings_context.get_setting(
- "rate_limiting.decay_per_day", 0.95
+ get_setting_from_snapshot(
+ "rate_limiting.decay_per_day",
+ settings_snapshot=self.settings_snapshot,
)
)
+ except NoSettingsContextError:
+ self.decay_per_day = 0.95 # Explicit default
+
+ try:
self.enabled = bool(
- settings_context.get_setting("rate_limiting.enabled", True)
+ get_setting_from_snapshot(
+ "rate_limiting.enabled",
+ settings_snapshot=self.settings_snapshot,
+ )
)
- profile = settings_context.get_setting(
- "rate_limiting.profile", "balanced"
+ except NoSettingsContextError:
+ # In programmatic mode, default to disabled
+ self.enabled = not self.programmatic_mode # Explicit default
+
+ try:
+ profile = get_setting_from_snapshot(
+ "rate_limiting.profile",
+ settings_snapshot=self.settings_snapshot,
)
- else:
- # Fall back to database settings if not in thread (unless in programmatic mode)
- if self.programmatic_mode:
- # Use defaults in programmatic mode
- logger.warning(
- "Rate limiting disabled in programmatic mode - using memory-only tracking without persistence"
- )
- self.memory_window = 100
- self.exploration_rate = 0.1
- self.learning_rate = 0.3
- self.decay_per_day = 0.95
- self.enabled = (
- False # Disable rate limiting in programmatic mode
- )
- profile = "balanced"
- else:
- # Get database imports
- db_imports = _get_db_imports()
- get_setting_from_db_main_thread = db_imports.get(
- "get_setting_from_db_main_thread"
- )
+ except NoSettingsContextError:
+ profile = "balanced" # Explicit default
- if get_setting_from_db_main_thread:
- self.memory_window = int(
- get_setting_from_db_main_thread(
- "rate_limiting.memory_window", 100
- )
- )
- self.exploration_rate = float(
- get_setting_from_db_main_thread(
- "rate_limiting.exploration_rate", 0.1
- )
- )
- self.learning_rate = float(
- get_setting_from_db_main_thread(
- "rate_limiting.learning_rate", 0.3
- )
- )
- self.decay_per_day = float(
- get_setting_from_db_main_thread(
- "rate_limiting.decay_per_day", 0.95
- )
- )
- self.enabled = bool(
- get_setting_from_db_main_thread(
- "rate_limiting.enabled", True
- )
- )
- profile = get_setting_from_db_main_thread(
- "rate_limiting.profile", "balanced"
- )
- else:
- # Database not available, use defaults
- self.memory_window = 100
- self.exploration_rate = 0.1
- self.learning_rate = 0.3
- self.decay_per_day = 0.95
- self.enabled = False
- profile = "balanced"
+ if self.programmatic_mode and self.enabled:
+ logger.info(
+ "Rate limiting enabled in programmatic mode - using memory-only tracking without persistence"
+ )
# Apply rate limiting profile
self._apply_profile(profile)
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 bf8613217f..e765c44f0b 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
@@ -27,6 +27,11 @@ def create_search_engine(
Returns:
Initialized search engine instance or None if creation failed
"""
+ # Debug logging
+ logger.info(
+ f"create_search_engine called with engine_name={engine_name} (type: {type(engine_name)})"
+ )
+
# Check if this is a registered retriever first
retriever = retriever_registry.get(engine_name)
if retriever:
@@ -438,7 +443,7 @@ def get_search(
# Create and return the search engine
logger.info(
- f"Creating search engine for tool: {search_tool} with params: {params.keys()}"
+ f"Creating search engine for tool: {search_tool} (type: {type(search_tool)}) with params: {params.keys()}"
)
engine = create_search_engine(