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: Clean up and improve programmatic API examples

LearningCircuit296be1ea838a
diff --git a/examples/api_usage/programmatic/README.md b/examples/api_usage/programmatic/README.md
index 595d9486dc..1e7f704a07 100644
--- a/examples/api_usage/programmatic/README.md
+++ b/examples/api_usage/programmatic/README.md
@@ -1,44 +1,108 @@
-# Programmatic Access Examples
+# Local Deep Research - Programmatic API Examples
-This directory contains examples demonstrating how to use Local Deep Research programmatically without requiring database setup.
+This directory contains examples demonstrating how to use Local Deep Research programmatically without requiring authentication or database access.
-## Overview
+## Quick Start
-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
+All examples use the programmatic API that bypasses authentication:
-## 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()`
+```python
+from local_deep_research.api import quick_summary, detailed_research
+from local_deep_research.api.settings_utils import create_settings_snapshot
-This is the simplest starting point for understanding programmatic access.
+# Create settings for programmatic mode
+settings = create_settings_snapshot({
+ "programmatic_mode": True,
+ "search.tool": "wikipedia"
+})
-## Prerequisites
+# Run research
+result = quick_summary("your topic", settings_snapshot=settings)
+```
-1. **Install Ollama** (if using Ollama models): Follow instructions at https://ollama.ai
-2. **Pull required model**:
- ```bash
- ollama pull mistral:latest
- ```
+## Examples Overview
+
+| Example | Purpose | Key Features | Difficulty |
+|---------|---------|--------------|------------|
+| **minimal_working_example.py** | Simplest possible example | Basic setup, minimal code | Beginner |
+| **simple_programmatic_example.py** | Common use cases with the new API | quick_summary, detailed_research, custom parameters | Beginner |
+| **search_strategies_example.py** | Demonstrates search strategies | source-based vs focused-iteration strategies | Intermediate |
+| **hybrid_search_example.py** | Combine multiple search sources | Multiple retrievers, web + retriever combo | Intermediate |
+| **custom_llm_retriever_example.py** | Custom LLM and retriever integration | Ollama, custom retrievers, FAISS | Advanced |
+| **searxng_example.py** | Web search with SearXNG | SearXNG integration, error handling | Advanced |
+
+## Example Details
+
+### minimal_working_example.py
+**Purpose:** Show the absolute minimum code needed to use LDR programmatically.
+- Creates a simple LLM and search engine
+- Runs a basic search
+- No external dependencies beyond Ollama
+
+### simple_programmatic_example.py
+**Purpose:** Demonstrate the main API functions with practical examples.
+- `quick_summary()` - Fast research with summary
+- `detailed_research()` - Comprehensive research with findings
+- Custom search parameters
+- Different search tools (Wikipedia, auto, etc.)
+
+### search_strategies_example.py
+**Purpose:** Explain and demonstrate the two main search strategies.
+- **source-based**: Comprehensive research with detailed citations
+- **focused-iteration**: Iterative refinement of research questions
+- Side-by-side comparison of strategies
+- When to use each strategy
+
+### hybrid_search_example.py
+**Purpose:** Show how to combine multiple search sources for comprehensive research.
+- Multiple named retrievers for different document types
+- Combining custom retrievers with web search
+- Source analysis and tracking
+- Meta search configuration
+
+### custom_llm_retriever_example.py
+**Purpose:** Advanced integration with custom components.
+- Custom LLM implementation (using Ollama)
+- Custom retriever with embeddings
+- Vector store integration (FAISS)
+- Direct use of AdvancedSearchSystem
+
+### searxng_example.py
+**Purpose:** Web search integration using SearXNG.
+- SearXNG configuration
+- Error handling and fallbacks
+- Real-time web search
+- Direct use of search engines
+
+## Key Concepts
+
+### Programmatic Mode
+All examples use `programmatic_mode: True` in settings to bypass authentication:
+```python
+settings = create_settings_snapshot({"programmatic_mode": True})
+```
-3. **Install dependencies**:
- ```bash
- pip install langchain-ollama
- ```
+### Search Strategies
+- **source-based**: Best for academic research, fact-checking
+- **focused-iteration**: Best for exploratory research, complex topics
-## Running the Examples
+### Search Tools
+Available search tools include:
+- `wikipedia` - Wikipedia search
+- `arxiv` - Academic papers
+- `searxng` - Web search via SearXNG
+- `auto` - Automatically select best tool
+- `meta` - Combine multiple tools
-```bash
-# Run the minimal working example
-python examples/programmatic_access/minimal_working_example.py
+### Custom Retrievers
+You can provide your own retrievers:
+```python
+result = quick_summary(
+ query="topic",
+ retrievers={"my_docs": custom_retriever},
+ search_tool="my_docs",
+ settings_snapshot=settings
+)
```
## API Functions
@@ -47,13 +111,14 @@ python examples/programmatic_access/minimal_working_example.py
Generate a quick research summary:
```python
from local_deep_research.api import quick_summary
+from local_deep_research.api.settings_utils import create_settings_snapshot
+settings = create_settings_snapshot({"programmatic_mode": True})
result = quick_summary(
query="Your research question",
- llms={"custom_llm": your_llm},
- retrievers={"custom_retriever": your_retriever},
- provider="custom_llm",
- search_tool="custom_retriever"
+ settings_snapshot=settings,
+ search_tool="wikipedia",
+ iterations=2
)
```
@@ -64,85 +129,88 @@ 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",
+ settings_snapshot=settings,
+ search_strategy="source-based",
iterations=3,
questions_per_iteration=5
)
```
### `generate_report()`
-Create a comprehensive research report:
+*Note: Currently requires authentication. Fix coming in separate PR.*
```python
from local_deep_research.api import generate_report
+# After auth fix is merged:
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"
+ settings_snapshot=settings,
+ output_file="report.md",
+ searches_per_section=3
)
```
-## Custom Components
+## Requirements
-### Custom LLMs
-Any LangChain-compatible chat model can be used directly:
-```python
-from langchain_community.llms import Ollama
+- Python 3.8+
+- Local Deep Research installed
+- Ollama (for most examples)
+- SearXNG instance (for searxng_example.py)
-# Create your LLM instance
-custom_llm = Ollama(model="your-model", temperature=0.7)
+## Running the Examples
-# 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
-)
-```
+1. Install Local Deep Research:
+ ```bash
+ pip install -e .
+ ```
-### Custom Retrievers
-Any LangChain retriever can be integrated:
-```python
-from langchain_community.vectorstores import FAISS
-from langchain_community.embeddings import OllamaEmbeddings
+2. Start Ollama (if using Ollama examples):
+ ```bash
+ ollama serve
+ ollama pull gemma3:12b
+ ollama pull nomic-embed-text # For embeddings
+ ```
-embeddings = OllamaEmbeddings(model="your-embedding-model")
-vectorstore = FAISS.from_documents(documents, embeddings)
-retriever = vectorstore.as_retriever()
-```
+3. Run any example:
+ ```bash
+ python minimal_working_example.py
+ python simple_programmatic_example.py
+ python search_strategies_example.py
+ ```
+
+## Troubleshooting
-### Factory Pattern (Optional)
-While you can pass LLM instances directly (recommended), you can also use factory functions for dynamic configuration:
+### "No settings context available" Error
+Make sure to pass `settings_snapshot` to all API functions:
```python
-def create_llm(model_name="default", temperature=0.7, **kwargs):
- # Dynamic configuration based on parameters
- return Ollama(model=model_name, temperature=temperature)
+settings = create_settings_snapshot({"programmatic_mode": True})
+result = quick_summary("topic", settings_snapshot=settings)
+```
-result = quick_summary(
- query="...",
- llms={"factory": create_llm},
- provider="factory",
- model_name="specific-model",
- temperature=0.3
-)
+### Ollama Connection Error
+Ensure Ollama is running:
+```bash
+ollama serve
```
-Note: Direct LLM instances are simpler and recommended for most use cases.
-## Tips
+### SearXNG Connection Error
+Start a SearXNG instance or use the fallback in the example:
+```bash
+docker run -p 8080:8080 searxng/searxng
+```
+
+## Coming Soon
+
+The `generate_report()` function currently requires authentication. A fix is planned in a separate PR to enable programmatic report generation without authentication.
+
+## Contributing
-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
+When adding new examples:
+1. Focus on demonstrating specific features
+2. Include clear comments explaining the code
+3. Handle errors gracefully
+4. Update this README with the new example
-## Related Tests
+## License
-See `tests/test_programmatic_custom_llm_retriever.py` for comprehensive test examples.
+See the main project LICENSE file.
diff --git a/examples/api_usage/programmatic/comprehensive_tutorial.py b/examples/api_usage/programmatic/comprehensive_tutorial.py
deleted file mode 100644
index 80f345c5cb..0000000000
--- a/examples/api_usage/programmatic/comprehensive_tutorial.py
+++ /dev/null
@@ -1,907 +0,0 @@
-#!/usr/bin/env python
-"""
-Comprehensive Local Deep Research API Tutorial
-
-This tutorial demonstrates all major features of the LDR API v1.0+
-with the new authentication and per-user encrypted databases.
-It replaces the Jupyter notebook with a complete Python example.
-
-Topics covered:
-1. Authentication and setup
-2. Quick summaries
-3. Detailed research
-4. Report generation
-5. Custom search parameters
-6. Using specific search engines
-7. Working with LangChain retrievers
-8. Analyzing results
-9. Exporting and saving data
-10. Advanced configuration
-
-Prerequisites:
-- LDR v1.0+ installed (with authentication features)
-- User account created via web interface
-- LLM provider configured
-"""
-
-import json
-import os
-from datetime import datetime, UTC
-from typing import Dict, List
-
-# Core LDR imports
-from local_deep_research.api import (
- quick_summary,
- detailed_research,
- generate_report,
-)
-from local_deep_research.database.session_context import get_user_db_session
-from local_deep_research.settings import SettingsManager
-
-# Additional imports for advanced features
-from local_deep_research.config.llm_config import get_available_providers
-
-# For custom retrievers
-from langchain.schema import BaseRetriever, Document
-
-# ============================================================================
-# CONFIGURATION - UPDATE THESE!
-# ============================================================================
-USERNAME = "your_username" # Change to your LDR username
-PASSWORD = "your_password" # Change to your LDR password
-
-# Optional: Set to True to save outputs
-SAVE_OUTPUTS = True
-OUTPUT_DIR = "./ldr_tutorial_outputs"
-
-# ============================================================================
-# HELPER FUNCTIONS
-# ============================================================================
-
-
-def setup_output_directory():
- """Create output directory if saving is enabled."""
- if SAVE_OUTPUTS and not os.path.exists(OUTPUT_DIR):
- os.makedirs(OUTPUT_DIR)
- print(f"Created output directory: {OUTPUT_DIR}")
-
-
-def save_output(filename: str, content: str):
- """Save content to file if saving is enabled."""
- if SAVE_OUTPUTS:
- filepath = os.path.join(OUTPUT_DIR, filename)
- with open(filepath, "w", encoding="utf-8") as f:
- f.write(content)
- print(f" → Saved to: {filepath}")
-
-
-def print_section(title: str):
- """Print a formatted section header."""
- print(f"\n{'=' * 70}")
- print(f" {title}")
- print(f"{'=' * 70}\n")
-
-
-# ============================================================================
-# TUTORIAL SECTIONS
-# ============================================================================
-
-
-def section_1_authentication():
- """Section 1: Authentication and Basic Setup"""
- print_section("1. AUTHENTICATION AND BASIC SETUP")
-
- print("Authenticating with LDR...")
-
- try:
- with get_user_db_session(
- username=USERNAME, password=PASSWORD
- ) as session:
- settings_manager = SettingsManager(session)
- settings_snapshot = settings_manager.get_all_settings()
-
- # Display current configuration
- provider = settings_snapshot.get("llm.provider", {}).get(
- "value", "Not set"
- )
- model = settings_snapshot.get("llm.model", {}).get(
- "value", "Not set"
- )
-
- print(f"✓ Successfully authenticated as: {USERNAME}")
- print(f"✓ LLM Provider: {provider}")
- print(f"✓ LLM Model: {model}")
-
- # Check available providers
- from local_deep_research.config.thread_settings import (
- set_settings_context,
- )
-
- set_settings_context(settings_snapshot)
- providers = get_available_providers(settings_snapshot)
-
- print("\nAvailable LLM providers:")
- for pid, pname in providers.items():
- print(f" - {pid}: {pname}")
-
- return True
-
- except Exception as e:
- print(f"\n❌ Authentication failed: {e}")
- print("\nPlease ensure:")
- print("1. You have created an account via the web interface")
- print("2. You have updated USERNAME and PASSWORD in this script")
- print(
- "3. The server has been started at least once to create databases"
- )
- return False
-
-
-def section_2_quick_summary():
- """Section 2: Generating Quick Summaries"""
- print_section("2. GENERATING QUICK SUMMARIES")
-
- with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = SettingsManager(session)
- settings_snapshot = settings_manager.get_all_settings()
-
- # Example 1: Basic quick summary
- print("Example 1: Basic quick summary")
- result = quick_summary(
- "advances in fusion energy", settings_snapshot=settings_snapshot
- )
-
- print(f"Summary: {result['summary'][:500]}...")
- print("\nMetrics:")
- print(f" - Sources found: {len(result.get('sources', []))}")
- print(f" - Research ID: {result.get('research_id', 'N/A')}")
-
- save_output("quick_summary_basic.json", json.dumps(result, indent=2))
-
- # Example 2: Custom parameters
- print("\n\nExample 2: Quick summary with custom parameters")
- custom_result = quick_summary(
- query="renewable energy trends 2024",
- settings_snapshot=settings_snapshot,
- search_tool="wikipedia",
- iterations=2,
- questions_per_iteration=3,
- temperature=0.5,
- )
-
- print(
- f"Research completed with {custom_result.get('iterations_completed', 0)} iterations"
- )
- print("\nQuestions researched:")
- questions = custom_result.get("questions", {})
- for iteration, qs in questions.items():
- print(f"\n Iteration {iteration}:")
- for q in qs:
- print(f" - {q}")
-
- save_output(
- "quick_summary_custom.json", json.dumps(custom_result, indent=2)
- )
-
-
-def section_3_detailed_research():
- """Section 3: Conducting Detailed Research"""
- print_section("3. CONDUCTING DETAILED RESEARCH")
-
- with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = SettingsManager(session)
- settings_snapshot = settings_manager.get_all_settings()
-
- print("Starting detailed research (this may take a few minutes)...")
-
- result = detailed_research(
- query="impact of artificial intelligence on healthcare diagnostics",
- settings_snapshot=settings_snapshot,
- iterations=3,
- questions_per_iteration=4,
- search_tool="auto", # Use all available search engines
- enable_direct_summary=True,
- enable_search_engine=True,
- validate_sources=True,
- )
-
- print("\nResearch completed!")
- print(f"Research ID: {result['research_id']}")
- print(f"Summary length: {len(result['summary'])} characters")
-
- # Analyze findings
- findings = result.get("findings", [])
- print(f"\nTotal findings: {len(findings)}")
-
- if findings:
- print("\nTop 3 findings:")
- for i, finding in enumerate(findings[:3], 1):
- text = finding.get("text", "N/A")
- print(f"\n{i}. {text[:200]}...")
- if "source" in finding:
- print(f" Source: {finding['source']}")
-
- # Analyze sources
- sources = result.get("sources", [])
- print(f"\nTotal sources: {len(sources)}")
-
- # Group sources by type
- source_types = {}
- for source in sources:
- stype = (
- type(source).__name__
- if not isinstance(source, dict)
- else "dict"
- )
- source_types[stype] = source_types.get(stype, 0) + 1
-
- print("\nSource breakdown:")
- for stype, count in source_types.items():
- print(f" - {stype}: {count}")
-
- save_output("detailed_research.json", json.dumps(result, indent=2))
-
-
-def section_4_report_generation():
- """Section 4: Generating Comprehensive Reports"""
- print_section("4. GENERATING COMPREHENSIVE REPORTS")
-
- with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = SettingsManager(session)
- settings_snapshot = settings_manager.get_all_settings()
-
- print(
- "Generating comprehensive report (this will take several minutes)..."
- )
-
- report_result = generate_report(
- query="The future of quantum computing: applications and challenges",
- settings_snapshot=settings_snapshot,
- report_type="research_report",
- report_style="technical",
- iterations=4,
- questions_per_iteration=5,
- searches_per_section=3,
- include_raw_data=True,
- enable_citations=True,
- )
-
- print("\nReport generated successfully!")
- print(f"Research ID: {report_result['research_id']}")
-
- # Extract report content
- report_content = report_result.get("content", "")
- if not report_content and "report" in report_result:
- # Handle different report formats
- report = report_result["report"]
- if isinstance(report, dict):
- report_content = json.dumps(report, indent=2)
- else:
- report_content = str(report)
-
- # Show report statistics
- print("\nReport statistics:")
- print(f" - Total length: {len(report_content)} characters")
- print(f" - Sources used: {len(report_result.get('sources', []))}")
-
- # Extract sections if available
- if isinstance(report_result.get("report"), dict):
- print("\nReport sections:")
- for section, content in report_result["report"].items():
- if isinstance(content, str):
- print(f" - {section}: {len(content)} characters")
-
- # Save full report
- save_output("comprehensive_report.md", report_content)
- save_output(
- "comprehensive_report_metadata.json",
- json.dumps(
- {
- "research_id": report_result.get("research_id"),
- "query": report_result.get("query"),
- "created_at": datetime.now(UTC).isoformat(),
- "sources_count": len(report_result.get("sources", [])),
- "iterations": report_result.get("iterations_completed", 0),
- },
- indent=2,
- ),
- )
-
- print("\nFirst 1000 characters of report:")
- print(report_content[:1000] + "...")
-
-
-def section_5_search_engines():
- """Section 5: Using Different Search Engines"""
- print_section("5. USING DIFFERENT SEARCH ENGINES")
-
- with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = SettingsManager(session)
- settings_snapshot = settings_manager.get_all_settings()
-
- # Test different search engines
- search_engines = [
- ("wikipedia", "History of the Internet"),
- ("arxiv", "transformer neural networks"),
- ("semantic_scholar", "CRISPR gene editing applications"),
- ("pubmed", "COVID-19 vaccine efficacy"),
- ]
-
- results_summary = []
-
- for engine, query in search_engines:
- print(f"\nTesting {engine}: '{query}'")
- try:
- result = quick_summary(
- query=query,
- settings_snapshot=settings_snapshot,
- search_tool=engine,
- iterations=1,
- questions_per_iteration=2,
- )
-
- sources_count = len(result.get("sources", []))
- print(f" ✓ Success - Found {sources_count} sources")
-
- results_summary.append(
- {
- "engine": engine,
- "query": query,
- "sources": sources_count,
- "summary_length": len(result.get("summary", "")),
- }
- )
-
- except Exception as e:
- print(f" ✗ Failed: {str(e)[:100]}...")
- results_summary.append(
- {
- "engine": engine,
- "query": query,
- "error": str(e),
- }
- )
-
- # Meta search example
- print("\n\nMeta Search (combining multiple engines):")
- meta_result = quick_summary(
- query="climate change impact on biodiversity",
- settings_snapshot=settings_snapshot,
- search_tool="meta",
- meta_search_config={
- "engines": ["wikipedia", "semantic_scholar"],
- "aggregate": True,
- "deduplicate": True,
- },
- iterations=2,
- questions_per_iteration=3,
- )
-
- print(
- f" ✓ Meta search found {len(meta_result.get('sources', []))} total sources"
- )
-
- save_output(
- "search_engines_comparison.json",
- json.dumps(results_summary, indent=2),
- )
-
-
-def section_6_custom_retriever():
- """Section 6: Using Custom LangChain Retrievers"""
- print_section("6. USING CUSTOM LANGCHAIN RETRIEVERS")
-
- # Define a custom retriever
- class CustomDocumentRetriever(BaseRetriever):
- """Example custom retriever for demonstration."""
-
- def __init__(self, documents: List[Dict[str, str]]):
- """Initialize with a list of documents."""
- self.documents = documents
-
- def get_relevant_documents(self, query: str) -> List[Document]:
- """Return documents relevant to the query."""
- # Simple keyword matching for demonstration
- query_lower = query.lower()
- relevant_docs = []
-
- for doc in self.documents:
- if any(
- word in doc["content"].lower()
- for word in query_lower.split()
- ):
- relevant_docs.append(
- Document(
- page_content=doc["content"],
- metadata={
- "title": doc.get("title", "Untitled"),
- "source": doc.get("source", "custom_retriever"),
- "relevance": "high",
- },
- )
- )
-
- return relevant_docs[:3] # Return top 3
-
- async def aget_relevant_documents(self, query: str) -> List[Document]:
- """Async version."""
- return self.get_relevant_documents(query)
-
- # Create sample documents
- sample_docs = [
- {
- "title": "Introduction to Machine Learning",
- "content": "Machine learning is a subset of artificial intelligence that enables systems to learn from data.",
- "source": "ml_textbook.pdf",
- },
- {
- "title": "Deep Learning Fundamentals",
- "content": "Deep learning uses neural networks with multiple layers to learn complex patterns in data.",
- "source": "dl_guide.pdf",
- },
- {
- "title": "AI Ethics and Society",
- "content": "The deployment of AI systems raises important ethical considerations about bias and fairness.",
- "source": "ai_ethics.pdf",
- },
- ]
-
- # Create retriever instance
- custom_retriever = CustomDocumentRetriever(sample_docs)
-
- with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = SettingsManager(session)
- settings_snapshot = settings_manager.get_all_settings()
-
- print("Using custom retriever for research...")
-
- result = quick_summary(
- query="ethical considerations in machine learning",
- settings_snapshot=settings_snapshot,
- retrievers={"custom_docs": custom_retriever},
- search_tool="custom_docs", # Use only the custom retriever
- iterations=1,
- questions_per_iteration=2,
- )
-
- print(f"\nSummary: {result['summary'][:400]}...")
- print(
- f"\nSources from custom retriever: {len(result.get('sources', []))}"
- )
-
- # Show retrieved documents
- for i, source in enumerate(result.get("sources", [])[:3], 1):
- print(f"\n{i}. Source: {source}")
-
- # Hybrid search: custom retriever + web
- print("\n\nHybrid search (custom retriever + web):")
-
- hybrid_result = quick_summary(
- query="machine learning applications in healthcare",
- settings_snapshot=settings_snapshot,
- retrievers={"internal_docs": custom_retriever},
- search_tool="meta",
- meta_search_config={
- "retrievers": ["internal_docs"],
- "engines": ["wikipedia", "pubmed"],
- "aggregate": True,
- },
- iterations=2,
- questions_per_iteration=3,
- )
-
- print(
- f"Hybrid search found {len(hybrid_result.get('sources', []))} total sources"
- )
-
- save_output(
- "custom_retriever_results.json", json.dumps(result, indent=2)
- )
-
-
-def section_7_analyzing_results():
- """Section 7: Analyzing and Processing Results"""
- print_section("7. ANALYZING AND PROCESSING RESULTS")
-
- with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = SettingsManager(session)
- settings_snapshot = settings_manager.get_all_settings()
-
- # Conduct research for analysis
- result = detailed_research(
- query="breakthroughs in renewable energy storage",
- settings_snapshot=settings_snapshot,
- iterations=2,
- questions_per_iteration=3,
- )
-
- print("Analyzing research results...\n")
-
- # 1. Analyze iterations
- print("1. Iteration Analysis:")
- questions = result.get("questions", {})
- for iteration, qs in questions.items():
- print(f" Iteration {iteration}: {len(qs)} questions")
-
- # 2. Source analysis
- print("\n2. Source Analysis:")
- sources = result.get("sources", [])
- source_domains = {}
- for source in sources:
- if isinstance(source, dict) and "url" in source:
- domain = (
- source["url"].split("/")[2]
- if "/" in source["url"]
- else "unknown"
- )
- else:
- domain = "other"
- source_domains[domain] = source_domains.get(domain, 0) + 1
-
- print(" Top source domains:")
- for domain, count in sorted(
- source_domains.items(), key=lambda x: x[1], reverse=True
- )[:5]:
- print(f" - {domain}: {count} sources")
-
- # 3. Finding analysis
- print("\n3. Finding Analysis:")
- findings = result.get("findings", [])
- print(f" Total findings: {len(findings)}")
-
- # Categorize findings by length
- short_findings = [f for f in findings if len(f.get("text", "")) < 100]
- medium_findings = [
- f for f in findings if 100 <= len(f.get("text", "")) < 300
- ]
- long_findings = [f for f in findings if len(f.get("text", "")) >= 300]
-
- print(f" - Short findings (<100 chars): {len(short_findings)}")
- print(f" - Medium findings (100-300 chars): {len(medium_findings)}")
- print(f" - Long findings (>300 chars): {len(long_findings)}")
-
- # 4. Extract key topics (simple keyword extraction)
- print("\n4. Key Topics (based on word frequency):")
- from collections import Counter
- import re
-
- # Combine all text
- all_text = result.get("summary", "") + " ".join(
- [f.get("text", "") for f in findings]
- )
-
- # Simple word extraction (lowercase, alphanumeric only)
- words = re.findall(r"\b[a-z]+\b", all_text.lower())
-
- # Filter common words
- common_words = {
- "the",
- "a",
- "an",
- "and",
- "or",
- "but",
- "in",
- "on",
- "at",
- "to",
- "for",
- "of",
- "with",
- "by",
- "from",
- "as",
- "is",
- "was",
- "are",
- "were",
- "been",
- "that",
- "this",
- "these",
- "those",
- "it",
- "its",
- "they",
- "their",
- }
-
- filtered_words = [
- w for w in words if w not in common_words and len(w) > 3
- ]
-
- # Get top words
- word_freq = Counter(filtered_words)
- print(" Top keywords:")
- for word, count in word_freq.most_common(10):
- print(f" - {word}: {count} occurrences")
-
- # Save analysis
- analysis_report = {
- "query": result.get("query"),
- "research_id": result.get("research_id"),
- "iterations": len(questions),
- "total_sources": len(sources),
- "total_findings": len(findings),
- "source_domains": source_domains,
- "finding_distribution": {
- "short": len(short_findings),
- "medium": len(medium_findings),
- "long": len(long_findings),
- },
- "top_keywords": dict(word_freq.most_common(20)),
- }
-
- save_output(
- "research_analysis.json", json.dumps(analysis_report, indent=2)
- )
-
-
-def section_8_export_formats():
- """Section 8: Exporting in Different Formats"""
- print_section("8. EXPORTING IN DIFFERENT FORMATS")
-
- with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = SettingsManager(session)
- settings_snapshot = settings_manager.get_all_settings()
-
- # First, generate a research result
- print("Generating research for export examples...")
- result = quick_summary(
- query="future of sustainable transportation",
- settings_snapshot=settings_snapshot,
- iterations=2,
- questions_per_iteration=3,
- )
-
- research_id = result.get("research_id")
- print(f"Research ID: {research_id}")
-
- # Export formats
- export_formats = ["markdown", "quarto", "latex", "bibtex", "ris"]
-
- print("\nExporting in different formats:")
-
- for format_type in export_formats:
- try:
- print(f"\n{format_type.upper()} format:")
-
- # Create appropriate filename
- filename = f"research_export.{format_type}"
- if format_type == "latex":
- filename = "research_export.tex"
- elif format_type == "bibtex":
- filename = "research_export.bib"
-
- # Export using the utility function
- export_path = (
- os.path.join(OUTPUT_DIR, filename)
- if SAVE_OUTPUTS
- else filename
- )
-
- # For demonstration, we'll create simple exports
- if format_type == "markdown":
- content = f"# {result.get('query', 'Research Report')}\n\n"
- content += f"**Research ID**: {research_id}\n\n"
- content += f"## Summary\n\n{result.get('summary', '')}\n\n"
- content += "## Sources\n\n"
- for i, source in enumerate(
- result.get("sources", [])[:5], 1
- ):
- content += f"{i}. {source}\n"
-
- elif format_type == "quarto":
- content = f'---\ntitle: "{result.get("query", "Research Report")}"\n'
- content += 'author: "LDR Research System"\n'
- content += (
- f'date: "{datetime.now(UTC).strftime("%Y-%m-%d")}"\n'
- )
- content += "format: html\n---\n\n"
- content += f"## Summary\n\n{result.get('summary', '')}\n"
-
- elif format_type == "latex":
- content = "\\documentclass{article}\n"
- content += (
- f"\\title{{{result.get('query', 'Research Report')}}}\n"
- )
- content += "\\author{LDR Research System}\n"
- content += "\\date{\\today}\n"
- content += "\\begin{document}\n"
- content += "\\maketitle\n"
- content += "\\section{Summary}\n"
- content += f"{result.get('summary', '')}\n"
- content += "\\end{document}\n"
-
- elif format_type == "bibtex":
- content = ""
- for i, source in enumerate(
- result.get("sources", [])[:3], 1
- ):
- content += f"@misc{{source{i},\n"
- content += f" title = {{Source {i}}},\n"
- content += f" note = {{{str(source)}}},\n"
- content += " year = {2024}\n"
- content += "}\n\n"
-
- elif format_type == "ris":
- content = ""
- for i, source in enumerate(
- result.get("sources", [])[:3], 1
- ):
- content += "TY - WEB\n"
- content += f"TI - Source {i}\n"
- content += f"UR - {source if isinstance(source, str) else 'N/A'}\n"
- content += "Y1 - 2024\n"
- content += "ER -\n\n"
-
- # Save the export
- if SAVE_OUTPUTS:
- with open(export_path, "w", encoding="utf-8") as f:
- f.write(content)
- print(f" ✓ Exported to: {export_path}")
- else:
- print(f" ✓ Export generated ({len(content)} bytes)")
-
- except Exception as e:
- print(f" ✗ Failed: {e}")
-
-
-def section_9_advanced_features():
- """Section 9: Advanced Features and Tips"""
- print_section("9. ADVANCED FEATURES AND TIPS")
-
- with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = SettingsManager(session)
- settings_snapshot = settings_manager.get_all_settings()
-
- print("1. Performance Optimization Tips:")
- print(" - Use fewer iterations for quick results")
- print(" - Specify search_tool instead of 'auto' for faster searches")
- print(" - Use validate_sources=False to skip source validation")
- print(" - Enable caching for repeated queries")
-
- print("\n2. Error Handling Example:")
- try:
- # Intentionally use a non-existent search engine
- result = quick_summary(
- query="test query",
- settings_snapshot=settings_snapshot,
- search_tool="nonexistent_engine",
- iterations=1,
- )
- except Exception as e:
- print(f" Expected error caught: {type(e).__name__}")
- print(f" Error message: {str(e)[:100]}...")
-
- print("\n3. Memory-Efficient Research:")
- print(" For large research projects, use streaming and pagination:")
-
- # Example of processing results in chunks
- result = quick_summary(
- query="overview of renewable energy",
- settings_snapshot=settings_snapshot,
- iterations=1,
- questions_per_iteration=2,
- )
-
- # Process findings in batches
- findings = result.get("findings", [])
- batch_size = 10
- for i in range(0, len(findings), batch_size):
- batch = findings[i : i + batch_size]
- print(
- f" Processing batch {i // batch_size + 1}: {len(batch)} findings"
- )
-
- print("\n4. Custom Temperature and Model Settings:")
-
- # Get current temperature
- current_temp = settings_snapshot.get("llm.temperature", {}).get(
- "value", 0.7
- )
- print(f" Current temperature: {current_temp}")
-
- # Research with different temperatures
- temps = [0.3, 0.7, 1.0]
- for temp in temps:
- print(f"\n Testing temperature {temp}:")
- result = quick_summary(
- query="explain quantum computing",
- settings_snapshot=settings_snapshot,
- iterations=1,
- questions_per_iteration=1,
- temperature=temp,
- )
- print(f" Summary preview: {result['summary'][:100]}...")
-
- print("\n5. Monitoring and Debugging:")
- print(" - Check research_id for tracking")
- print(" - Monitor iterations_completed vs iterations requested")
- print(" - Review questions generated for each iteration")
- print(" - Analyze source quality and relevance")
-
- # Save configuration reference
- config_reference = {
- "authentication": {
- "method": "get_user_db_session",
- "requires": ["username", "password"],
- },
- "api_functions": {
- "quick_summary": "Fast research with summary",
- "detailed_research": "Comprehensive research with findings",
- "generate_report": "Full report generation",
- },
- "key_parameters": {
- "settings_snapshot": "Required for all API calls",
- "search_tool": ["auto", "wikipedia", "arxiv", "meta", "etc."],
- "iterations": "Number of research rounds",
- "questions_per_iteration": "Questions per round",
- "temperature": "LLM creativity (0.0-1.0)",
- },
- "export_formats": ["markdown", "quarto", "latex", "bibtex", "ris"],
- }
-
- save_output(
- "api_reference.json", json.dumps(config_reference, indent=2)
- )
-
-
-# ============================================================================
-# MAIN EXECUTION
-# ============================================================================
-
-
-def main():
- """Run the complete tutorial."""
- print("=" * 70)
- print(" LOCAL DEEP RESEARCH API TUTORIAL v1.0")
- print("=" * 70)
-
- # Check credentials
- if USERNAME == "your_username":
- print("\n⚠️ ERROR: Please update USERNAME and PASSWORD in this script!")
- print("\nSetup instructions:")
- print("1. Start LDR server: python -m local_deep_research.web.app")
- print("2. Open http://localhost:5000 in your browser")
- print("3. Register a new account")
- print("4. Configure an LLM provider in Settings")
- print("5. Update USERNAME and PASSWORD in this script")
- print("\nFor more details, see: docs/api-quickstart.md")
- return
-
- # Setup output directory
- setup_output_directory()
-
- try:
- # Run all tutorial sections
- if section_1_authentication():
- section_2_quick_summary()
- section_3_detailed_research()
- section_4_report_generation()
- section_5_search_engines()
- section_6_custom_retriever()
- section_7_analyzing_results()
- section_8_export_formats()
- section_9_advanced_features()
-
- print_section("TUTORIAL COMPLETED")
- print("✅ All examples completed successfully!")
-
- if SAVE_OUTPUTS:
- print(f"\nAll outputs saved to: {OUTPUT_DIR}")
- print("\nGenerated files:")
- for filename in os.listdir(OUTPUT_DIR):
- print(f" - {filename}")
-
- except KeyboardInterrupt:
- print("\n\n⚠️ Tutorial interrupted by user")
- except Exception as e:
- print(f"\n\n❌ Error during tutorial: {e}")
- import traceback
-
- traceback.print_exc()
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/api_usage/programmatic/example_with_ollama.py b/examples/api_usage/programmatic/example_with_ollama.py
deleted file mode 100644
index ea86a9816b..0000000000
--- a/examples/api_usage/programmatic/example_with_ollama.py
+++ /dev/null
@@ -1,158 +0,0 @@
-#!/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 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():
- print(f"\nIteration {iteration}:")
- for q in questions:
- print(f" - {q}")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/api_usage/programmatic/hybrid_search_example.py b/examples/api_usage/programmatic/hybrid_search_example.py
new file mode 100644
index 0000000000..c24afd7a20
--- /dev/null
+++ b/examples/api_usage/programmatic/hybrid_search_example.py
@@ -0,0 +1,406 @@
+#!/usr/bin/env python3
+"""
+Hybrid Search Example for Local Deep Research
+
+This example demonstrates how to combine multiple search sources:
+1. Multiple named retrievers for different document types
+2. Combining custom retrievers with web search
+3. Analyzing and comparing sources from different origins
+"""
+
+from typing import List
+from langchain.schema import Document, BaseRetriever
+from langchain_community.vectorstores import FAISS
+from langchain_community.embeddings import OllamaEmbeddings
+
+from local_deep_research.api import quick_summary, detailed_research
+from local_deep_research.api.settings_utils import create_settings_snapshot
+
+
+class TechnicalDocsRetriever(BaseRetriever):
+ """Mock retriever for technical documentation."""
+
+ def get_relevant_documents(self, query: str) -> List[Document]:
+ """Return mock technical documents."""
+ # In a real scenario, this would search actual technical docs
+ return [
+ Document(
+ page_content=f"Technical specification for {query}: Implementation requires careful consideration of system architecture, performance metrics, and scalability factors.",
+ metadata={
+ "source": "tech_docs",
+ "type": "specification",
+ "title": f"Technical Spec: {query}",
+ },
+ ),
+ Document(
+ page_content=f"Best practices for {query}: Follow industry standards, implement proper error handling, and ensure comprehensive testing coverage.",
+ metadata={
+ "source": "tech_docs",
+ "type": "best_practices",
+ "title": f"Best Practices: {query}",
+ },
+ ),
+ ]
+
+ async def aget_relevant_documents(self, query: str) -> List[Document]:
+ """Async version."""
+ return self.get_relevant_documents(query)
+
+
+class BusinessDocsRetriever(BaseRetriever):
+ """Mock retriever for business/strategy documents."""
+
+ def get_relevant_documents(self, query: str) -> List[Document]:
+ """Return mock business documents."""
+ return [
+ Document(
+ page_content=f"Business implications of {query}: Consider market impact, ROI analysis, and strategic alignment with organizational goals.",
+ metadata={
+ "source": "business_docs",
+ "type": "strategy",
+ "title": f"Business Strategy: {query}",
+ },
+ ),
+ Document(
+ page_content=f"Cost-benefit analysis for {query}: Initial investment requirements, expected returns, and risk assessment factors.",
+ metadata={
+ "source": "business_docs",
+ "type": "analysis",
+ "title": f"Cost Analysis: {query}",
+ },
+ ),
+ ]
+
+ async def aget_relevant_documents(self, query: str) -> List[Document]:
+ """Async version."""
+ return self.get_relevant_documents(query)
+
+
+def create_knowledge_base_retriever() -> BaseRetriever:
+ """Create a FAISS-based retriever with sample knowledge base documents."""
+ documents = [
+ Document(
+ page_content="Machine learning models require training data, validation strategies, and performance metrics for evaluation.",
+ metadata={"source": "ml_knowledge_base", "topic": "ml_basics"},
+ ),
+ Document(
+ page_content="Cloud computing provides scalable infrastructure, reducing capital expenditure and enabling flexible resource allocation.",
+ metadata={
+ "source": "cloud_knowledge_base",
+ "topic": "cloud_benefits",
+ },
+ ),
+ Document(
+ page_content="Agile methodology emphasizes iterative development, customer collaboration, and responding to change.",
+ metadata={"source": "project_knowledge_base", "topic": "agile"},
+ ),
+ Document(
+ page_content="Data privacy regulations like GDPR require explicit consent, data minimization, and user rights management.",
+ metadata={
+ "source": "compliance_knowledge_base",
+ "topic": "privacy",
+ },
+ ),
+ ]
+
+ # Create embeddings and vector store
+ embeddings = OllamaEmbeddings(model="nomic-embed-text")
+ vectorstore = FAISS.from_documents(documents, embeddings)
+ return vectorstore.as_retriever(search_kwargs={"k": 2})
+
+
+def demonstrate_multiple_retrievers():
+ """Show how to use multiple named retrievers for different document types."""
+ print("=" * 70)
+ print("MULTIPLE NAMED RETRIEVERS")
+ print("=" * 70)
+ print("""
+Using multiple specialized retrievers:
+- Technical documentation retriever
+- Business documentation retriever
+- Knowledge base retriever
+Each provides different perspectives on the same topic.
+ """)
+
+ # Create different retrievers
+ tech_retriever = TechnicalDocsRetriever()
+ business_retriever = BusinessDocsRetriever()
+ kb_retriever = create_knowledge_base_retriever()
+
+ # Configure settings
+ settings = create_settings_snapshot(
+ {
+ "programmatic_mode": True,
+ "search.tool": "auto", # Will use all provided retrievers
+ }
+ )
+
+ # Use multiple retrievers in research
+ result = quick_summary(
+ query="Implementing machine learning in production",
+ settings_snapshot=settings,
+ retrievers={
+ "technical": tech_retriever,
+ "business": business_retriever,
+ "knowledge_base": kb_retriever,
+ },
+ search_tool="auto", # Use all retrievers
+ iterations=2,
+ questions_per_iteration=2,
+ )
+
+ print("\nResearch Summary (first 400 chars):")
+ print(result["summary"][:400] + "...")
+
+ # Analyze sources by type
+ sources = result.get("sources", [])
+ print(f"\nTotal sources found: {len(sources)}")
+
+ # Group sources by retriever
+ source_types = {}
+ for source in sources:
+ if isinstance(source, dict):
+ source_type = source.get("metadata", {}).get("source", "unknown")
+ else:
+ source_type = "other"
+ source_types[source_type] = source_types.get(source_type, 0) + 1
+
+ print("\nSources by retriever:")
+ for stype, count in source_types.items():
+ print(f" - {stype}: {count} sources")
+
+ return result
+
+
+def demonstrate_retriever_plus_web():
+ """Show how to combine custom retrievers with web search."""
+ print("\n" + "=" * 70)
+ print("RETRIEVER + WEB SEARCH COMBINATION")
+ print("=" * 70)
+ print("""
+Combining internal knowledge with web search:
+- Internal: Custom retriever with proprietary knowledge
+- External: Wikipedia for general context
+This provides both specific and general information.
+ """)
+
+ # Create internal knowledge retriever
+ internal_retriever = create_knowledge_base_retriever()
+
+ # Configure settings to use both retriever and web
+ settings = create_settings_snapshot(
+ {
+ "programmatic_mode": True,
+ "search.tool": "wikipedia", # Also use Wikipedia
+ }
+ )
+
+ # Research combining internal and external sources
+ result = detailed_research(
+ query="Best practices for cloud migration",
+ settings_snapshot=settings,
+ retrievers={
+ "internal_kb": internal_retriever,
+ },
+ search_tool="wikipedia", # Also search Wikipedia
+ search_strategy="source-based",
+ iterations=2,
+ questions_per_iteration=3,
+ )
+
+ print(f"\nResearch ID: {result['research_id']}")
+ print(f"Summary length: {len(result['summary'])} characters")
+
+ # Analyze source distribution
+ sources = result.get("sources", [])
+ internal_sources = 0
+ external_sources = 0
+
+ for source in sources:
+ if isinstance(source, dict) and "knowledge_base" in str(source):
+ internal_sources += 1
+ else:
+ external_sources += 1
+
+ print("\nSource distribution:")
+ print(f" - Internal knowledge base: {internal_sources} sources")
+ print(f" - External (Wikipedia): {external_sources} sources")
+
+ # Show how different sources complement each other
+ print("\nComplementary insights from hybrid search:")
+ print(
+ " - Internal sources provide: Specific procedures, proprietary knowledge"
+ )
+ print(
+ " - External sources provide: Industry context, general best practices"
+ )
+
+ return result
+
+
+def demonstrate_source_analysis():
+ """Show how to analyze and compare sources from different origins."""
+ print("\n" + "=" * 70)
+ print("SOURCE ANALYSIS AND COMPARISON")
+ print("=" * 70)
+ print("""
+Analyzing source quality and relevance:
+- Track source origins
+- Compare information consistency
+- Identify unique insights from each source type
+ """)
+
+ # Create multiple retrievers
+ tech_retriever = TechnicalDocsRetriever()
+ business_retriever = BusinessDocsRetriever()
+
+ settings = create_settings_snapshot(
+ {
+ "programmatic_mode": True,
+ "search.tool": "wikipedia",
+ }
+ )
+
+ # Run research with detailed source tracking
+ result = quick_summary(
+ query="Artificial intelligence implementation strategies",
+ settings_snapshot=settings,
+ retrievers={
+ "technical": tech_retriever,
+ "business": business_retriever,
+ },
+ search_tool="wikipedia", # Also use web search
+ iterations=2,
+ questions_per_iteration=2,
+ )
+
+ # Detailed source analysis
+ print("\nSource Analysis:")
+ sources = result.get("sources", [])
+
+ # Categorize sources
+ source_categories = {"technical": [], "business": [], "web": []}
+
+ for source in sources:
+ if isinstance(source, dict):
+ source_type = source.get("metadata", {}).get("source", "")
+ if "tech" in source_type:
+ source_categories["technical"].append(source)
+ elif "business" in source_type:
+ source_categories["business"].append(source)
+ else:
+ source_categories["web"].append(source)
+ else:
+ source_categories["web"].append(source)
+
+ # Report on each category
+ for category, category_sources in source_categories.items():
+ print(f"\n{category.upper()} Sources ({len(category_sources)}):")
+ if category_sources:
+ for i, source in enumerate(category_sources[:2], 1): # Show first 2
+ if isinstance(source, dict):
+ title = source.get("metadata", {}).get("title", "Untitled")
+ print(f" {i}. {title}")
+ else:
+ print(f" {i}. {str(source)[:60]}...")
+
+ # Show findings breakdown
+ findings = result.get("findings", [])
+ print(f"\nTotal findings: {len(findings)}")
+ print("Findings provide integrated insights from all source types")
+
+ return result
+
+
+def demonstrate_meta_search_config():
+ """Show how to use meta search configuration for complex setups."""
+ print("\n" + "=" * 70)
+ print("META SEARCH CONFIGURATION")
+ print("=" * 70)
+ print("""
+Using meta search for sophisticated search strategies:
+- Combine multiple search engines
+- Configure aggregation and deduplication
+- Control search priority and weighting
+ """)
+
+ # Create retrievers
+ tech_retriever = TechnicalDocsRetriever()
+
+ settings = create_settings_snapshot(
+ {
+ "programmatic_mode": True,
+ }
+ )
+
+ # Advanced meta search configuration
+ result = quick_summary(
+ query="Quantum computing applications",
+ settings_snapshot=settings,
+ retrievers={
+ "tech_docs": tech_retriever,
+ },
+ search_tool="meta", # Use meta search
+ meta_search_config={
+ "retrievers": ["tech_docs"], # Include custom retriever
+ "engines": ["wikipedia", "arxiv"], # Also search these
+ "aggregate": True, # Combine results
+ "deduplicate": True, # Remove duplicate content
+ "max_results_per_engine": 5, # Limit per source
+ },
+ iterations=2,
+ questions_per_iteration=3,
+ )
+
+ print("\nMeta search results:")
+ print(f" - Total sources: {len(result.get('sources', []))}")
+ print(f" - Summary length: {len(result.get('summary', ''))} chars")
+ print(f" - Findings: {len(result.get('findings', []))}")
+
+ print("\nMeta search advantages:")
+ print(" - Comprehensive coverage from multiple sources")
+ print(" - Automatic deduplication of similar content")
+ print(" - Balanced perspective from different source types")
+
+ return result
+
+
+def main():
+ """Run all hybrid search demonstrations."""
+ print("=" * 70)
+ print("LOCAL DEEP RESEARCH - HYBRID SEARCH DEMONSTRATION")
+ print("=" * 70)
+ print("""
+This example shows how to combine multiple search sources:
+- Custom retrievers for proprietary knowledge
+- Web search engines for public information
+- Meta search for sophisticated strategies
+ """)
+
+ # Run demonstrations
+ demonstrate_multiple_retrievers()
+ demonstrate_retriever_plus_web()
+ demonstrate_source_analysis()
+ demonstrate_meta_search_config()
+
+ print("\n" + "=" * 70)
+ print("KEY TAKEAWAYS")
+ print("=" * 70)
+ print("""
+1. Multiple Retrievers: Use specialized retrievers for different document types
+2. Hybrid Search: Combine internal knowledge with web search for comprehensive results
+3. Source Analysis: Track and analyze sources to understand information origin
+4. Meta Search: Configure complex search strategies with aggregation and deduplication
+
+Best Practices:
+- Name your retrievers descriptively for easy tracking
+- Balance internal and external sources based on your needs
+- Use source analysis to verify information consistency
+- Configure meta search for optimal result aggregation
+ """)
+
+ print("\n✓ Hybrid search demonstration complete!")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/api_usage/programmatic/programmatic_access_v1.py b/examples/api_usage/programmatic/programmatic_access_v1.py
deleted file mode 100644
index ecb88d1888..0000000000
--- a/examples/api_usage/programmatic/programmatic_access_v1.py
+++ /dev/null
@@ -1,329 +0,0 @@
-"""
-Programmatic Access Examples for Local Deep Research v1.0+
-
-This script demonstrates how to use LDR's Python API directly with authentication.
-For interactive exploration, see programmatic_access.ipynb
-
-Requirements:
-- LDR v1.0+ (with authentication features)
-- User account created through web interface
-- LLM provider configured in settings
-"""
-
-from datetime import datetime, UTC
-
-# Import LDR components
-from local_deep_research.api.research_functions import (
- quick_summary,
- detailed_research,
- generate_report,
-)
-from local_deep_research.database.session_context import get_user_db_session
-from local_deep_research.config.llm_config import get_available_providers
-from local_deep_research.settings import SettingsManager
-
-# Configuration - UPDATE THESE!
-USERNAME = "your_username" # Change this to your LDR username
-PASSWORD = "your_password" # Change this to your LDR password
-
-
-def example_basic_usage():
- """Example 1: Basic programmatic usage with authentication."""
- print("=== Example 1: Basic Usage ===")
-
- try:
- with get_user_db_session(
- username=USERNAME, password=PASSWORD
- ) as session:
- # Create settings manager
- settings_manager = SettingsManager(session)
- settings_snapshot = settings_manager.get_all_settings()
-
- # Show current configuration
- provider = settings_snapshot.get("llm.provider", {}).get(
- "value", "Not set"
- )
- model = settings_snapshot.get("llm.model", {}).get(
- "value", "Not set"
- )
-
- print(f"Authenticated as: {USERNAME}")
- print(f"LLM Provider: {provider}")
- print(f"LLM Model: {model}")
-
- # Run quick summary
- result = quick_summary(
- query="What is artificial intelligence?",
- settings_snapshot=settings_snapshot,
- iterations=1,
- questions_per_iteration=2,
- )
-
- print(f"\nSummary: {result['summary'][:300]}...")
- print(f"Sources: {len(result.get('sources', []))}")
- print(f"Research ID: {result.get('research_id', 'N/A')}")
-
- except Exception as e:
- print(f"Error: {e}")
- print("\nMake sure you have:")
- print("1. Created a user account")
- print("2. Configured an LLM provider")
- print("3. Updated USERNAME and PASSWORD in this script")
-
-
-def example_custom_parameters():
- """Example 2: Research with custom parameters."""
- print("\n=== Example 2: Custom Parameters ===")
-
- with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = SettingsManager(session, USERNAME)
- settings_snapshot = settings_manager.get_all_settings()
-
- # Custom research parameters
- result = quick_summary(
- query="Explain quantum computing applications in cryptography",
- settings_snapshot=settings_snapshot,
- search_tool="auto", # Use all available search engines
- search_strategy="focused-iteration",
- iterations=3,
- questions_per_iteration=4,
- model_name=None, # Use default from settings
- temperature=0.7,
- local_context=3000,
- web_context=3000,
- follow_up_questions=True,
- )
-
- print(f"Summary length: {len(result['summary'])} characters")
- print(f"Sources: {len(result.get('sources', []))}")
- print(f"Findings: {len(result.get('findings', []))}")
-
- # Show some findings
- findings = result.get("findings", [])[:3]
- if findings:
- print("\nTop findings:")
- for i, finding in enumerate(findings, 1):
- print(f"{i}. {finding.get('text', 'N/A')[:100]}...")
-
-
-def example_detailed_research():
- """Example 3: Detailed research with full analysis."""
- print("\n=== Example 3: Detailed Research ===")
-
- with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = SettingsManager(session, USERNAME)
- settings_snapshot = settings_manager.get_all_settings()
-
- # Run detailed research
- result = detailed_research(
- query="Impact of renewable energy on climate change mitigation",
- settings_snapshot=settings_snapshot,
- iterations=5, # More thorough research
- questions_per_iteration=5,
- search_tool="auto",
- require_all_sources=True, # Ensure source validation
- enable_search_engine=True,
- )
-
- print(f"Research ID: {result['research_id']}")
- print(f"Summary: {result['summary'][:500]}...")
- print("\nStatistics:")
- print(f"- Total sources: {len(result.get('sources', []))}")
- print(f"- Total findings: {len(result.get('findings', []))}")
- print(
- f"- Iterations completed: {result.get('iterations_completed', 'N/A')}"
- )
-
- # Analyze sources
- sources = result.get("sources", [])
- if sources:
- print("\nSource types:")
- source_types = {}
- for source in sources:
- source_type = type(source).__name__
- source_types[source_type] = source_types.get(source_type, 0) + 1
-
- for stype, count in source_types.items():
- print(f" - {stype}: {count}")
-
-
-def example_generate_report():
- """Example 4: Generate a full research report."""
- print("\n=== Example 4: Generate Report ===")
-
- with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = SettingsManager(session, USERNAME)
- settings_snapshot = settings_manager.get_all_settings()
-
- # Generate comprehensive report
- print("Generating report (this may take a while)...")
-
- result = generate_report(
- query="Comprehensive analysis of machine learning in healthcare",
- settings_snapshot=settings_snapshot,
- report_type="research_report",
- iterations=3,
- questions_per_iteration=4,
- include_raw_data=False,
- enable_citations=True,
- )
-
- print("\nReport generated!")
- print(f"Research ID: {result['research_id']}")
- print(f"Title: {result.get('title', 'N/A')}")
-
- # Show report structure
- report = result.get("report", {})
- if isinstance(report, dict):
- print("\nReport sections:")
- for section, content in report.items():
- if isinstance(content, str):
- print(f" - {section}: {len(content)} characters")
- elif isinstance(content, list):
- print(f" - {section}: {len(content)} items")
-
- # Save report excerpt
- summary = result.get("summary", "")
- if summary:
- filename = (
- f"report_{result.get('research_id', 'unknown')}_excerpt.txt"
- )
- with open(filename, "w") as f:
- f.write(f"Title: {result.get('title', 'Research Report')}\n")
- f.write(f"Date: {datetime.now(UTC).isoformat()}\n")
- f.write(f"Query: {result.get('query', 'N/A')}\n")
- f.write("\n" + "=" * 50 + "\n\n")
- f.write("SUMMARY\n")
- f.write("=" * 50 + "\n")
- f.write(summary[:1000] + "...")
- print(f"\nReport excerpt saved to: {filename}")
-
-
-def example_check_providers():
- """Example 5: Check available providers and settings."""
- print("\n=== Example 5: Available Providers ===")
-
- with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = SettingsManager(session, USERNAME)
- settings_snapshot = settings_manager.get_all_settings()
-
- # Get available providers (with settings context)
- from local_deep_research.config.thread_settings import (
- set_settings_context,
- )
-
- set_settings_context(settings_snapshot)
-
- providers = get_available_providers(settings_snapshot)
-
- print("Available LLM providers:")
- for provider_id, provider_name in providers.items():
- print(f" - {provider_id}: {provider_name}")
-
- # Show current provider details
- current_provider = settings_snapshot.get("llm.provider", {}).get(
- "value"
- )
- if current_provider:
- print(f"\nCurrent provider: {current_provider}")
-
- # Show provider-specific settings
- provider_settings = {
- k: v
- for k, v in settings_snapshot.items()
- if k.startswith(f"llm.{current_provider}.")
- }
-
- if provider_settings:
- print(f"\n{current_provider} settings:")
- for key, setting in provider_settings.items():
- # Don't show API keys
- if "api_key" not in key.lower():
- print(f" - {key}: {setting.get('value', 'N/A')}")
-
-
-def example_search_engines():
- """Example 6: Using specific search engines."""
- print("\n=== Example 6: Search Engine Selection ===")
-
- with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = SettingsManager(session, USERNAME)
- settings_snapshot = settings_manager.get_all_settings()
-
- # Example with Wikipedia only
- print("1. Wikipedia-only search:")
- result = quick_summary(
- query="History of the Internet",
- settings_snapshot=settings_snapshot,
- search_tool="wikipedia",
- iterations=1,
- questions_per_iteration=3,
- )
- print(f" Sources: {len(result.get('sources', []))}")
-
- # Example with academic sources
- print("\n2. Academic search (arXiv):")
- result = quick_summary(
- query="Recent advances in transformer neural networks",
- settings_snapshot=settings_snapshot,
- search_tool="arxiv",
- iterations=1,
- questions_per_iteration=2,
- )
- print(f" Sources: {len(result.get('sources', []))}")
-
- # Example with meta search (multiple engines)
- print("\n3. Meta search (multiple engines):")
- result = quick_summary(
- query="Climate change impact on biodiversity",
- settings_snapshot=settings_snapshot,
- search_tool="meta",
- meta_search_config={
- "engines": ["wikipedia", "semantic_scholar"],
- "aggregate": True,
- },
- iterations=2,
- questions_per_iteration=3,
- )
- print(f" Sources: {len(result.get('sources', []))}")
-
-
-def main():
- """Run all examples."""
- print("=== LDR v1.0 Programmatic Access Examples ===")
-
- if USERNAME == "your_username":
- print(
- "\n⚠️ WARNING: Please update USERNAME and PASSWORD in this script!"
- )
- print("\nSteps to get started:")
- print("1. Start the server: python -m local_deep_research.web.app")
- print("2. Open http://localhost:5000 in your browser")
- print("3. Register a new account")
- print("4. Configure your LLM provider in Settings")
- print("5. Update USERNAME and PASSWORD in this script")
- print("\nFor more details, see: docs/api-quickstart.md")
- return
-
- try:
- # Run examples
- example_basic_usage()
- example_custom_parameters()
- example_detailed_research()
- example_generate_report()
- example_check_providers()
- example_search_engines()
-
- print("\n✅ All examples completed successfully!")
-
- except Exception as e:
- print(f"\n❌ Error running examples: {e}")
- print("\nTroubleshooting:")
- print("1. Ensure the server has been started at least once")
- print("2. Verify your username and password")
- print("3. Check that you've configured an LLM provider")
- print("4. See logs for more details")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/api_usage/programmatic/quick_summary_example.py b/examples/api_usage/programmatic/quick_summary_example.py
deleted file mode 100644
index c84defce24..0000000000
--- a/examples/api_usage/programmatic/quick_summary_example.py
+++ /dev/null
@@ -1,73 +0,0 @@
-#!/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/retriever_usage_example.py b/examples/api_usage/programmatic/retriever_usage_example.py
deleted file mode 100644
index 59e28f3ce6..0000000000
--- a/examples/api_usage/programmatic/retriever_usage_example.py
+++ /dev/null
@@ -1,251 +0,0 @@
-"""
-Example of using LangChain retrievers with LDR v1.0+
-
-This example shows how to use any LangChain retriever as a search engine in LDR
-with the new authentication and settings requirements.
-
-Requirements:
-- LDR v1.0+ (with authentication features)
-- User account created through web interface
-- LLM provider configured in settings
-"""
-
-import os
-from typing import List
-
-from langchain.embeddings import OpenAIEmbeddings
-from langchain.schema import BaseRetriever, Document
-from langchain.vectorstores import FAISS
-
-# Import LDR functions and authentication
-from local_deep_research.api.research_functions import (
- detailed_research,
- quick_summary,
-)
-from local_deep_research.database.session_context import get_user_db_session
-from local_deep_research.settings import SettingsManager
-
-# Configuration - UPDATE THESE!
-USERNAME = "your_username" # Change this to your LDR username
-PASSWORD = "your_password" # Change this to your LDR password
-
-
-# Example 1: Simple mock retriever for testing
-class MockRetriever(BaseRetriever):
- """Mock retriever for demonstration."""
-
- def get_relevant_documents(self, query: str) -> List[Document]:
- """Return mock documents."""
- return [
- Document(
- page_content=f"This is a mock document about {query}. It contains relevant information.",
- metadata={
- "title": f"Document about {query}",
- "source": "mock_db",
- },
- ),
- Document(
- page_content=f"Another document discussing {query} in detail.",
- metadata={
- "title": f"Detailed analysis of {query}",
- "source": "mock_db",
- },
- ),
- ]
-
- async def aget_relevant_documents(self, query: str) -> List[Document]:
- """Async version."""
- return self.get_relevant_documents(query)
-
-
-def example_single_retriever():
- """Example using a single retriever with authentication."""
- print("=== Example 1: Single Retriever with Authentication ===")
-
- # Create a mock retriever
- retriever = MockRetriever()
-
- # Authenticate and get settings
- with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- # Get settings snapshot for thread safety
- settings_manager = SettingsManager(session, USERNAME)
- settings_snapshot = settings_manager.get_all_settings()
-
- print(f"Authenticated as: {USERNAME}")
- print(
- f"Using LLM provider: {settings_snapshot.get('llm.provider', {}).get('value', 'Not set')}"
- )
-
- # Use retriever with LDR
- result = quick_summary(
- query="What are the best practices for ML deployment?",
- retrievers={"mock_kb": retriever},
- search_tool="mock_kb", # Use only this retriever
- iterations=2,
- questions_per_iteration=3,
- settings_snapshot=settings_snapshot, # Required in v1.0+
- )
-
- print(f"Summary: {result['summary'][:200]}...")
- print(f"Sources: {len(result.get('sources', []))} sources found")
-
-
-def example_multiple_retrievers():
- """Example using multiple retrievers with authentication."""
- print("\n=== Example 2: Multiple Retrievers ===")
-
- # Create multiple mock retrievers
- tech_retriever = MockRetriever()
- business_retriever = MockRetriever()
-
- with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = SettingsManager(session, USERNAME)
- settings_snapshot = settings_manager.get_all_settings()
-
- # Use them with LDR
- result = detailed_research(
- query="What are the business and technical implications of ML deployment?",
- retrievers={
- "tech_docs": tech_retriever,
- "business_docs": business_retriever,
- },
- search_tool="auto", # Use all retrievers
- iterations=3,
- settings_snapshot=settings_snapshot,
- )
-
- print(f"Research ID: {result['research_id']}")
- print(f"Summary: {result['summary'][:200]}...")
- print(f"Findings: {len(result['findings'])} findings")
-
-
-def example_hybrid_search():
- """Example mixing retrievers with web search."""
- print("\n=== Example 3: Hybrid Search (Retriever + Web) ===")
-
- # Create retriever
- retriever = MockRetriever()
-
- with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = SettingsManager(session, USERNAME)
- settings_snapshot = settings_manager.get_all_settings()
-
- # Use retriever + web search
- result = quick_summary(
- query="Compare internal ML best practices with industry standards",
- retrievers={"internal_docs": retriever},
- search_tool="meta", # Meta search uses all available engines
- meta_search_config={
- "retrievers": ["internal_docs"],
- "engines": ["wikipedia", "arxiv"], # Add web search
- },
- iterations=2,
- settings_snapshot=settings_snapshot,
- )
-
- print(f"Summary: {result['summary'][:200]}...")
- print(f"Sources: {len(result.get('sources', []))} sources")
-
- # Show source breakdown
- retriever_sources = [
- s for s in result.get("sources", []) if "mock_db" in str(s)
- ]
- web_sources = [
- s for s in result.get("sources", []) if "mock_db" not in str(s)
- ]
- print(f" - Retriever sources: {len(retriever_sources)}")
- print(f" - Web sources: {len(web_sources)}")
-
-
-def example_real_vector_store():
- """Example using a real vector store (requires OpenAI API key)."""
- print("\n=== Example 4: Real Vector Store (FAISS) ===")
-
- # Check if OpenAI API key is available
- openai_api_key = os.getenv("OPENAI_API_KEY")
- if not openai_api_key:
- print("Skipping: OPENAI_API_KEY environment variable not set")
- return
-
- try:
- # Create some sample documents
- documents = [
- Document(
- page_content="Machine learning deployment requires careful consideration of model versioning.",
- metadata={"source": "ml_guide.pdf", "page": 1},
- ),
- Document(
- page_content="CI/CD pipelines are essential for reliable ML model deployment.",
- metadata={"source": "ml_guide.pdf", "page": 2},
- ),
- Document(
- page_content="Model monitoring helps detect drift and performance degradation.",
- metadata={"source": "ml_guide.pdf", "page": 3},
- ),
- ]
-
- # Create embeddings and vector store
- embeddings = OpenAIEmbeddings(openai_api_key=openai_api_key)
- vector_store = FAISS.from_documents(documents, embeddings)
-
- # Convert to retriever
- retriever = vector_store.as_retriever(search_kwargs={"k": 2})
-
- with get_user_db_session(
- username=USERNAME, password=PASSWORD
- ) as session:
- settings_manager = SettingsManager(session)
- settings_snapshot = settings_manager.get_all_settings()
-
- # Use with LDR
- result = quick_summary(
- query="What are the key aspects of ML deployment?",
- retrievers={"ml_docs": retriever},
- search_tool="ml_docs",
- iterations=1,
- settings_snapshot=settings_snapshot,
- )
-
- print(f"Summary: {result['summary'][:300]}...")
- print(f"Sources used: {len(result.get('sources', []))}")
-
- except Exception as e:
- print(f"Error: {e}")
- print("Make sure you have configured OpenAI in LDR settings")
-
-
-def main():
- """Run all examples."""
- print("=== LDR v1.0 Retriever Examples ===")
- print(f"Username: {USERNAME}")
-
- if USERNAME == "your_username":
- print(
- "\n⚠️ WARNING: Please update USERNAME and PASSWORD in this script!"
- )
- print(" Create an account through the web interface first:")
- print(" 1. Run: python -m local_deep_research.web.app")
- print(" 2. Open: http://localhost:5000")
- print(" 3. Register an account")
- print(" 4. Configure your LLM provider in Settings")
- return
-
- try:
- # Run examples
- example_single_retriever()
- example_multiple_retrievers()
- example_hybrid_search()
- example_real_vector_store()
-
- except Exception as e:
- print(f"\n❌ Error: {e}")
- print("\nCommon issues:")
- print(
- "- Ensure LDR server has been started at least once to create databases"
- )
- print("- Verify your username and password are correct")
- print("- Check that you have configured an LLM provider in settings")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/api_usage/programmatic/search_strategies_example.py b/examples/api_usage/programmatic/search_strategies_example.py
new file mode 100644
index 0000000000..fb23afd30e
--- /dev/null
+++ b/examples/api_usage/programmatic/search_strategies_example.py
@@ -0,0 +1,224 @@
+#!/usr/bin/env python3
+"""
+Search Strategies Example for Local Deep Research
+
+This example demonstrates the two main search strategies:
+1. source-based: Comprehensive research with source citation
+2. focused-iteration: Iterative refinement of research questions
+
+Each strategy has different strengths and use cases.
+"""
+
+from local_deep_research.api import quick_summary, detailed_research
+from local_deep_research.api.settings_utils import create_settings_snapshot
+
+
+def demonstrate_source_based_strategy():
+ """
+ Source-based strategy:
+ - Focuses on gathering and synthesizing information from multiple sources
+ - Provides detailed citations and source tracking
+ - Best for: Academic research, fact-checking, comprehensive reports
+ """
+ print("=" * 70)
+ print("SOURCE-BASED STRATEGY")
+ print("=" * 70)
+ print("""
+This strategy:
+- Systematically searches for sources related to your topic
+- Synthesizes information across multiple sources
+- Provides detailed citations for all claims
+- Ideal for research requiring source verification
+ """)
+
+ # Configure settings for programmatic mode
+ settings = create_settings_snapshot(
+ {
+ "programmatic_mode": True,
+ "search.tool": "wikipedia", # Using Wikipedia for demonstration
+ }
+ )
+
+ # Run research with source-based strategy
+ result = detailed_research(
+ query="What are the main causes of climate change?",
+ settings_snapshot=settings,
+ search_strategy="source-based", # Explicitly set strategy
+ iterations=2, # Number of research iterations
+ questions_per_iteration=3, # Questions to explore per iteration
+ )
+
+ print(f"Research ID: {result['research_id']}")
+ print("\nSummary (first 500 chars):")
+ print(result["summary"][:500] + "...")
+
+ # Show sources found
+ sources = result.get("sources", [])
+ print(f"\nSources found: {len(sources)}")
+ if sources:
+ print("\nFirst 3 sources:")
+ for i, source in enumerate(sources[:3], 1):
+ print(f" {i}. {source}")
+
+ # Show the questions that were researched
+ questions = result.get("questions", {})
+ print(f"\nQuestions researched across {len(questions)} iterations:")
+ for iteration, qs in questions.items():
+ print(f"\n Iteration {iteration}:")
+ for q in qs[:2]: # Show first 2 questions per iteration
+ print(f" - {q}")
+
+ return result
+
+
+def demonstrate_focused_iteration_strategy():
+ """
+ Focused-iteration strategy:
+ - Iteratively refines the research based on previous findings
+ - Adapts questions based on what's been learned
+ - Best for: Deep dives, evolving research questions, exploratory research
+ """
+ print("\n" + "=" * 70)
+ print("FOCUSED-ITERATION STRATEGY")
+ print("=" * 70)
+ print("""
+This strategy:
+- Starts with initial research on the topic
+- Analyzes findings to generate more targeted questions
+- Iteratively refines understanding through multiple rounds
+- Ideal for complex topics requiring deep exploration
+ """)
+
+ # Configure settings
+ settings = create_settings_snapshot(
+ {
+ "programmatic_mode": True,
+ "search.tool": "wikipedia",
+ }
+ )
+
+ # Run research with focused-iteration strategy
+ result = quick_summary(
+ query="How do neural networks learn?",
+ settings_snapshot=settings,
+ search_strategy="focused-iteration", # Use focused iteration
+ iterations=3, # More iterations for deeper exploration
+ questions_per_iteration=2, # Fewer but more focused questions
+ temperature=0.7, # Slightly higher for creative question generation
+ )
+
+ print("\nSummary (first 500 chars):")
+ print(result["summary"][:500] + "...")
+
+ # Show how questions evolved
+ questions = result.get("questions", {})
+ if questions:
+ print("\nQuestion evolution across iterations:")
+ for iteration, qs in questions.items():
+ print(f"\n Iteration {iteration}:")
+ for q in qs:
+ print(f" - {q}")
+
+ # Show findings
+ findings = result.get("findings", [])
+ print(f"\nKey findings: {len(findings)}")
+ if findings:
+ print("\nFirst 2 findings:")
+ for i, finding in enumerate(findings[:2], 1):
+ text = (
+ finding.get("text", "N/A")
+ if isinstance(finding, dict)
+ else str(finding)
+ )
+ print(f" {i}. {text[:150]}...")
+
+ return result
+
+
+def compare_strategies():
+ """
+ Direct comparison of both strategies on the same topic.
+ """
+ print("\n" + "=" * 70)
+ print("STRATEGY COMPARISON")
+ print("=" * 70)
+ print(
+ "\nComparing both strategies on the same topic: 'Quantum Computing Applications'\n"
+ )
+
+ settings = create_settings_snapshot(
+ {
+ "programmatic_mode": True,
+ "search.tool": "wikipedia",
+ }
+ )
+
+ # Same topic, different strategies
+ topic = "Quantum computing applications in cryptography"
+
+ print("1. Source-based approach:")
+ source_result = quick_summary(
+ query=topic,
+ settings_snapshot=settings,
+ search_strategy="source-based",
+ iterations=2,
+ questions_per_iteration=3,
+ )
+ print(f" - Sources found: {len(source_result.get('sources', []))}")
+ print(f" - Summary length: {len(source_result.get('summary', ''))} chars")
+ print(f" - Findings: {len(source_result.get('findings', []))}")
+
+ print("\n2. Focused-iteration approach:")
+ focused_result = quick_summary(
+ query=topic,
+ settings_snapshot=settings,
+ search_strategy="focused-iteration",
+ iterations=2,
+ questions_per_iteration=3,
+ )
+ print(f" - Sources found: {len(focused_result.get('sources', []))}")
+ print(
+ f" - Summary length: {len(focused_result.get('summary', ''))} chars"
+ )
+ print(f" - Findings: {len(focused_result.get('findings', []))}")
+
+ print("\n" + "=" * 70)
+ print("WHEN TO USE EACH STRATEGY")
+ print("=" * 70)
+ print("""
+Use SOURCE-BASED when you need:
+- Comprehensive coverage with citations
+- Academic or professional research
+- Fact-checking and verification
+- Documentation with source tracking
+
+Use FOCUSED-ITERATION when you need:
+- Deep exploration of complex topics
+- Adaptive research that evolves
+- Discovery of unexpected connections
+- Exploratory or investigative research
+ """)
+
+
+def main():
+ """Run all demonstrations."""
+ print("=" * 70)
+ print("LOCAL DEEP RESEARCH - SEARCH STRATEGIES DEMONSTRATION")
+ print("=" * 70)
+
+ # Demonstrate each strategy
+ demonstrate_source_based_strategy()
+ demonstrate_focused_iteration_strategy()
+
+ # Compare strategies
+ compare_strategies()
+
+ print("\n✓ Search strategies demonstration complete!")
+ print("\nNote: Both strategies can be combined with different search tools")
+ print(
+ "(wikipedia, arxiv, searxng, etc.) and custom parameters for optimal results."
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/api_usage/programmatic/simple_programmatic_example.py b/examples/api_usage/programmatic/simple_programmatic_example.py
index 95b20c2d6a..68a081777c 100755
--- a/examples/api_usage/programmatic/simple_programmatic_example.py
+++ b/examples/api_usage/programmatic/simple_programmatic_example.py
@@ -64,13 +64,21 @@ print(
# Example 4: Generate and Save a Report
print("\n=== Generate Report (Optional - Uncomment to run) ===")
print("Note: Report generation can take several minutes")
-# Uncomment the following to generate a full report:
+
+# TODO: generate_report() currently requires authentication to work properly.
+# This will be fixed in a separate PR to enable programmatic report generation.
+# See: https://github.com/[org]/[repo]/issues/[number] for tracking
+
+# Uncomment the following to generate a full report (after auth fix):
"""
+from local_deep_research.api import generate_report
+
report = generate_report(
query="Future of artificial intelligence",
output_file="ai_future_report.md", # Save directly to file
searches_per_section=2,
- iterations=1
+ iterations=1,
+ settings_snapshot=settings_snapshot # Will work after auth fix
)
print(f"Report saved to: {report.get('file_path', 'ai_future_report.md')}")
print(f"Report length: {len(report['content'])} characters")