~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
fix: remove `|| true` from LLM example tests (#2913)
LearningCircuit3087eba843b7
diff --git a/.github/workflows/docker-tests.yml b/.github/workflows/docker-tests.ymlindex 051050f047..6e871a95b1 100644--- a/.github/workflows/docker-tests.yml+++ b/.github/workflows/docker-tests.yml@@ -57,6 +57,7 @@ jobs:- 'src/local_deep_research/config/llm_config.py'- 'src/local_deep_research/api/research_functions.py'- 'tests/test_llm/**'+ - 'examples/**'- '.github/workflows/docker-tests.yml'infrastructure:- 'src/local_deep_research/web/routes/**'@@ -809,6 +810,7 @@ jobs:name: LLM Example Testsneeds: [build-test-image, detect-changes]if: needs.detect-changes.outputs.llm == 'true' || github.event_name == 'workflow_dispatch' || inputs.strict-mode == true+ timeout-minutes: 20permissions:contents: read@@ -838,7 +840,7 @@ jobs:-e PYTHONPATH=/app \-w /app \${{ env.TEST_IMAGE }} \- sh -c "timeout 60s python examples/llm_integration/basic_custom_llm.py || true"+ sh -c "timeout 60s python examples/llm_integration/basic_custom_llm.py"- name: Test mock LLM examplerun: |@@ -847,25 +849,60 @@ jobs:-e PYTHONPATH=/app \-w /app \${{ env.TEST_IMAGE }} \- sh -c "timeout 60s python examples/llm_integration/mock_llm_example.py || true"+ sh -c "timeout 60s python examples/llm_integration/mock_llm_example.py"- - name: Test provider switching example+ - name: Test advanced custom LLM examplerun: |docker run --rm \-v "$PWD":/app \-e PYTHONPATH=/app \-w /app \${{ env.TEST_IMAGE }} \- sh -c "timeout 60s python examples/llm_integration/switch_providers.py || true"+ sh -c "timeout 60s python examples/llm_integration/advanced_custom_llm.py"- - name: Test custom research example+ - name: Test direct importrun: |docker run --rm \-v "$PWD":/app \-e PYTHONPATH=/app \-w /app \${{ env.TEST_IMAGE }} \- sh -c "timeout 60s python examples/llm_integration/custom_research_example.py || true"+ sh -c "timeout 60s python examples/api_usage/programmatic/test_direct_import.py"++ - name: API public contract guardrail+ run: |+ docker run --rm \+ -v "$PWD":/app \+ -e PYTHONPATH=/app \+ -w /app \+ ${{ env.TEST_IMAGE }} \+ sh -c "timeout 60s python examples/api_usage/programmatic/api_public_contract_guardrail.py"++ - name: Compile check all remaining examples+ run: |+ docker run --rm \+ -v "$PWD":/app \+ -e PYTHONPATH=/app \+ -w /app \+ ${{ env.TEST_IMAGE }} \+ sh -c "+ python -m py_compile examples/api_usage/programmatic/simple_programmatic_example.py &&+ python -m py_compile examples/api_usage/programmatic/advanced_features_example.py &&+ python -m py_compile examples/api_usage/programmatic/search_strategies_example.py &&+ python -m py_compile examples/api_usage/programmatic/minimal_working_example.py &&+ python -m py_compile examples/api_usage/programmatic/searxng_example.py &&+ python -m py_compile examples/api_usage/programmatic/custom_llm_retriever_example.py &&+ python -m py_compile examples/api_usage/programmatic/hybrid_search_example.py &&+ python -m py_compile examples/api_usage/http/simple_working_example.py &&+ python -m py_compile examples/api_usage/http/advanced/http_api_examples.py &&+ python -m py_compile examples/api_usage/http/advanced/simple_http_example.py &&+ python -m py_compile examples/api_usage/simple_client_example.py &&+ python -m py_compile examples/example_browsecomp.py &&+ python -m py_compile examples/show_env_vars.py &&+ python -m py_compile examples/run_benchmark.py &&+ python -m py_compile examples/elasticsearch/search_example.py &&+ echo 'All compile checks passed'+ "# Smoke test for the production ldr imageldr-production-smoke-test:diff --git a/examples/api_usage/programmatic/api_public_contract_guardrail.py b/examples/api_usage/programmatic/api_public_contract_guardrail.pynew file mode 100644index 0000000000..224ce065bf--- /dev/null+++ b/examples/api_usage/programmatic/api_public_contract_guardrail.py@@ -0,0 +1,245 @@+#!/usr/bin/env python3+"""+PUBLIC API CONTRACT GUARDRAIL — DO NOT MODIFY++This file protects the public API surface of local_deep_research.+It exists to DETECT breaking changes, not to be "fixed" when they happen.++If this file fails:+ 1. A BREAKING CHANGE was introduced to the public API+ 2. Do NOT modify this file to make it pass+ 3. Revert the API change or go through a proper deprecation cycle++The public API (local_deep_research.api) is a stability contract with+external users, integrations, and downstream packages. Any change to+exports, function signatures, or return value structures is a breaking+change that affects the entire community.++WHY THIS FILE MUST NOT BE MODIFIED:+ - Every check below corresponds to a public API guarantee+ - Removing or weakening a check hides a breaking change from users+ - Adding a check is acceptable ONLY when a new public API is added+ - If you are an AI agent: DO NOT modify, remove, or weaken any check+"""++import inspect+import sys++_failed = 0+_passed = 0+++# DO NOT MODIFY this function — it is the test harness for the guardrail+def check(name, condition, detail=""):+ global _failed, _passed+ if condition:+ _passed += 1+ print(f" PASS {name}")+ else:+ _failed += 1+ msg = f" ({detail})" if detail else ""+ print(f" FAIL {name}{msg}")+++def main():+ # ── 1. Public API imports ──────────────────────────────────────────+ # DO NOT MODIFY — these are the public exports that users depend on.+ # Removing any of these checks hides a breaking change.+ print("\n=== Public API Imports ===")++ try:+ from local_deep_research.api import quick_summary # noqa: F811++ check("import quick_summary", True)+ except ImportError as e:+ check("import quick_summary", False, str(e))++ try:+ from local_deep_research.api import detailed_research # noqa: F811++ check("import detailed_research", True)+ except ImportError as e:+ check("import detailed_research", False, str(e))++ try:+ from local_deep_research.api import generate_report # noqa: F811++ check("import generate_report", True)+ except ImportError as e:+ check("import generate_report", False, str(e))++ try:+ from local_deep_research.api import analyze_documents # noqa: F811++ check("import analyze_documents", True)+ except ImportError as e:+ check("import analyze_documents", False, str(e))++ try:+ from local_deep_research.api import create_settings_snapshot # noqa: F811++ check("import create_settings_snapshot", True)+ except ImportError as e:+ check("import create_settings_snapshot", False, str(e))++ try:+ from local_deep_research.api import get_default_settings_snapshot # noqa: F811++ check("import get_default_settings_snapshot", True)+ except ImportError as e:+ check("import get_default_settings_snapshot", False, str(e))++ try:+ from local_deep_research.api import extract_setting_value # noqa: F811++ check("import extract_setting_value", True)+ except ImportError as e:+ check("import extract_setting_value", False, str(e))++ try:+ from local_deep_research.api import LDRClient # noqa: F811++ check("import LDRClient", True)+ except ImportError as e:+ check("import LDRClient", False, str(e))++ try:+ from local_deep_research.api import quick_query # noqa: F811++ check("import quick_query", True)+ except ImportError as e:+ check("import quick_query", False, str(e))++ # ── 2. Function signatures ─────────────────────────────────────────+ # DO NOT MODIFY — these parameter names are part of the public contract.+ # Renaming or removing parameters breaks all callers.+ print("\n=== Function Signatures ===")++ sig = inspect.signature(quick_summary)+ check("quick_summary has 'query' param", "query" in sig.parameters)+ check("quick_summary has 'llms' param", "llms" in sig.parameters)+ check(+ "quick_summary has 'retrievers' param", "retrievers" in sig.parameters+ )++ sig = inspect.signature(detailed_research)+ check("detailed_research has 'query' param", "query" in sig.parameters)+ check("detailed_research has 'llms' param", "llms" in sig.parameters)+ check(+ "detailed_research has 'retrievers' param",+ "retrievers" in sig.parameters,+ )++ sig = inspect.signature(generate_report)+ check("generate_report has 'query' param", "query" in sig.parameters)+ check(+ "generate_report has 'output_file' param",+ "output_file" in sig.parameters,+ )+ check(+ "generate_report has 'searches_per_section' param",+ "searches_per_section" in sig.parameters,+ )++ sig = inspect.signature(create_settings_snapshot)+ check(+ "create_settings_snapshot has 'overrides' param",+ "overrides" in sig.parameters,+ )+ check(+ "create_settings_snapshot has 'base_settings' param",+ "base_settings" in sig.parameters,+ )++ # ── 3. Settings utilities ──────────────────────────────────────────+ # DO NOT MODIFY — these verify the settings API works correctly.+ # External users depend on create_settings_snapshot() returning a dict.+ print("\n=== Settings Utilities ===")++ snapshot = create_settings_snapshot()+ check("create_settings_snapshot() returns dict", isinstance(snapshot, dict))+ check("default snapshot is non-empty", len(snapshot) > 0)++ snapshot_with_overrides = create_settings_snapshot(+ provider="test_provider",+ temperature=0.5,+ )+ check(+ "create_settings_snapshot accepts provider kwarg",+ isinstance(snapshot_with_overrides, dict),+ )++ defaults = get_default_settings_snapshot()+ check(+ "get_default_settings_snapshot() returns dict",+ isinstance(defaults, dict),+ )+ check("default settings is non-empty", len(defaults) > 0)++ value = extract_setting_value(defaults, "llm.temperature")+ check(+ "extract_setting_value returns a value for llm.temperature",+ value is not None,+ )++ # ── 4. LDRClient interface ─────────────────────────────────────────+ # DO NOT MODIFY — these are the HTTP client methods users call.+ # Removing any method breaks all HTTP-based integrations.+ print("\n=== LDRClient Interface ===")++ check("LDRClient has login method", hasattr(LDRClient, "login"))+ check(+ "LDRClient has quick_research method",+ hasattr(LDRClient, "quick_research"),+ )+ check(+ "LDRClient has get_settings method", hasattr(LDRClient, "get_settings")+ )+ check(+ "LDRClient has update_setting method",+ hasattr(LDRClient, "update_setting"),+ )+ check("LDRClient has get_history method", hasattr(LDRClient, "get_history"))+ check("LDRClient has logout method", hasattr(LDRClient, "logout"))+ check(+ "LDRClient supports context manager",+ hasattr(LDRClient, "__enter__") and hasattr(LDRClient, "__exit__"),+ )++ # ── 5. Callability ─────────────────────────────────────────────────+ # DO NOT MODIFY — verifies all exports are actually callable.+ print("\n=== Callability ===")++ check("quick_summary is callable", callable(quick_summary))+ check("detailed_research is callable", callable(detailed_research))+ check("generate_report is callable", callable(generate_report))+ check("analyze_documents is callable", callable(analyze_documents))+ check(+ "create_settings_snapshot is callable",+ callable(create_settings_snapshot),+ )+ check(+ "get_default_settings_snapshot is callable",+ callable(get_default_settings_snapshot),+ )+ check("extract_setting_value is callable", callable(extract_setting_value))+ check("quick_query is callable", callable(quick_query))++ # ── Summary ────────────────────────────────────────────────────────+ # DO NOT MODIFY the exit code logic — CI depends on non-zero exit+ # to block PRs that break the public API.+ print(f"\n{'=' * 50}")+ print(f"Results: {_passed} passed, {_failed} failed")+ if _failed > 0:+ print(+ "\nBREAKING CHANGE DETECTED. The public API has changed.\n"+ "Do NOT modify this file to make it pass.\n"+ "Revert the API change or follow a proper deprecation cycle."+ )+ sys.exit(1)+ else:+ print("\nAll API public contract checks passed.")+++if __name__ == "__main__":+ main()diff --git a/examples/llm_integration/advanced_custom_llm.py b/examples/llm_integration/advanced_custom_llm.pyindex d4b95faa8b..366e93c1c1 100644--- a/examples/llm_integration/advanced_custom_llm.py+++ b/examples/llm_integration/advanced_custom_llm.py@@ -17,22 +17,19 @@ from langchain_core.messages import AIMessage, BaseMessagefrom langchain_core.outputs import ChatGeneration, ChatResultfrom loguru import logger-from local_deep_research.api import detailed_research, quick_summary+from local_deep_research.api import (+ create_settings_snapshot,+ detailed_research,+ quick_summary,+)class RetryLLM(BaseChatModel):"""LLM wrapper that adds retry logic to any base LLM."""- def __init__(- self,- base_llm: BaseChatModel,- max_retries: int = 3,- retry_delay: float = 1.0,- ):- super().__init__()- self.base_llm = base_llm- self.max_retries = max_retries- self.retry_delay = retry_delay+ base_llm: BaseChatModel+ max_retries: int = 3+ retry_delay: float = 1.0def _generate(self,@@ -43,6 +40,7 @@ class RetryLLM(BaseChatModel):) -> ChatResult:"""Generate with retry logic."""last_error = None+ delay = self.retry_delayfor attempt in range(self.max_retries):try:@@ -53,10 +51,10 @@ class RetryLLM(BaseChatModel):last_error = eif attempt < self.max_retries - 1:logger.warning(- f"Attempt {attempt + 1} failed, retrying in {self.retry_delay}s..."+ f"Attempt {attempt + 1} failed, retrying in {delay}s...")- time.sleep(self.retry_delay)- self.retry_delay *= 2 # Exponential backoff+ time.sleep(delay)+ delay *= 2 # Exponential backoffraise last_error@@ -68,29 +66,10 @@ class RetryLLM(BaseChatModel):class ConfigurableLLM(BaseChatModel):"""LLM that can be configured with custom parameters."""- def __init__(- self,- model_name: str = "configurable-v1",- response_style: str = "technical",- max_length: int = 500,- include_confidence: bool = False,- **kwargs,- ):- """- Initialize ConfigurableLLM.-- Args:- model_name: Name of the model to use- response_style: Style of response ('technical', 'simple', or other)- max_length: Maximum length of response in characters- include_confidence: Whether to include confidence scores in responses- **kwargs: Additional keyword arguments- """- super().__init__(**kwargs)- self.model_name = model_name- self.response_style = response_style- self.max_length = max_length- self.include_confidence = include_confidence+ model_name: str = "configurable-v1"+ response_style: str = "technical"+ max_length: int = 500+ include_confidence: bool = Falsedef _generate(self,@@ -132,24 +111,19 @@ class ConfigurableLLM(BaseChatModel):return "configurable"+_DOMAIN_KNOWLEDGE: Dict[str, List[str]] = {+ "medical": ["diagnosis", "treatment", "symptoms", "medications"],+ "legal": ["contracts", "liability", "regulations", "compliance"],+ "technical": ["algorithms", "architecture", "performance", "scalability"],+ "finance": ["investments", "risk", "portfolio", "markets"],+}++class DomainExpertLLM(BaseChatModel):"""LLM that specializes in specific domains."""- def __init__(self, domain: str = "general", expertise_level: float = 0.8):- super().__init__()- self.domain = domain- self.expertise_level = expertise_level- self.domain_knowledge = {- "medical": ["diagnosis", "treatment", "symptoms", "medications"],- "legal": ["contracts", "liability", "regulations", "compliance"],- "technical": [- "algorithms",- "architecture",- "performance",- "scalability",- ],- "finance": ["investments", "risk", "portfolio", "markets"],- }+ domain: str = "general"+ expertise_level: float = 0.8def _generate(self,@@ -162,7 +136,7 @@ class DomainExpertLLM(BaseChatModel):query = messages[-1].content if messages else ""# Check if query matches domain- domain_terms = self.domain_knowledge.get(self.domain, [])+ domain_terms = _DOMAIN_KNOWLEDGE.get(self.domain, [])relevance = sum(1 for term in domain_terms if term.lower() in query.lower())@@ -227,13 +201,16 @@ def main():# Example 1: Using a retry wrapperlogger.info("\n1. Retry Wrapper Example:")base_llm = ConfigurableLLM(response_style="technical")- retry_llm = RetryLLM(base_llm, max_retries=3)+ retry_llm = RetryLLM(base_llm=base_llm, max_retries=3)+ snapshot = create_settings_snapshot(+ provider="retry_tech",+ overrides={"search.tool": "wikipedia"},+ )result = quick_summary(query="Explain quantum computing applications",llms={"retry_tech": retry_llm},- provider="retry_tech",- search_tool="wikipedia",+ settings_snapshot=snapshot,)logger.info(f"Summary: {result['summary'][:200]}...")@@ -250,11 +227,14 @@ def main():}# Medical query+ snapshot = create_settings_snapshot(+ provider="medical_expert",+ overrides={"search.tool": "pubmed"},+ )_ = quick_summary(query="What are the latest treatments for diabetes?",llms=experts,- provider="medical_expert",- search_tool="pubmed",+ settings_snapshot=snapshot,)logger.info("Medical summary retrieved successfully. Content not logged for privacy."@@ -280,6 +260,10 @@ def main():"base_config": tech_writer_config,}+ snapshot = create_settings_snapshot(+ provider="robust_writer",+ overrides={"search.tool": "arxiv"},+ )result = quick_summary(query="How do neural networks learn?",llms={@@ -287,8 +271,7 @@ def main():robust_config)},- provider="robust_writer",- search_tool="arxiv",+ settings_snapshot=snapshot,)logger.info(f"Robust Writer: {result['summary'][:150]}...")@@ -298,10 +281,11 @@ def main():# Stage 1: Quick exploration with simple LLMsimple_llm = ConfigurableLLM(response_style="simple", max_length=200)+ snapshot = create_settings_snapshot(provider="simple")initial = quick_summary(query="Climate change impacts on agriculture",llms={"simple": simple_llm},- provider="simple",+ settings_snapshot=snapshot,iterations=1,)@@ -310,10 +294,11 @@ def main():# Stage 2: Detailed research with expertexpert_llm = DomainExpertLLM(domain="technical", expertise_level=0.95)+ snapshot = create_settings_snapshot(provider="expert")detailed = detailed_research(query="Climate change impacts on agriculture: focus on technology solutions",llms={"expert": expert_llm},- provider="expert",+ settings_snapshot=snapshot,iterations=2,)@@ -335,12 +320,15 @@ def main():include_confidence=True,)+ snapshot = create_settings_snapshot(+ provider="integrated",+ overrides={"search.tool": "company_docs"},+ )result = quick_summary(query="Internal company policies on remote work",llms={"integrated": custom_llm},retrievers={"company_docs": MockRetriever()},- provider="integrated",- search_tool="company_docs",+ settings_snapshot=snapshot,)logger.info(f"Integrated result: {result['summary'][:150]}...")diff --git a/examples/llm_integration/basic_custom_llm.py b/examples/llm_integration/basic_custom_llm.pyindex ce16df4454..f0c751943a 100644--- a/examples/llm_integration/basic_custom_llm.py+++ b/examples/llm_integration/basic_custom_llm.py@@ -11,18 +11,18 @@ from langchain_core.language_models import BaseChatModelfrom langchain_core.messages import AIMessage, BaseMessagefrom langchain_core.outputs import ChatGeneration, ChatResult-from local_deep_research.api import detailed_research, quick_summary+from local_deep_research.api import (+ create_settings_snapshot,+ detailed_research,+ quick_summary,+)class CustomLLM(BaseChatModel):"""Example custom LLM implementation."""- def __init__(- self, model_name: str = "custom-model", temperature: float = 0.7- ):- super().__init__()- self.model_name = model_name- self.temperature = temperature+ model_name: str = "custom-model"+ temperature: float = 0.7def _generate(self,@@ -58,11 +58,14 @@ def main():# Example 1: Using a custom LLM instancecustom_llm = CustomLLM(model_name="my-custom-model", temperature=0.8)+ snapshot = create_settings_snapshot(+ provider="my_custom",+ overrides={"search.tool": "wikipedia"},+ )result = quick_summary(query="What are the latest advances in quantum computing?",llms={"my_custom": custom_llm},- provider="my_custom", # Use our registered LLM- search_tool="wikipedia", # Use Wikipedia as search engine+ settings_snapshot=snapshot,)print("Summary with custom LLM instance:")@@ -70,13 +73,16 @@ def main():print("-" * 80)# Example 2: Using a factory function+ snapshot = create_settings_snapshot(+ provider="factory_llm",+ temperature=0.3,+ overrides={"search.tool": "auto"},+ )result = quick_summary(query="Explain the benefits of renewable energy",llms={"factory_llm": custom_llm_factory},- provider="factory_llm", # Use our factory-created LLMmodel_name="renewable-expert", # This gets passed to the factory- temperature=0.3,- search_tool="auto",+ settings_snapshot=snapshot,)print("\nSummary with factory-created LLM:")@@ -90,11 +96,14 @@ def main():}# Technical analysis+ snapshot = create_settings_snapshot(+ provider="technical",+ overrides={"search.tool": "arxiv"},+ )technical_result = detailed_research(query="How do neural networks work?",llms=llms,- provider="technical",- search_tool="arxiv",+ settings_snapshot=snapshot,)print("\nTechnical analysis:")@@ -102,11 +111,14 @@ def main():print("-" * 80)# Creative exploration+ snapshot = create_settings_snapshot(+ provider="creative",+ overrides={"search.tool": "wikipedia"},+ )creative_result = quick_summary(query="What are the philosophical implications of AI?",llms=llms,- provider="creative",- search_tool="wikipedia",+ settings_snapshot=snapshot,)print("\nCreative exploration:")diff --git a/examples/llm_integration/mock_llm_example.py b/examples/llm_integration/mock_llm_example.pyindex 07d5c55141..5fb8376c0c 100644--- a/examples/llm_integration/mock_llm_example.py+++ b/examples/llm_integration/mock_llm_example.py@@ -16,27 +16,35 @@ from langchain_core.language_models import BaseChatModelfrom langchain_core.messages import AIMessage, BaseMessagefrom langchain_core.outputs import ChatGeneration, ChatResult-from local_deep_research.api import generate_report, quick_summary+from local_deep_research.api import (+ create_settings_snapshot,+ generate_report,+ quick_summary,+)+++_DEFAULT_RESPONSES: Dict[str, str] = {+ "default": "This is a mock response for testing purposes.",+ "quantum": "Quantum computing uses quantum mechanics principles like superposition and entanglement to process information in fundamentally new ways.",+ "climate": "Climate change refers to long-term shifts in global temperatures and weather patterns, primarily driven by human activities.",+ "ai": "Artificial Intelligence encompasses machine learning, neural networks, and systems that can perform tasks requiring human intelligence.",+ "summary": "Based on the search results, here is a comprehensive summary of the findings.",+ "report": "# Research Report\n\n## Executive Summary\n\nThis report provides detailed analysis.\n\n## Findings\n\n1. Key finding one\n2. Key finding two",+}class MockLLM(BaseChatModel):"""Mock LLM that returns predefined responses based on queries."""- def __init__(self, response_map: Optional[Dict[str, str]] = None):- super().__init__()- self.response_map = response_map or self._get_default_responses()- self.call_history = []+ response_map: Optional[Dict[str, str]] = None+ call_history: Optional[List[Dict]] = None- def _get_default_responses(self) -> Dict[str, str]:- """Get default mock responses."""- return {- "default": "This is a mock response for testing purposes.",- "quantum": "Quantum computing uses quantum mechanics principles like superposition and entanglement to process information in fundamentally new ways.",- "climate": "Climate change refers to long-term shifts in global temperatures and weather patterns, primarily driven by human activities.",- "ai": "Artificial Intelligence encompasses machine learning, neural networks, and systems that can perform tasks requiring human intelligence.",- "summary": "Based on the search results, here is a comprehensive summary of the findings.",- "report": "# Research Report\n\n## Executive Summary\n\nThis report provides detailed analysis.\n\n## Findings\n\n1. Key finding one\n2. Key finding two",- }+ def model_post_init(self, __context: Any) -> None:+ super().model_post_init(__context)+ if self.response_map is None:+ self.response_map = dict(_DEFAULT_RESPONSES)+ if self.call_history is None:+ self.call_history = []def _generate(self,@@ -90,10 +98,8 @@ class MockLLM(BaseChatModel):class ScenarioMockLLM(BaseChatModel):"""Mock LLM that simulates specific scenarios for testing."""- def __init__(self, scenario: str = "success"):- super().__init__()- self.scenario = scenario- self.call_count = 0+ scenario: str = "success"+ call_count: int = 0def _generate(self,@@ -185,11 +191,14 @@ def test_basic_mock():mock_llm = MockLLM()+ snapshot = create_settings_snapshot(+ provider="mock",+ overrides={"search.tool": "none"},+ )result = quick_summary(query="Tell me about quantum computing",llms={"mock": mock_llm},- provider="mock",- search_tool="none", # Disable search for pure mock testing+ settings_snapshot=snapshot,iterations=1,)@@ -210,11 +219,14 @@ def test_scenario_mocks():mock_llm = ScenarioMockLLM(scenario=scenario)try:+ snapshot = create_settings_snapshot(+ provider=f"mock_{scenario}",+ overrides={"search.tool": "none"},+ )result = quick_summary(query="Test query for scenario",llms={f"mock_{scenario}": mock_llm},- provider=f"mock_{scenario}",- search_tool="none",+ settings_snapshot=snapshot,iterations=1,)@@ -241,11 +253,14 @@ def test_mock_in_pipeline():mock_llm = MockLLM(response_map=response_map)# Test with report generation+ snapshot = create_settings_snapshot(+ provider="pipeline_mock",+ overrides={"search.tool": "none"},+ )report = generate_report(query="Create a comprehensive report",llms={"pipeline_mock": mock_llm},- provider="pipeline_mock",- search_tool="none",+ settings_snapshot=snapshot,searches_per_section=1,)@@ -282,18 +297,21 @@ def test_mock_with_custom_retriever():]mock_llm = MockLLM(- {+ response_map={"default": "Analyzed documents and found relevant information.","summary": "Summary: Based on internal documents, the answer is clear.",})+ snapshot = create_settings_snapshot(+ provider="mock",+ overrides={"search.tool": "mock_retriever"},+ )result = quick_summary(query="Internal policy question",llms={"mock": mock_llm},retrievers={"mock_retriever": MockRetriever()},- provider="mock",- search_tool="mock_retriever",+ settings_snapshot=snapshot,)print(f"Result: {result['summary']}")diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.pyindex 060bac74eb..ced3009014 100644--- a/src/local_deep_research/api/research_functions.py+++ b/src/local_deep_research/api/research_functions.py@@ -225,9 +225,7 @@ def quick_summary("""logger.info("Generating quick summary for query: %s", query)- # Only create settings snapshot if not already provided (programmatic API)if "settings_snapshot" not in kwargs:- # Build kwargs for create_settings_snapshot from explicit parameterssnapshot_kwargs = {}if provider is not None:snapshot_kwargs["provider"] = provider@@ -238,6 +236,17 @@ def quick_summary(if max_search_results is not None:snapshot_kwargs["max_search_results"] = max_search_results+ if (+ not snapshot_kwargs+ and settings is None+ and settings_override is None+ ):+ logger.warning(+ "No settings_snapshot or explicit config provided to quick_summary(). "+ "Using defaults and environment variables. For explicit control, "+ "pass settings_snapshot=create_settings_snapshot(...)."+ )+kwargs["settings_snapshot"] = create_settings_snapshot(base_settings=settings,overrides=settings_override,@@ -386,9 +395,7 @@ def generate_report("""logger.info("Generating comprehensive research report for query: %s", query)- # Only create settings snapshot if not already provided (programmatic API)if "settings_snapshot" not in kwargs:- # Build kwargs for create_settings_snapshot from explicit parameterssnapshot_kwargs = {}if provider is not None:snapshot_kwargs["provider"] = provider@@ -399,6 +406,17 @@ def generate_report(if max_search_results is not None:snapshot_kwargs["max_search_results"] = max_search_results+ if (+ not snapshot_kwargs+ and settings is None+ and settings_override is None+ ):+ logger.warning(+ "No settings_snapshot or explicit config provided to generate_report(). "+ "Using defaults and environment variables. For explicit control, "+ "pass settings_snapshot=create_settings_snapshot(...)."+ )+kwargs["settings_snapshot"] = create_settings_snapshot(base_settings=settings,overrides=settings_override,@@ -506,13 +524,23 @@ def detailed_research(retrievers: Optional dictionary of {name: retriever} pairs to use as search enginesllms: Optional dictionary of {name: llm} pairs to use as language modelsusername: Optional username for per-user cache isolation- **kwargs: Configuration for the search system+ **kwargs: Configuration for the search system. Pass settings_snapshot+ (via create_settings_snapshot()) to configure provider, temperature, etc.Returns:Dictionary containing detailed research results"""logger.info("Performing detailed research for query: %s", query)+ if "settings_snapshot" not in kwargs:+ logger.warning(+ "No settings_snapshot provided to detailed_research(). "+ "Using defaults and environment variables. For explicit control, "+ "pass settings_snapshot=create_settings_snapshot(provider=..., "+ "overrides={'search.tool': ...})."+ )+ kwargs["settings_snapshot"] = create_settings_snapshot()+# Generate a research_id if none providedif research_id is None:import uuid