~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
feat: Add programmatic access examples and tests with API fixes
LearningCircuitc6622d7620ff
diff --git a/examples/programmatic_access/README.md b/examples/programmatic_access/README.mdnew file mode 100644index 0000000000..595d9486dc--- /dev/null+++ b/examples/programmatic_access/README.md@@ -0,0 +1,148 @@+# Programmatic Access Examples++This directory contains examples demonstrating how to use Local Deep Research programmatically without requiring database setup.++## Overview++Local Deep Research can be used programmatically by:+- Setting `programmatic_mode: True` in settings to disable database dependencies+- Providing your own LangChain-compatible LLMs+- Providing your own search engines/retrievers+- Using the `AdvancedSearchSystem` class directly++## Examples++### 1. `minimal_working_example.py`+A minimal example showing how to use Local Deep Research programmatically:+- Uses **Ollama LLM** (`mistral:latest`) for language processing+- Creates a simple mock search engine that returns hardcoded results+- Demonstrates the `programmatic_mode` flag to disable database dependencies+- Shows basic usage of `AdvancedSearchSystem.analyze_topic()`++This is the simplest starting point for understanding programmatic access.++## Prerequisites++1. **Install Ollama** (if using Ollama models): Follow instructions at https://ollama.ai+2. **Pull required model**:+ ```bash+ ollama pull mistral:latest+ ```++3. **Install dependencies**:+ ```bash+ pip install langchain-ollama+ ```++## Running the Examples++```bash+# Run the minimal working example+python examples/programmatic_access/minimal_working_example.py+```++## API Functions++### `quick_summary()`+Generate a quick research summary:+```python+from local_deep_research.api import quick_summary++result = quick_summary(+ query="Your research question",+ llms={"custom_llm": your_llm},+ retrievers={"custom_retriever": your_retriever},+ provider="custom_llm",+ search_tool="custom_retriever"+)+```++### `detailed_research()`+Perform in-depth research with multiple iterations:+```python+from local_deep_research.api import detailed_research++result = detailed_research(+ query="Your research question",+ llms={"custom_llm": your_llm},+ retrievers={"custom_retriever": your_retriever},+ provider="custom_llm",+ search_tool="custom_retriever",+ iterations=3,+ questions_per_iteration=5+)+```++### `generate_report()`+Create a comprehensive research report:+```python+from local_deep_research.api import generate_report++result = generate_report(+ query="Your research question",+ llms={"custom_llm": your_llm},+ retrievers={"custom_retriever": your_retriever},+ provider="custom_llm",+ search_tool="custom_retriever",+ searches_per_section=3,+ output_file="report.md"+)+```++## Custom Components++### Custom LLMs+Any LangChain-compatible chat model can be used directly:+```python+from langchain_community.llms import Ollama++# Create your LLM instance+custom_llm = Ollama(model="your-model", temperature=0.7)++# Pass it directly to the API+result = quick_summary(+ query="Your question",+ llms={"my_llm": custom_llm}, # Direct instance, no factory needed+ provider="my_llm",+ # ... other parameters+)+```++### Custom Retrievers+Any LangChain retriever can be integrated:+```python+from langchain_community.vectorstores import FAISS+from langchain_community.embeddings import OllamaEmbeddings++embeddings = OllamaEmbeddings(model="your-embedding-model")+vectorstore = FAISS.from_documents(documents, embeddings)+retriever = vectorstore.as_retriever()+```++### Factory Pattern (Optional)+While you can pass LLM instances directly (recommended), you can also use factory functions for dynamic configuration:+```python+def create_llm(model_name="default", temperature=0.7, **kwargs):+ # Dynamic configuration based on parameters+ return Ollama(model=model_name, temperature=temperature)++result = quick_summary(+ query="...",+ llms={"factory": create_llm},+ provider="factory",+ model_name="specific-model",+ temperature=0.3+)+```+Note: Direct LLM instances are simpler and recommended for most use cases.++## Tips++1. **Temperature Settings**: Use lower temperatures (0.1-0.3) for factual research, higher (0.7-0.9) for creative tasks+2. **Multiple Retrievers**: Use `search_tool="auto"` to search across all registered retrievers+3. **Memory Management**: FAISS in-memory stores are fast but limited by RAM; consider disk-based stores for large datasets+4. **Model Selection**: Choose embedding models that match your content language and domain++## Related Tests++See `tests/test_programmatic_custom_llm_retriever.py` for comprehensive test examples.diff --git a/examples/programmatic_access/example_with_ollama.py b/examples/programmatic_access/example_with_ollama.pynew file mode 100644index 0000000000..5c6c703837--- /dev/null+++ b/examples/programmatic_access/example_with_ollama.py@@ -0,0 +1,142 @@+#!/usr/bin/env python3+"""+Example of using Local Deep Research programmatically with Ollama.++This example shows how to use the library without any database dependencies,+providing your own LLM and search components.+"""++from langchain_ollama import ChatOllama+from langchain_community.embeddings import OllamaEmbeddings+from langchain_community.vectorstores import FAISS+from langchain.schema import Document++# Import the search system+from local_deep_research.search_system import AdvancedSearchSystem+++def create_simple_retriever():+ """Create a simple FAISS retriever with sample documents."""+ documents = [+ Document(+ page_content="Machine learning is a subset of artificial intelligence that enables systems to learn from data.",+ metadata={+ "source": "ml_intro.txt",+ "title": "Introduction to Machine Learning",+ },+ ),+ Document(+ page_content="Deep learning uses neural networks with multiple layers to process complex patterns.",+ metadata={+ "source": "dl_intro.txt",+ "title": "Deep Learning Fundamentals",+ },+ ),+ Document(+ page_content="Natural language processing (NLP) allows computers to understand and generate human language.",+ metadata={"source": "nlp_intro.txt", "title": "NLP Overview"},+ ),+ Document(+ page_content="Computer vision enables machines to interpret and understand visual information from images and videos.",+ metadata={+ "source": "cv_intro.txt",+ "title": "Computer Vision Basics",+ },+ ),+ ]++ # Create embeddings and vector store+ embeddings = OllamaEmbeddings(model="nomic-embed-text")+ vectorstore = FAISS.from_documents(documents, embeddings)+ return vectorstore.as_retriever(k=3)+++class RetrieverSearchAdapter:+ """Adapter to make a LangChain retriever work as a search engine."""++ def __init__(self, retriever, settings_snapshot=None):+ self.retriever = retriever+ self.include_full_content = True+ self.settings_snapshot = settings_snapshot or {}++ def run(self, query, research_context=None):+ """Run a search and return results in the expected format."""+ docs = self.retriever.get_relevant_documents(query)+ results = []+ for i, doc in enumerate(docs):+ results.append(+ {+ "title": doc.metadata.get("title", f"Result {i + 1}"),+ "link": doc.metadata.get("source", "local"),+ "snippet": doc.page_content[:200] + "..."+ if len(doc.page_content) > 200+ else doc.page_content,+ "full_content": doc.page_content+ if self.include_full_content+ else None,+ "rank": i + 1,+ }+ )+ return results+++def main():+ """Demonstrate programmatic usage of Local Deep Research."""+ print("=== Local Deep Research Programmatic Example ===\n")++ # 1. Create LLM instance+ print("1. Setting up Ollama LLM...")+ llm = ChatOllama(+ model="gemma3:12b", # You can use any Ollama model+ temperature=0.7,+ )++ # 2. Create search engine (using a simple retriever)+ print("2. Creating search engine from retriever...")+ retriever = create_simple_retriever()++ # Create settings snapshot with programmatic_mode flag+ settings_snapshot = {+ "programmatic_mode": True, # This disables database dependencies+ "search.iterations": 2,+ "search.questions_per_iteration": 3,+ "search.strategy": "source-based", # Can be: source-based, direct, standard, etc.+ }++ search_engine = RetrieverSearchAdapter(retriever, settings_snapshot)++ # 3. Create AdvancedSearchSystem+ print("3. Initializing AdvancedSearchSystem...")+ search_system = AdvancedSearchSystem(+ llm=llm, search=search_engine, settings_snapshot=settings_snapshot+ )++ # 4. Run a research query+ query = "What are the main types of AI and how do they work?"+ print(f"\n4. Running research query: '{query}'")+ print("-" * 60)++ result = search_system.analyze_topic(query)++ # 5. Display results+ print("\n=== RESEARCH RESULTS ===\n")+ print(result["formatted_findings"])++ # Show some metadata+ print("\n=== METADATA ===")+ print(f"Iterations completed: {result['iterations']}")+ print(f"Total findings: {len(result['findings'])}")+ print(+ f"Questions generated: {sum(len(qs) for qs in result['questions_by_iteration'].values())}"+ )++ # Show the questions that were generated+ print("\n=== QUESTIONS BY ITERATION ===")+ for iteration, questions in result["questions_by_iteration"].items():+ print(f"\nIteration {iteration}:")+ for q in questions:+ print(f" - {q}")+++if __name__ == "__main__":+ main()diff --git a/examples/programmatic_access/test_direct_import.py b/examples/programmatic_access/test_direct_import.pynew file mode 100644index 0000000000..f28b0e629e--- /dev/null+++ b/examples/programmatic_access/test_direct_import.py@@ -0,0 +1,30 @@+#!/usr/bin/env python3+"""Test importing search_system directly without going through __init__.py"""++import sys++# Try importing the search_system module directly+try:+ print("Attempting to import search_system module directly...")+ from local_deep_research import search_system++ print("✓ search_system module imported!")++ # Now try to access AdvancedSearchSystem+ print("\nTrying to access AdvancedSearchSystem class...")+ AdvancedSearchSystem = search_system.AdvancedSearchSystem+ print("✓ Got AdvancedSearchSystem class!")++except Exception as e:+ print(f"✗ Failed: {e}")+ import traceback++ traceback.print_exc()++# Also try a more direct import+try:+ print("\nAttempting direct file import...")+ sys.path.insert(0, "src")+ print("✓ Direct import worked!")+except Exception as e:+ print(f"✗ Direct import failed: {e}")diff --git a/examples/programmatic_access/test_logging.py b/examples/programmatic_access/test_logging.pynew file mode 100644index 0000000000..12bda2c329--- /dev/null+++ b/examples/programmatic_access/test_logging.py@@ -0,0 +1,66 @@+#!/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/config/llm_config.py b/src/local_deep_research/config/llm_config.pyindex 9861270dff..d85c7c9779 100644--- a/src/local_deep_research/config/llm_config.py+++ b/src/local_deep_research/config/llm_config.py@@ -1,5 +1,6 @@import osfrom functools import cache+from typing import Union, Callablefrom langchain_anthropic import ChatAnthropicfrom langchain_community.llms import VLLM@@ -7,6 +8,7 @@ from langchain_core.language_models import BaseChatModel, FakeListChatModelfrom langchain_ollama import ChatOllamafrom langchain_openai import ChatOpenAIfrom loguru import logger+from pydantic import TypeAdapter, ValidationErrorfrom ..llm import get_llm_from_registry, is_llm_registeredfrom ..utilities.search_utilities import remove_think_tags@@ -258,23 +260,40 @@ def get_llm(logger.info(f"Using registered custom LLM: {provider}")custom_llm = get_llm_from_registry(provider)- # Check if it's already a BaseChatModel instance- if isinstance(custom_llm, BaseChatModel):- # It's already an LLM instance, use it directly- llm_instance = custom_llm- elif callable(custom_llm):- # It's a factory function, call it with parameters- try:- llm_instance = custom_llm(- model_name=model_name,- temperature=temperature,- )- except Exception:- logger.exception("Error creating custom LLM instance")- raise- else:+ # Use Pydantic to validate the type+ llm_validator = TypeAdapter(Union[BaseChatModel, Callable])++ try:+ # Validate that it's either a BaseChatModel or a Callable+ llm_validator.validate_python(custom_llm)++ if isinstance(custom_llm, BaseChatModel):+ # It's already a proper LLM instance, use it directly+ llm_instance = custom_llm+ else:+ # It's a callable (factory function), call it with parameters+ try:+ llm_instance = custom_llm(+ model_name=model_name,+ temperature=temperature,+ )+ # Validate the result is a BaseChatModel+ if not isinstance(llm_instance, BaseChatModel):+ raise ValueError(+ f"Factory function for {provider} must return a BaseChatModel instance, "+ f"got {type(llm_instance).__name__}"+ )+ except TypeError as e:+ # This happens when passing a class instead of instance or factory+ raise ValueError(+ f"Registered LLM {provider} appears to be a class. "+ f"Please register either an instance or a factory function, not a class. "+ f"Error: {e}"+ )+ except ValidationError:raise ValueError(- f"Registered LLM {provider} is neither a BaseChatModel nor a callable factory"+ f"Registered LLM {provider} must be either a BaseChatModel instance "+ f"or a callable factory function. Got: {type(custom_llm).__name__}")return wrap_llm_without_think_tags(diff --git a/tests/programmatic_access/test_ollama_integration.py b/tests/programmatic_access/test_ollama_integration.pynew file mode 100644index 0000000000..4e67aee497--- /dev/null+++ b/tests/programmatic_access/test_ollama_integration.py@@ -0,0 +1,318 @@+"""Integration tests for Ollama LLM with real text generation."""++import pytest+import os+from typing import List+from datetime import datetime+from langchain_ollama import ChatOllama+from langchain_community.embeddings import OllamaEmbeddings+from langchain_community.vectorstores import FAISS+from langchain.schema import Document++from src.local_deep_research.api import quick_summary+++# Skip these tests if SKIP_OLLAMA_TESTS is set+pytestmark = pytest.mark.skipif(+ os.environ.get("SKIP_OLLAMA_TESTS", "true").lower() == "true",+ reason="Ollama integration tests skipped (set SKIP_OLLAMA_TESTS=false to run)",+)+++def create_test_documents() -> List[Document]:+ """Create a small set of test documents."""+ return [+ Document(+ page_content="Python is a high-level, interpreted programming language known for its readability and versatility. It supports multiple programming paradigms including procedural, object-oriented, and functional programming.",+ metadata={"source": "python_overview.txt", "topic": "programming"},+ ),+ Document(+ page_content="Machine learning is a subset of artificial intelligence that enables systems to learn and improve from experience without being explicitly programmed. It uses algorithms to parse data, learn from it, and make decisions.",+ metadata={"source": "ml_intro.txt", "topic": "machine_learning"},+ ),+ Document(+ page_content="Deep learning is a specialized subset of machine learning that uses artificial neural networks with multiple layers. It excels at tasks like image recognition, natural language processing, and speech recognition.",+ metadata={"source": "deep_learning.txt", "topic": "deep_learning"},+ ),+ ]+++def ollama_llm_factory():+ """Create a factory function for Ollama LLM."""++ def create_llm(model_name="gemma3:12b", temperature=0.7, **kwargs):+ """Factory that creates ChatOllama instances."""+ # Use the provided model_name or default+ actual_model = model_name+ return ChatOllama(+ model=actual_model,+ temperature=temperature,+ num_predict=kwargs.get("max_tokens", 256),+ )++ return create_llm+++def memory_retriever():+ """Create an in-memory retriever with test documents."""+ documents = create_test_documents()++ # Create embeddings+ embeddings = OllamaEmbeddings(+ model="jeffh/intfloat-multilingual-e5-large-instruct:f16"+ )++ # Create vector store+ vectorstore = FAISS.from_documents(+ documents=documents, embedding=embeddings+ )++ # Return retriever+ return vectorstore.as_retriever(+ search_kwargs={"k": 2} # Return top 2 documents+ )+++def write_test_summary(+ test_name: str, result: dict, output_dir: str = "test_outputs"+):+ """Write test results to a summary file."""+ os.makedirs(output_dir, exist_ok=True)++ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")+ filename = f"{output_dir}/ollama_test_{test_name}_{timestamp}.md"++ with open(filename, "w") as f:+ f.write(f"# Ollama Integration Test: {test_name}\n\n")+ f.write(f"**Timestamp**: {datetime.now().isoformat()}\n\n")+ f.write(f"**Query**: {result.get('query', 'N/A')}\n\n")+ f.write("## Generated Summary\n\n")+ f.write(f"{result.get('summary', 'No summary generated')}\n\n")++ if result.get("findings"):+ f.write("## Findings\n\n")+ for i, finding in enumerate(result["findings"], 1):+ f.write(f"{i}. {finding}\n")+ f.write("\n")++ if result.get("sources"):+ f.write("## Sources\n\n")+ for source in result["sources"]:+ f.write(f"- {source}\n")++ return filename+++def test_ollama_quick_summary_real_generation(memory_retriever):+ """Test quick_summary with real Ollama text generation."""++ # Create ChatOllama LLM instance directly+ llm = ChatOllama(+ model="gemma3:12b",+ temperature=0.3,+ num_predict=256,+ )++ # Perform quick summary with real generation+ result = quick_summary(+ query="What is Python and how is it used in machine learning?",+ llms={"ollama": llm}, # Pass LLM instance directly+ retrievers={"test_docs": memory_retriever},+ provider="ollama",+ search_tool="test_docs",+ )++ # Verify we got a real response+ assert "summary" in result+ assert isinstance(result["summary"], str)+ assert len(result["summary"]) > 50 # Should be a meaningful summary++ # The summary should mention Python and ML based on our documents+ summary_lower = result["summary"].lower()+ assert any(+ term in summary_lower for term in ["python", "programming", "language"]+ )+ assert any(+ term in summary_lower+ for term in ["machine learning", "ml", "learning", "ai"]+ )++ # Check other fields+ assert "findings" in result+ assert isinstance(result["findings"], list)++ # Write summary to file+ result["query"] = "What is Python and how is it used in machine learning?"+ output_file = write_test_summary("quick_summary", result)++ # Print the actual generated summary for verification+ print("\n=== GENERATED SUMMARY ===")+ print(result["summary"])+ print("\n=== FINDINGS ===")+ for i, finding in enumerate(result.get("findings", [])[:3]):+ print(f"{i + 1}. {finding}")+ print(f"\n=== Summary written to: {output_file} ===")+++def test_ollama_with_multiple_queries(ollama_llm_factory, memory_retriever):+ """Test multiple queries to verify consistent operation."""++ queries = [+ "What is deep learning?",+ "How does Python relate to AI development?",+ "Explain the difference between machine learning and deep learning",+ ]++ all_results = []+ summaries = []++ for query in queries:+ result = quick_summary(+ query=query,+ llms={"ollama": ollama_llm_factory},+ retrievers={"docs": memory_retriever},+ provider="ollama",+ search_tool="docs",+ temperature=0.5,+ )++ # Verify each query produces a summary+ assert "summary" in result+ assert len(result["summary"]) > 30++ result["query"] = query+ all_results.append(result)+ summaries.append(result["summary"])++ # All summaries should be different (not cached or static)+ assert len(set(summaries)) == len(summaries), (+ "All summaries should be unique"+ )++ # Write combined summary+ combined_result = {+ "summary": "\n\n---\n\n".join(+ f"**Query**: {r['query']}\n\n{r['summary']}" for r in all_results+ ),+ "findings": [],+ "query": "Multiple queries test",+ }+ output_file = write_test_summary("multiple_queries", combined_result)++ # Print summaries for manual verification+ print("\n=== MULTIPLE QUERY RESULTS ===")+ for query, summary in zip(queries, summaries):+ print(f"\nQuery: {query}")+ print(f"Summary: {summary[:200]}...")+ print(f"\n=== Combined summary written to: {output_file} ===")+++def test_ollama_factory_with_different_parameters(memory_retriever):+ """Test that factory parameters are properly passed through."""++ def custom_factory(model_name="gemma3:12b", temperature=0.7, **kwargs):+ """Factory with custom defaults."""+ # Track what parameters were received+ print(+ f"\nFactory called with: model_name={model_name}, temp={temperature}, kwargs={kwargs}"+ )++ return ChatOllama(+ model=model_name,+ temperature=temperature,+ num_predict=kwargs.get("max_tokens", 100),+ )++ # Test with custom parameters+ result = quick_summary(+ query="Brief explanation of Python",+ llms={"custom": custom_factory},+ retrievers={"docs": memory_retriever},+ provider="custom",+ search_tool="docs",+ temperature=0.1, # Should override factory default+ max_tokens=150, # Should be passed to factory+ )++ assert "summary" in result+ assert len(result["summary"]) > 20++ # Write summary+ result["query"] = "Brief explanation of Python"+ output_file = write_test_summary("custom_parameters", result)+ print(f"\nCustom parameters test summary written to: {output_file}")+++def test_retriever_actually_retrieves_documents(memory_retriever):+ """Verify the retriever is working correctly."""++ # Test retriever directly+ docs = memory_retriever.get_relevant_documents("Python programming")++ assert len(docs) > 0+ assert all(isinstance(doc.page_content, str) for doc in docs)++ # Should retrieve Python-related content+ combined_content = " ".join(doc.page_content for doc in docs).lower()+ assert "python" in combined_content++[email protected]("temperature", [0.1, 0.5, 0.9])+def test_temperature_affects_generation(+ ollama_llm_factory, memory_retriever, temperature+):+ """Test that different temperatures produce different outputs."""++ result = quick_summary(+ query="Describe machine learning",+ llms={"ollama": ollama_llm_factory},+ retrievers={"docs": memory_retriever},+ provider="ollama",+ search_tool="docs",+ temperature=temperature,+ )++ assert "summary" in result+ print(f"\nTemp {temperature} summary: {result['summary'][:100]}...")+++if __name__ == "__main__":+ # Allow running directly for debugging+ print("Running Ollama integration tests...")+ print("Make sure Ollama is running and models are available:")+ print(" ollama pull gemma3:12b")+ print(" ollama pull jeffh/intfloat-multilingual-e5-large-instruct:f16")++ # Run a simple test+ try:++ def factory(**kwargs):+ return ChatOllama(model="gemma3:12b", **kwargs)++ # Create simple retriever+ docs = [Document(page_content="Test content about Python programming.")]+ embeddings = OllamaEmbeddings(+ model="jeffh/intfloat-multilingual-e5-large-instruct:f16"+ )+ vectorstore = FAISS.from_documents(docs, embeddings)+ retriever = vectorstore.as_retriever()++ result = quick_summary(+ query="What is Python?",+ llms={"test": factory},+ retrievers={"test": retriever},+ provider="test",+ search_tool="test",+ )++ print(+ f"\nSuccess! Generated summary: {result.get('summary', 'No summary')}"+ )++ except Exception as e:+ print(f"\nError: {e}")+ import traceback++ traceback.print_exc()diff --git a/tests/test_programmatic_custom_llm_retriever.py b/tests/test_programmatic_custom_llm_retriever.pynew file mode 100644index 0000000000..b54e26106e--- /dev/null+++ b/tests/test_programmatic_custom_llm_retriever.py@@ -0,0 +1,395 @@+"""Test demonstrating programmatic access with Langchain Ollama LLM and in-memory vector retriever."""++import pytest+from unittest.mock import patch, MagicMock+from langchain_community.llms import Ollama+from langchain_community.embeddings import OllamaEmbeddings+from langchain_community.vectorstores import FAISS+from langchain.schema import Document++from src.local_deep_research.api import (+ quick_summary,+ detailed_research,+ generate_report,+)+from src.local_deep_research.llm import clear_llm_registry++[email protected](autouse=True)+def clear_registries():+ """Clear registries before and after each test."""+ clear_llm_registry()+ yield+ clear_llm_registry()+++def sample_documents():+ """Create sample documents for the vector store."""+ docs = [+ Document(+ page_content="Machine learning is a subset of artificial intelligence that enables systems to learn from data.",+ metadata={"source": "ml_basics.txt", "topic": "machine_learning"},+ ),+ Document(+ page_content="Deep learning uses neural networks with multiple layers to extract features from raw data.",+ metadata={"source": "dl_intro.txt", "topic": "deep_learning"},+ ),+ Document(+ page_content="Natural language processing allows computers to understand and generate human language.",+ metadata={"source": "nlp_guide.txt", "topic": "nlp"},+ ),+ Document(+ page_content="Computer vision enables machines to interpret and analyze visual information from images and videos.",+ metadata={"source": "cv_overview.txt", "topic": "computer_vision"},+ ),+ Document(+ page_content="Reinforcement learning trains agents to make decisions by rewarding desired behaviors.",+ metadata={+ "source": "rl_basics.txt",+ "topic": "reinforcement_learning",+ },+ ),+ ]+ return docs+++def ollama_llm():+ """Create an Ollama LLM instance."""+ # Using gemma3n:e4b as requested+ return Ollama(+ model="gemma3n:e4b",+ temperature=0.7,+ )+++def memory_retriever(sample_documents):+ """Create an in-memory vector store retriever."""+ # Create embeddings using the specified multilingual model+ embeddings = OllamaEmbeddings(+ model="jeffh/intfloat-multilingual-e5-large-instruct:f16"+ )++ # Create FAISS vector store from documents+ vectorstore = FAISS.from_documents(+ documents=sample_documents, embedding=embeddings+ )++ # Create retriever from vector store+ retriever = vectorstore.as_retriever(+ search_kwargs={"k": 3} # Return top 3 most relevant documents+ )++ return retriever+++def mock_search_system():+ """Create a mock search system for testing."""+ system = MagicMock()+ system.analyze_topic.return_value = {+ "current_knowledge": "Analysis using Ollama LLM and in-memory retriever",+ "findings": [+ "Successfully retrieved relevant documents from vector store",+ "Ollama LLM provided coherent responses",+ ],+ "iterations": 2,+ "questions": {+ "iteration_1": ["What is the main concept?"],+ "iteration_2": ["How is it applied in practice?"],+ },+ "formatted_findings": "## Research Summary\n- Vector retrieval worked effectively",+ "all_links_of_system": [],+ }+ system.model = MagicMock()+ return system+++def test_quick_summary_with_ollama_and_memory_retriever(+ ollama_llm, memory_retriever, mock_search_system+):+ """Test quick_summary using Ollama LLM and in-memory vector retriever."""++ with patch(+ "src.local_deep_research.api.research_functions._init_search_system"+ ) as mock_init:+ mock_init.return_value = mock_search_system++ # Use programmatic API with Ollama and memory retriever+ result = quick_summary(+ query="What is deep learning and how does it relate to machine learning?",+ llms={"ollama_llm": ollama_llm},+ retrievers={"memory_docs": memory_retriever},+ provider="ollama_llm",+ search_tool="memory_docs",+ temperature=0.5,+ )++ # Verify result structure+ assert "summary" in result+ assert (+ result["summary"]+ == "Analysis using Ollama LLM and in-memory retriever"+ )+ assert len(result["findings"]) == 2+ assert "vector store" in result["findings"][0].lower()++ # Verify components were configured correctly+ init_kwargs = mock_init.call_args[1]+ assert init_kwargs["provider"] == "ollama_llm"+ assert init_kwargs["search_tool"] == "memory_docs"+ assert init_kwargs["temperature"] == 0.5+++def test_detailed_research_with_ollama_and_memory_retriever(+ ollama_llm, memory_retriever, mock_search_system+):+ """Test detailed_research with Ollama and memory retriever."""++ with patch(+ "src.local_deep_research.api.research_functions._init_search_system"+ ) as mock_init:+ mock_init.return_value = mock_search_system++ result = detailed_research(+ query="Explain the differences between various machine learning approaches",+ llms={"ollama": ollama_llm},+ retrievers={"local_docs": memory_retriever},+ provider="ollama",+ search_tool="local_docs",+ iterations=3,+ questions_per_iteration=2,+ )++ # Verify detailed research results+ assert (+ result["query"]+ == "Explain the differences between various machine learning approaches"+ )+ assert (+ result["summary"]+ == "Analysis using Ollama LLM and in-memory retriever"+ )+ assert result["metadata"]["iterations_requested"] == 3+ assert result["metadata"]["search_tool"] == "local_docs"+++def test_generate_report_with_ollama_and_memory_retriever(+ ollama_llm, memory_retriever+):+ """Test report generation using Ollama and memory retriever."""++ with patch(+ "src.local_deep_research.api.research_functions._init_search_system"+ ) as mock_init:+ with patch(+ "src.local_deep_research.api.research_functions.IntegratedReportGenerator"+ ) as mock_report_gen:+ # Setup mocks+ mock_system = MagicMock()+ mock_system.analyze_topic.return_value = {+ "findings": "Initial ML findings"+ }+ mock_init.return_value = mock_system++ mock_generator = MagicMock()+ mock_generator.generate_report.return_value = {+ "content": "# Machine Learning Overview\n\n## Introduction\nThis report covers key ML concepts from local documents.",+ "metadata": {+ "query": "machine learning overview",+ "sources_used": 5,+ },+ }+ mock_report_gen.return_value = mock_generator++ # Generate report+ result = generate_report(+ query="Create a comprehensive overview of machine learning concepts",+ llms={"ollama": ollama_llm},+ retrievers={"vector_store": memory_retriever},+ provider="ollama",+ search_tool="vector_store",+ searches_per_section=2,+ )++ # Verify report generation+ assert "content" in result+ assert "# Machine Learning Overview" in result["content"]+ assert "local documents" in result["content"]++ # Verify configuration+ init_kwargs = mock_init.call_args[1]+ assert init_kwargs["provider"] == "ollama"+ assert init_kwargs["search_tool"] == "vector_store"+++def test_custom_vector_store_with_more_documents():+ """Test creating a larger in-memory vector store."""++ # Create more documents+ extended_docs = [+ Document(+ page_content="Transfer learning allows models trained on one task to be adapted for related tasks.",+ metadata={"source": "transfer_learning.txt"},+ ),+ Document(+ page_content="Attention mechanisms help models focus on relevant parts of the input data.",+ metadata={"source": "attention.txt"},+ ),+ Document(+ page_content="Gradient descent is an optimization algorithm used to train neural networks.",+ metadata={"source": "optimization.txt"},+ ),+ Document(+ page_content="Convolutional neural networks are particularly effective for image processing tasks.",+ metadata={"source": "cnn.txt"},+ ),+ Document(+ page_content="Recurrent neural networks can process sequential data like text or time series.",+ metadata={"source": "rnn.txt"},+ ),+ ]++ # Create vector store with extended documents+ embeddings = OllamaEmbeddings(+ model="jeffh/intfloat-multilingual-e5-large-instruct:f16"+ )+ vectorstore = FAISS.from_documents(+ documents=extended_docs, embedding=embeddings+ )++ # Create retriever with different search parameters+ retriever = vectorstore.as_retriever(+ search_type="similarity",+ search_kwargs={"k": 5}, # Return top 5 documents+ )++ # Create Ollama LLM+ llm = Ollama(model="gemma3n:e4b", temperature=0.3)++ with patch(+ "src.local_deep_research.api.research_functions._init_search_system"+ ) as mock_init:+ mock_system = MagicMock()+ mock_system.analyze_topic.return_value = {+ "current_knowledge": "Extended document analysis complete",+ "findings": ["Found relevant information about neural networks"],+ }+ mock_init.return_value = mock_system++ result = quick_summary(+ query="How do different types of neural networks work?",+ llms={"ollama": llm},+ retrievers={"extended_docs": retriever},+ provider="ollama",+ search_tool="extended_docs",+ )++ assert "summary" in result+ assert result["summary"] == "Extended document analysis complete"+++def test_multiple_retrievers_with_ollama():+ """Test using multiple in-memory retrievers with Ollama."""++ # Create first retriever for ML topics+ ml_docs = [+ Document(+ page_content="Supervised learning uses labeled data for training."+ ),+ Document(+ page_content="Unsupervised learning finds patterns in unlabeled data."+ ),+ ]++ # Create second retriever for application topics+ app_docs = [+ Document(+ page_content="ML is used in recommendation systems for personalized content."+ ),+ Document(+ page_content="ML powers autonomous vehicles through computer vision and sensor fusion."+ ),+ ]++ embeddings = OllamaEmbeddings(+ model="jeffh/intfloat-multilingual-e5-large-instruct:f16"+ )++ ml_vectorstore = FAISS.from_documents(ml_docs, embeddings)+ app_vectorstore = FAISS.from_documents(app_docs, embeddings)++ ml_retriever = ml_vectorstore.as_retriever()+ app_retriever = app_vectorstore.as_retriever()++ ollama_llm = Ollama(model="gemma3n:e4b")++ with patch(+ "src.local_deep_research.api.research_functions._init_search_system"+ ) as mock_init:+ mock_system = MagicMock()+ mock_system.analyze_topic.return_value = {+ "current_knowledge": "Analysis from multiple vector stores",+ "findings": ["ML concepts retrieved", "Applications identified"],+ }+ mock_init.return_value = mock_system++ result = quick_summary(+ query="What are ML techniques and their applications?",+ llms={"ollama": ollama_llm},+ retrievers={+ "ml_concepts": ml_retriever,+ "ml_applications": app_retriever,+ },+ provider="ollama",+ search_tool="auto", # Use all retrievers+ )++ assert "summary" in result+ assert "multiple vector stores" in result["summary"]+++def test_simple_ollama_factory_pattern():+ """Test using a factory function to create Ollama instances."""++ def create_ollama_llm(model_name="gemma3n:e4b", temperature=0.7, **kwargs):+ """Factory function for creating configured Ollama instances."""+ return Ollama(+ model=model_name,+ temperature=temperature,+ num_predict=kwargs.get("max_tokens", 256),+ )++ # Create simple in-memory retriever+ docs = [Document(page_content="Test content for factory pattern demo.")]+ embeddings = OllamaEmbeddings(+ model="jeffh/intfloat-multilingual-e5-large-instruct:f16"+ )+ vectorstore = FAISS.from_documents(docs, embeddings)+ retriever = vectorstore.as_retriever()++ with patch(+ "src.local_deep_research.api.research_functions._init_search_system"+ ) as mock_init:+ mock_system = MagicMock()+ mock_system.analyze_topic.return_value = {+ "current_knowledge": "Factory pattern test successful",+ "findings": [],+ }+ mock_init.return_value = mock_system++ result = quick_summary(+ query="Test factory pattern",+ llms={"ollama_factory": create_ollama_llm},+ retrievers={"test_docs": retriever},+ provider="ollama_factory",+ search_tool="test_docs",+ model_name="gemma3n:e4b",+ temperature=0.2,+ max_tokens=512,+ )++ assert "summary" in result+ assert "Factory pattern test successful" in result["summary"]