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: migrate settings and everything else to a single ldr.db, use db as a main source of configs

hashedvikinge7584cd4f68a
diff --git a/README.md b/README.md
index d7cbd7aa23..db931ac98c 100644
--- a/README.md
+++ b/README.md
@@ -1,383 +1,419 @@
-# Local Deep Research
-
-A powerful AI-powered research assistant that performs deep, iterative analysis using multiple LLMs and web searches. The system can be run locally for privacy or configured to use cloud-based LLMs for enhanced capabilities.
-
-<div align="center">
- <a href="https://www.youtube.com/watch?v=0ISreg9q0p0">
- <img src="https://img.youtube.com/vi/0ISreg9q0p0/0.jpg" alt="Local Deep Research">
- <br>
- <span>▶️ Watch Video</span>
- </a>
-</div>
-
-
-**Important for non-academic searches:** For normal web searches you will need SearXGN or an API key to a search provider like brave search or SerpAPI. The free searches are mostly academic search engines and will not help you for most normal searches.
-
-## Windows Installation
-
- Download the [Windows Installer](https://github.com/LearningCircuit/local-deep-research/releases/download/v0.1.0/LocalDeepResearch_Setup.exe) for easy one-click installation.
-
- **Requires Ollama (or other model provider configured in .env).**
- Download from https://ollama.ai and then pull a model
- ollama pull gemma3:12b
-
-## Quick Start (not required if installed with windows installer)
-
-```bash
-# Install the package
-pip install local-deep-research
-
-# Install required browser automation tools
-playwright install
-
-# For local models, install Ollama
-# Download from https://ollama.ai and then pull a model
-ollama pull gemma3:12b
-```
-
-Then run:
-
-```bash
-# Start the web interface (recommended)
-ldr-web # (OR python -m local_deep_research.web.app)
-
-# OR run the command line version
-ldr # (OR python -m local_deep_research.main)
-```
-
-Access the web interface at `http://127.0.0.1:5000` in your browser.
-
-## Docker Support
-
-Build the image first if you haven't already
-```bash
-docker build -t local-deep-research .
-```
-
-Quick Docker Run
-
-```bash
-# Run with default settings (connects to Ollama running on the host)
-docker run --network=host \
- -e LDR_LLM__PROVIDER="ollama" \
- -e LDR_LLM__MODEL="mistral" \
- local-deep-research
-```
-
-For comprehensive Docker setup information, see:
-- [Docker Usage Guide](https://github.com/LearningCircuit/local-deep-research/blob/main/docs/docker-usage-readme.md)
-- [Docker Compose Guide](https://github.com/LearningCircuit/local-deep-research/blob/main/docs/docker-compose-guide.md)
-
-## Programmatic Access
-
-Local Deep Research now provides a simple API for programmatic access to its research capabilities:
-
-```python
-import os
-# Set environment variables to control the LLM
-os.environ["LDR_LLM__MODEL"] = "mistral" # Specify model name
-
-from local_deep_research import quick_summary, generate_report, analyze_documents
-
-# Generate a quick research summary with custom parameters
-results = quick_summary(
- query="advances in fusion energy",
- search_tool="auto", # Auto-select the best search engine
- iterations=1, # Single research cycle for speed
- questions_per_iteration=2, # Generate 2 follow-up questions
- max_results=30, # Consider up to 30 search results
- temperature=0.7 # Control creativity of generation
-)
-print(results["summary"])
-```
-
-These functions provide flexible options for customizing the search parameters, iterations, and output formats. For more examples, see the [programmatic access tutorial](https://github.com/LearningCircuit/local-deep-research/blob/main/examples/programmatic_access.ipynb).
-
-
-## Features
-
-- 🔍 **Advanced Research Capabilities**
- - Automated deep research with intelligent follow-up questions
- - Proper inline citation and source verification
- - Multi-iteration analysis for comprehensive coverage
- - Full webpage content analysis (not just snippets)
-
-- 🤖 **Flexible LLM Support**
- - Local AI processing with Ollama models
- - Cloud LLM support (Claude, GPT)
- - Supports all Langchain models
- - Configurable model selection based on needs
-
-- 📊 **Rich Output Options**
- - Detailed research findings with proper citations
- - Well-structured comprehensive research reports
- - Quick summaries for rapid insights
- - Source tracking and verification
-
-- 🔒 **Privacy-Focused**
- - Runs entirely on your machine when using local models
- - Configurable search settings
- - Transparent data handling
-
-- 🌐 **Enhanced Search Integration**
- - **Auto-selection of search sources**: The "auto" search engine intelligently analyzes your query and selects the most appropriate search engine
- - Multiple search engines including Wikipedia, arXiv, PubMed, Semantic Scholar, and more
- - **Local RAG search for private documents** - search your own documents with vector embeddings
- - Full webpage content retrieval and intelligent filtering
-
-- 🎓 **Academic & Scientific Integration**
- - Direct integration with PubMed, arXiv, Wikipedia, Semantic Scholar
- - Properly formatted citations from academic sources
- - Report structure suitable for literature reviews
- - Cross-disciplinary synthesis of information
-
-## Configuration System
-
-The package automatically creates and manages configuration files in your user directory:
-
-- **Windows**: `Documents\LearningCircuit\local-deep-research\config\`
-- **Linux/Mac**: `~/.config/local_deep_research/config/`
-
-### Default Configuration Files
-
-When you first run the tool, it creates these configuration files:
-
-| File | Purpose |
-|------|---------|
-| `settings.toml` | General settings for research, web interface, and search |
-| `llm_config.py` | Advanced LLM configuration (rarely needs modification) |
-| `search_engines.toml` | Define and configure search engines |
-| `local_collections.toml` | Configure local document collections for RAG |
-| `.env` | Environment variables for configuration (recommended for API keys) |
-
-> **Note:** For comprehensive environment variable configuration, see our [Environment Variables Guide](https://github.com/LearningCircuit/local-deep-research/blob/main/docs/env_configuration.md).
-
-## Setting Up AI Models
-
-The system supports multiple LLM providers:
-
-### Local Models (via Ollama)
-
-1. [Install Ollama](https://ollama.ai)
-2. Pull a model: `ollama pull gemma3:12b` (recommended model)
-3. Ollama runs on port 11434 by default
-
-### Cloud Models
-
-Add API keys to your environment variables (recommended) by creating a `.env` file in your config directory:
-
-```bash
-# Set API keys for cloud providers in .env
-ANTHROPIC_API_KEY=your-api-key-here # For Claude models
-OPENAI_API_KEY=your-openai-key-here # For GPT models
-OPENAI_ENDPOINT_API_KEY=your-key-here # For OpenRouter or similar services
-
-# Set your preferred LLM provider and model (no need to edit llm_config.py)
-LDR_LLM__PROVIDER=ollama # Options: ollama, openai, anthropic, etc.
-LDR_LLM__MODEL=gemma3:12b # Model name to use
-```
-
-> **Important:** In most cases, you don't need to modify the `llm_config.py` file. Simply set the `LDR_LLM__PROVIDER` and `LDR_LLM__MODEL` environment variables to use your preferred model.
-
-### Supported LLM Providers
-
-The system supports multiple LLM providers:
-
-| Provider | Type | API Key | Setup Details | Models |
-|----------|------|---------|---------------|--------|
-| `OLLAMA` | Local | No | Install from [ollama.ai](https://ollama.ai) | Mistral, Llama, Gemma, etc. |
-| `OPENAI` | Cloud | `OPENAI_API_KEY` | Set in environment | GPT-3.5, GPT-4, GPT-4o |
-| `ANTHROPIC` | Cloud | `ANTHROPIC_API_KEY` | Set in environment | Claude 3 Opus, Sonnet, Haiku |
-| `OPENAI_ENDPOINT` | Cloud | `OPENAI_ENDPOINT_API_KEY` | Set in environment | Any OpenAI-compatible model |
-| `VLLM` | Local | No | Requires GPU setup | Any supported by vLLM |
-| `LMSTUDIO` | Local | No | Use LM Studio server | Models from LM Studio |
-| `LLAMACPP` | Local | No | Configure model path | GGUF model formats |
-
-The `OPENAI_ENDPOINT` provider can access any service with an OpenAI-compatible API, including:
-- OpenRouter (access to hundreds of models)
-- Azure OpenAI
-- Together.ai
-- Groq
-- Anyscale
-- Self-hosted LLM servers with OpenAI compatibility
-
-## Setting Up Search Engines
-
-Some search engines require API keys. Add them to your environment variables by creating a `.env` file in your config directory:
-
-```bash
-# Search engine API keys (add to .env file)
-SERP_API_KEY=your-serpapi-key-here # For Google results via SerpAPI
-GOOGLE_PSE_API_KEY=your-google-key-here # For Google Programmable Search
-GOOGLE_PSE_ENGINE_ID=your-pse-id-here # For Google Programmable Search
-BRAVE_API_KEY=your-brave-search-key-here # For Brave Search
-GUARDIAN_API_KEY=your-guardian-key-here # For The Guardian
-
-# Set your preferred search tool
-LDR_SEARCH__TOOL=auto # Default: intelligently selects best engine
-```
-
-> **Tip:** To override other settings via environment variables (e.g., to change the web port), use: **LDR_WEB__PORT=8080**
-
-### Available Search Engines
-
-| Engine | Purpose | API Key Required? | Rate Limit |
-|--------|---------|-------------------|------------|
-| `auto` | Intelligently selects the best engine | No | Based on selected engine |
-| `wikipedia` | General knowledge and facts | No | No strict limit |
-| `arxiv` | Scientific papers and research | No | No strict limit |
-| `pubmed` | Medical and biomedical research | No | No strict limit |
-| `semantic_scholar` | Academic literature across all fields | No | 100/5min |
-| `github` | Code repositories and documentation | No | 60/hour (unauthenticated) |
-| `brave` | Web search (privacy-focused) | Yes | Based on plan |
-| `serpapi` | Google search results | Yes | Based on plan |
-| `google_pse` | Custom Google search | Yes | 100/day free tier |
-| `wayback` | Historical web content | No | No strict limit |
-| `searxng` | Local web search engine | No (requires local server) | No limit |
-| Any collection name | Search your local documents | No | No limit |
-
-> **Note:** For detailed SearXNG setup, see our [SearXNG Setup Guide](https://github.com/LearningCircuit/local-deep-research/blob/main/docs/SearXNG-Setup.md).
-
-## Local Document Search (RAG)
-
-The system can search through your local documents using vector embeddings.
-
-### Setting Up Document Collections
-
-1. Define collections in `local_collections.toml`. Default collections include:
-
-```toml
-[project_docs]
-name = "Project Documents"
-description = "Project documentation and specifications"
-paths = ["@format ${DOCS_DIR}/project_documents"]
-enabled = true
-embedding_model = "all-MiniLM-L6-v2"
-embedding_device = "cpu"
-embedding_model_type = "sentence_transformers"
-max_results = 20
-max_filtered_results = 5
-chunk_size = 1000
-chunk_overlap = 200
-cache_dir = "__CACHE_DIR__/local_search/project_docs"
-```
-
-2. Create your document directories:
- - The `${DOCS_DIR}` variable points to a default location in your Documents folder
- - Documents are automatically indexed when the search is first used
-
-### Using Local Search
-
-You can use local document search in several ways:
-
-1. **Auto-selection**: Set `tool = "auto"` in `settings.toml` [search] section
-2. **Explicit collection**: Set `tool = "project_docs"` to search only that collection
-3. **All collections**: Set `tool = "local_all"` to search across all collections
-4. **Query syntax**: Type `collection:project_docs your query` to target a specific collection
-
-
-## Advanced Configuration
-
-### Research Parameters
-
-Edit `settings.toml` to customize research parameters or use environment variables:
-
-```toml
-[search]
-# Search tool to use (auto, wikipedia, arxiv, etc.)
-tool = "auto"
-
-# Number of research cycles
-iterations = 2
-
-# Questions generated per cycle
-questions_per_iteration = 2
-
-# Results per search query
-max_results = 50
-
-# Results after relevance filtering
-max_filtered_results = 5
-```
-
-Using environment variables:
-```bash
-LDR_SEARCH__TOOL=auto
-LDR_SEARCH__ITERATIONS=3
-LDR_SEARCH__QUESTIONS_PER_ITERATION=2
-```
-
-## Web Interface
-
-The web interface offers several features:
-
-- **Dashboard**: Start and manage research queries
-- **Real-time Updates**: Track research progress
-- **Research History**: Access past queries
-- **PDF Export**: Download reports
-- **Research Management**: Terminate processes or delete records
-
-## Command Line Interface
-
-The CLI version allows you to:
-
-1. Choose between a quick summary or detailed report
-2. Enter your research query
-3. View results directly in the terminal
-4. Save reports automatically to the configured output directory
-
-You can run the application directly using Python module syntax:
-
-```bash
-# Run the web interface
-python -m local_deep_research.web.app
-
-# Run the CLI version
-python -m local_deep_research.main
-```
-
-## Community & Support
-
-Join our [Discord server](https://discord.gg/2E6gYU2Z) to exchange ideas, discuss usage patterns, and share research approaches.
-
-## License
-
-This project is licensed under the MIT License.
-
-## Acknowledgments
-
-- Built with [Ollama](https://ollama.ai) for local AI processing
-- Search powered by multiple sources:
- - [Wikipedia](https://www.wikipedia.org/) for factual knowledge
- - [arXiv](https://arxiv.org/) for scientific papers
- - [PubMed](https://pubmed.ncbi.nlm.nih.gov/) for biomedical literature
- - [Semantic Scholar](https://www.semanticscholar.org/) for academic literature
- - [DuckDuckGo](https://duckduckgo.com) for web search
- - [The Guardian](https://www.theguardian.com/) for journalism
- - [SerpAPI](https://serpapi.com) for Google search results
- - [SearXNG](https://searxng.org/) for local web-search engine
- - [Brave Search](https://search.brave.com/) for privacy-focused web search
-- Built on [LangChain](https://github.com/hwchase17/langchain) framework
-- Uses [justext](https://github.com/miso-belica/justext), [Playwright](https://playwright.dev), [FAISS](https://github.com/facebookresearch/faiss), and more
-
-> **Support Free Knowledge:** If you frequently use the search engines in this tool, please consider making a donation to these organizations:
-> - [Donate to Wikipedia](https://donate.wikimedia.org)
-> - [Support arXiv](https://arxiv.org/about/give)
-> - [Donate to DuckDuckGo](https://duckduckgo.com/donations)
-> - [Support PubMed/NCBI](https://www.nlm.nih.gov/pubs/donations/donations.html)
-
-## Contributing
-
-Contributions are welcome! Please feel free to submit a Pull Request.
-
-See [the docs](docs/developing.md) for how to set up your
-local development environment.
-
-1. Fork the repository
-2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
-3. Make your changes
-4. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
-5. Push to the branch (`git push origin feature/AmazingFeature`)
-6. **Important:** Open a Pull Request against the `dev` branch, not the `main` branch
-
-We prefer all pull requests to be submitted against the `dev` branch for easier testing and integration before releasing to the main branch.
+# Local Deep Research
+
+A powerful AI-powered research assistant that performs deep, iterative analysis using multiple LLMs and web searches. The system can be run locally for privacy or configured to use cloud-based LLMs for enhanced capabilities.
+
+<div align="center">
+ <a href="https://www.youtube.com/watch?v=0ISreg9q0p0">
+ <img src="https://img.youtube.com/vi/0ISreg9q0p0/0.jpg" alt="Local Deep Research">
+ <br>
+ <span>▶️ Watch Video</span>
+ </a>
+</div>
+
+
+**Important for non-academic searches:** For normal web searches you will need SearXGN or an API key to a search provider like brave search or SerpAPI. The free searches are mostly academic search engines and will not help you for most normal searches.
+
+## Windows Installation
+
+ Download the [Windows Installer](https://github.com/LearningCircuit/local-deep-research/releases/download/v0.1.0/LocalDeepResearch_Setup.exe) for easy one-click installation.
+
+ **Requires Ollama (or other model provider configured in .env).**
+ Download from https://ollama.ai and then pull a model
+ ollama pull gemma3:12b
+
+## Quick Start (not required if installed with windows installer)
+
+```bash
+# Install the package
+pip install local-deep-research
+
+# Install required browser automation tools
+playwright install
+
+# For local models, install Ollama
+# Download from https://ollama.ai and then pull a model
+ollama pull gemma3:12b
+```
+
+Then run:
+
+```bash
+# Start the web interface (recommended)
+ldr-web # (OR python -m local_deep_research.web.app)
+
+# OR run the command line version
+ldr # (OR python -m local_deep_research.main)
+```
+
+Access the web interface at `http://127.0.0.1:5000` in your browser.
+
+## Docker Support
+
+Build the image first if you haven't already
+```bash
+docker build -t local-deep-research .
+```
+
+Quick Docker Run
+
+```bash
+# Run with default settings (connects to Ollama running on the host)
+docker run --network=host \
+ -e LDR_LLM__PROVIDER="ollama" \
+ -e LDR_LLM__MODEL="mistral" \
+ local-deep-research
+```
+
+For comprehensive Docker setup information, see:
+- [Docker Usage Guide](https://github.com/LearningCircuit/local-deep-research/blob/main/docs/docker-usage-readme.md)
+- [Docker Compose Guide](https://github.com/LearningCircuit/local-deep-research/blob/main/docs/docker-compose-guide.md)
+
+## Programmatic Access
+
+Local Deep Research now provides a simple API for programmatic access to its research capabilities:
+
+```python
+import os
+# Set environment variables to control the LLM
+os.environ["LDR_LLM__MODEL"] = "mistral" # Specify model name
+
+from local_deep_research import quick_summary, generate_report, analyze_documents
+
+# Generate a quick research summary with custom parameters
+results = quick_summary(
+ query="advances in fusion energy",
+ search_tool="auto", # Auto-select the best search engine
+ iterations=1, # Single research cycle for speed
+ questions_per_iteration=2, # Generate 2 follow-up questions
+ max_results=30, # Consider up to 30 search results
+ temperature=0.7 # Control creativity of generation
+)
+print(results["summary"])
+```
+
+These functions provide flexible options for customizing the search parameters, iterations, and output formats. For more examples, see the [programmatic access tutorial](https://github.com/LearningCircuit/local-deep-research/blob/main/examples/programmatic_access.ipynb).
+
+
+## Features
+
+- 🔍 **Advanced Research Capabilities**
+ - Automated deep research with intelligent follow-up questions
+ - Proper inline citation and source verification
+ - Multi-iteration analysis for comprehensive coverage
+ - Full webpage content analysis (not just snippets)
+
+- 🤖 **Flexible LLM Support**
+ - Local AI processing with Ollama models
+ - Cloud LLM support (Claude, GPT)
+ - Supports all Langchain models
+ - Configurable model selection based on needs
+
+- 📊 **Rich Output Options**
+ - Detailed research findings with proper citations
+ - Well-structured comprehensive research reports
+ - Quick summaries for rapid insights
+ - Source tracking and verification
+
+- 🔒 **Privacy-Focused**
+ - Runs entirely on your machine when using local models
+ - Configurable search settings
+ - Transparent data handling
+
+- 🌐 **Enhanced Search Integration**
+ - **Auto-selection of search sources**: The "auto" search engine intelligently analyzes your query and selects the most appropriate search engine
+ - Multiple search engines including Wikipedia, arXiv, PubMed, Semantic Scholar, and more
+ - **Local RAG search for private documents** - search your own documents with vector embeddings
+ - Full webpage content retrieval and intelligent filtering
+
+- 🎓 **Academic & Scientific Integration**
+ - Direct integration with PubMed, arXiv, Wikipedia, Semantic Scholar
+ - Properly formatted citations from academic sources
+ - Report structure suitable for literature reviews
+ - Cross-disciplinary synthesis of information
+
+## Configuration System
+
+The package automatically creates and manages configuration files in your user directory:
+
+- **Windows**: `Documents\LearningCircuit\local-deep-research\config\`
+- **Linux/Mac**: `~/.config/local_deep_research/config/`
+
+### Default Configuration Files
+
+When you first run the tool, it creates these configuration files:
+
+| File | Purpose |
+|------|---------|
+| `settings.toml` | General settings for research, web interface, and search |
+| `llm_config.py` | Advanced LLM configuration (rarely needs modification) |
+| `search_engines.toml` | Define and configure search engines |
+| `local_collections.toml` | Configure local document collections for RAG |
+| `.env` | Environment variables for configuration (recommended for API keys) |
+
+> **Note:** For comprehensive environment variable configuration, see our [Environment Variables Guide](https://github.com/LearningCircuit/local-deep-research/blob/main/docs/env_configuration.md).
+
+## Setting Up AI Models
+
+The system supports multiple LLM providers:
+
+### Local Models (via Ollama)
+
+1. [Install Ollama](https://ollama.ai)
+2. Pull a model: `ollama pull gemma3:12b` (recommended model)
+3. Ollama runs on port 11434 by default
+
+### Cloud Models
+
+Add API keys to your environment variables (recommended) by creating a `.env` file in your config directory:
+
+```bash
+# Set API keys for cloud providers in .env
+ANTHROPIC_API_KEY=your-api-key-here # For Claude models
+OPENAI_API_KEY=your-openai-key-here # For GPT models
+OPENAI_ENDPOINT_API_KEY=your-key-here # For OpenRouter or similar services
+
+# Set your preferred LLM provider and model (no need to edit llm_config.py)
+LDR_LLM__PROVIDER=ollama # Options: ollama, openai, anthropic, etc.
+LDR_LLM__MODEL=gemma3:12b # Model name to use
+```
+
+> **Important:** In most cases, you don't need to modify the `llm_config.py` file. Simply set the `LDR_LLM__PROVIDER` and `LDR_LLM__MODEL` environment variables to use your preferred model.
+
+### Supported LLM Providers
+
+The system supports multiple LLM providers:
+
+| Provider | Type | API Key | Setup Details | Models |
+|----------|------|---------|---------------|--------|
+| `OLLAMA` | Local | No | Install from [ollama.ai](https://ollama.ai) | Mistral, Llama, Gemma, etc. |
+| `OPENAI` | Cloud | `OPENAI_API_KEY` | Set in environment | GPT-3.5, GPT-4, GPT-4o |
+| `ANTHROPIC` | Cloud | `ANTHROPIC_API_KEY` | Set in environment | Claude 3 Opus, Sonnet, Haiku |
+| `OPENAI_ENDPOINT` | Cloud | `OPENAI_ENDPOINT_API_KEY` | Set in environment | Any OpenAI-compatible model |
+| `VLLM` | Local | No | Requires GPU setup | Any supported by vLLM |
+| `LMSTUDIO` | Local | No | Use LM Studio server | Models from LM Studio |
+| `LLAMACPP` | Local | No | Configure model path | GGUF model formats |
+
+The `OPENAI_ENDPOINT` provider can access any service with an OpenAI-compatible API, including:
+- OpenRouter (access to hundreds of models)
+- Azure OpenAI
+- Together.ai
+- Groq
+- Anyscale
+- Self-hosted LLM servers with OpenAI compatibility
+
+## Setting Up Search Engines
+
+Some search engines require API keys. Add them to your environment variables by creating a `.env` file in your config directory:
+
+```bash
+# Search engine API keys (add to .env file)
+SERP_API_KEY=your-serpapi-key-here # For Google results via SerpAPI
+GOOGLE_PSE_API_KEY=your-google-key-here # For Google Programmable Search
+GOOGLE_PSE_ENGINE_ID=your-pse-id-here # For Google Programmable Search
+BRAVE_API_KEY=your-brave-search-key-here # For Brave Search
+GUARDIAN_API_KEY=your-guardian-key-here # For The Guardian
+
+# Set your preferred search tool
+LDR_SEARCH__TOOL=auto # Default: intelligently selects best engine
+```
+
+> **Tip:** To override other settings via environment variables (e.g., to change the web port), use: **LDR_WEB__PORT=8080**
+
+### Available Search Engines
+
+| Engine | Purpose | API Key Required? | Rate Limit |
+|--------|---------|-------------------|------------|
+| `auto` | Intelligently selects the best engine | No | Based on selected engine |
+| `wikipedia` | General knowledge and facts | No | No strict limit |
+| `arxiv` | Scientific papers and research | No | No strict limit |
+| `pubmed` | Medical and biomedical research | No | No strict limit |
+| `semantic_scholar` | Academic literature across all fields | No | 100/5min |
+| `github` | Code repositories and documentation | No | 60/hour (unauthenticated) |
+| `brave` | Web search (privacy-focused) | Yes | Based on plan |
+| `serpapi` | Google search results | Yes | Based on plan |
+| `google_pse` | Custom Google search | Yes | 100/day free tier |
+| `wayback` | Historical web content | No | No strict limit |
+| `searxng` | Local web search engine | No (requires local server) | No limit |
+| Any collection name | Search your local documents | No | No limit |
+
+> **Note:** For detailed SearXNG setup, see our [SearXNG Setup Guide](https://github.com/LearningCircuit/local-deep-research/blob/main/docs/SearXNG-Setup.md).
+
+## Local Document Search (RAG)
+
+The system can search through your local documents using vector embeddings.
+
+### Setting Up Document Collections
+
+1. Define collections in `local_collections.toml`. Default collections include:
+
+```toml
+[project_docs]
+name = "Project Documents"
+description = "Project documentation and specifications"
+paths = ["@format ${DOCS_DIR}/project_documents"]
+enabled = true
+embedding_model = "all-MiniLM-L6-v2"
+embedding_device = "cpu"
+embedding_model_type = "sentence_transformers"
+max_results = 20
+max_filtered_results = 5
+chunk_size = 1000
+chunk_overlap = 200
+cache_dir = "__CACHE_DIR__/local_search/project_docs"
+```
+
+2. Create your document directories:
+ - The `${DOCS_DIR}` variable points to a default location in your Documents folder
+ - Documents are automatically indexed when the search is first used
+
+### Using Local Search
+
+You can use local document search in several ways:
+
+1. **Auto-selection**: Set `tool = "auto"` in `settings.toml` [search] section
+2. **Explicit collection**: Set `tool = "project_docs"` to search only that collection
+3. **All collections**: Set `tool = "local_all"` to search across all collections
+4. **Query syntax**: Type `collection:project_docs your query` to target a specific collection
+
+
+## Advanced Configuration
+
+### Research Parameters
+
+Edit `settings.toml` to customize research parameters or use environment variables:
+
+```toml
+[search]
+# Search tool to use (auto, wikipedia, arxiv, etc.)
+tool = "auto"
+
+# Number of research cycles
+iterations = 2
+
+# Questions generated per cycle
+questions_per_iteration = 2
+
+# Results per search query
+max_results = 50
+
+# Results after relevance filtering
+max_filtered_results = 5
+```
+
+Using environment variables:
+```bash
+LDR_SEARCH__TOOL=auto
+LDR_SEARCH__ITERATIONS=3
+LDR_SEARCH__QUESTIONS_PER_ITERATION=2
+```
+
+## Web Interface
+
+The web interface offers several features:
+
+- **Dashboard**: Start and manage research queries
+- **Real-time Updates**: Track research progress
+- **Research History**: Access past queries
+- **PDF Export**: Download reports
+- **Research Management**: Terminate processes or delete records
+
+## Command Line Interface
+
+The CLI version allows you to:
+
+1. Choose between a quick summary or detailed report
+2. Enter your research query
+3. View results directly in the terminal
+4. Save reports automatically to the configured output directory
+
+You can run the application directly using Python module syntax:
+
+```bash
+# Run the web interface
+python -m local_deep_research.web.app
+
+# Run the CLI version
+python -m local_deep_research.main
+```
+
+## Community & Support
+
+Join our [Discord server](https://discord.gg/2E6gYU2Z) to exchange ideas, discuss usage patterns, and share research approaches.
+
+## License
+
+This project is licensed under the MIT License.
+
+## Acknowledgments
+
+- Built with [Ollama](https://ollama.ai) for local AI processing
+- Search powered by multiple sources:
+ - [Wikipedia](https://www.wikipedia.org/) for factual knowledge
+ - [arXiv](https://arxiv.org/) for scientific papers
+ - [PubMed](https://pubmed.ncbi.nlm.nih.gov/) for biomedical literature
+ - [Semantic Scholar](https://www.semanticscholar.org/) for academic literature
+ - [DuckDuckGo](https://duckduckgo.com) for web search
+ - [The Guardian](https://www.theguardian.com/) for journalism
+ - [SerpAPI](https://serpapi.com) for Google search results
+ - [SearXNG](https://searxng.org/) for local web-search engine
+ - [Brave Search](https://search.brave.com/) for privacy-focused web search
+- Built on [LangChain](https://github.com/hwchase17/langchain) framework
+- Uses [justext](https://github.com/miso-belica/justext), [Playwright](https://playwright.dev), [FAISS](https://github.com/facebookresearch/faiss), and more
+
+> **Support Free Knowledge:** If you frequently use the search engines in this tool, please consider making a donation to these organizations:
+> - [Donate to Wikipedia](https://donate.wikimedia.org)
+> - [Support arXiv](https://arxiv.org/about/give)
+> - [Donate to DuckDuckGo](https://duckduckgo.com/donations)
+> - [Support PubMed/NCBI](https://www.nlm.nih.gov/pubs/donations/donations.html)
+
+## Contributing
+
+Contributions are welcome! Please feel free to submit a Pull Request.
+
+See [the docs](docs/developing.md) for how to set up your
+local development environment.
+
+1. Fork the repository
+2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
+3. Make your changes
+4. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
+5. Push to the branch (`git push origin feature/AmazingFeature`)
+6. **Important:** Open a Pull Request against the `dev` branch, not the `main` branch
+
+We prefer all pull requests to be submitted against the `dev` branch for easier testing and integration before releasing to the main branch.
+
+## Database Path Update
+
+The application now uses a unified database (`ldr.db`) located at `src/data/ldr.db` within the project directory. This replaces the previous approach of using separate databases (`deep_research.db` in an external location and `research_history.db` in the project root).
+
+### Migration
+
+If you have existing data in the legacy databases, follow these steps to migrate it:
+
+1. Run the setup script to ensure the data directory exists:
+ ```
+ python -m src.local_deep_research.setup_data_dir
+ ```
+
+2. Run the migration script to transfer data:
+ ```
+ python -m src.local_deep_research.migrate_db --backup
+ ```
+
+The `--backup` flag creates backups of your existing databases before migration.
+
+### Starting the Application
+
+To start the application with the new database:
+
+```
+python -m src.local_deep_research.main
+```
+
+If you want to start with automatic migration if needed:
+
+```
+python -m src.local_deep_research.main --auto-migrate
+```
+
+
diff --git a/data/config/llm_config.py b/data/config/llm_config.py
deleted file mode 100644
index 6f984df15c..0000000000
--- a/data/config/llm_config.py
+++ /dev/null
@@ -1,11 +0,0 @@
-"""
-LLM Configuration Module
-
-This module provides configuration and utilities for language model interactions.
-You can customize model selection, parameters, and fallbacks here.
-"""
-
-import logging
-
-# Initialize logger
-logger = logging.getLogger(__name__)
diff --git a/src/local_deep_research/config/config_files.py b/src/local_deep_research/config/config_files.py
index 2f3e7cf5bf..5774647240 100644
--- a/src/local_deep_research/config/config_files.py
+++ b/src/local_deep_research/config/config_files.py
@@ -39,6 +39,11 @@ SEARCH_ENGINES_FILE = CONFIG_DIR / "search_engines.toml"
LOCAL_COLLECTIONS_FILE = CONFIG_DIR / "local_collections.toml"
+# Define data directory for database
+DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "data"))
+os.makedirs(DATA_DIR, exist_ok=True)
+DB_PATH = os.path.join(DATA_DIR, "ldr.db")
+
env_file = CONFIG_DIR / ".env"
if env_file.exists():
@@ -86,6 +91,17 @@ def init_config_files():
if not os.path.exists(settings_file) and os.path.exists(default_settings):
shutil.copyfile(default_settings, settings_file)
logger.info(f"Created settings.toml at {settings_file}")
+ # Add note about database-first settings
+ with open(settings_file, "a") as f:
+ f.write(
+ "\n\n# NOTE: Settings in this file are used as fallback only.\n"
+ )
+ f.write(
+ "# Settings stored in the database (ldr.db) take precedence.\n"
+ )
+ f.write(
+ "# To modify settings permanently, use the web interface settings page.\n"
+ )
# Create local_collections.toml if it doesn't exist
collections_file = os.path.join(CONFIG_DIR, "local_collections.toml")
@@ -104,6 +120,17 @@ def init_config_files():
):
shutil.copyfile(default_engines, search_engines_file)
logger.info(f"Created search_engines.toml at {search_engines_file}")
+ # Add note about database-first settings
+ with open(search_engines_file, "a") as f:
+ f.write(
+ "\n\n# NOTE: Settings in this file are used as fallback only.\n"
+ )
+ f.write(
+ "# Settings stored in the database (ldr.db) take precedence.\n"
+ )
+ f.write(
+ "# To modify search settings permanently, use the web interface settings page.\n"
+ )
# Create .env.template if it doesn't exist
env_template_file = CONFIG_DIR / ".env.template"
@@ -138,6 +165,15 @@ def init_config_files():
if not settings_file.exists():
shutil.copy(defaults_dir / "main.toml", settings_file)
logger.info(f"Created settings.toml at {settings_file}")
+ # Add note about database-first settings
+ with open(settings_file, "a") as f:
+ f.write(
+ "\n\n# NOTE: Settings in this file are used as fallback only.\n"
+ )
+ f.write("# Settings stored in the database (ldr.db) take precedence.\n")
+ f.write(
+ "# To modify settings permanently, use the web interface settings page.\n"
+ )
# Create local_collections.toml if it doesn't exist
collections_file = CONFIG_DIR / "local_collections.toml"
@@ -150,6 +186,16 @@ def init_config_files():
if not search_engines_file.exists():
shutil.copy(defaults_dir / "search_engines.toml", search_engines_file)
logger.info(f"Created search_engines.toml at {search_engines_file}")
+ # Add note about database-first settings
+ with open(search_engines_file, "a") as f:
+ f.write(
+ "\n\n# NOTE: Settings in this file are used as fallback only.\n"
+ )
+ f.write("# Settings stored in the database (ldr.db) take precedence.\n")
+ f.write(
+ "# To modify search settings permanently, use the web interface settings page.\n"
+ )
+
env_template_file = CONFIG_DIR / ".env.template"
if not env_template_file.exists():
shutil.copy(defaults_dir / ".env.template", env_template_file)
@@ -177,6 +223,11 @@ def init_config_files():
)
+# Add a comment to explain the DB-first settings approach
+logger.info(
+ "Using database-first settings approach. TOML files are used as fallback only."
+)
+
settings = Dynaconf(
settings_files=[
str(SETTINGS_FILE),
diff --git a/src/local_deep_research/main.py b/src/local_deep_research/main.py
index 7acc707d26..607da82667 100644
--- a/src/local_deep_research/main.py
+++ b/src/local_deep_research/main.py
@@ -1,3 +1,5 @@
+import logging
+import sys
from typing import Dict
# from .report_generator import IntegratedReportGenerator
@@ -119,5 +121,91 @@ def main():
print("Research failed. Please try again.")
+# Add command for database migration
if __name__ == "__main__":
- main()
+ import argparse
+
+ parser = argparse.ArgumentParser(description="Local Deep Research")
+ parser.add_argument("--web", action="store_true", help="Start the web server")
+ parser.add_argument(
+ "--migrate-db", action="store_true", help="Migrate legacy databases to ldr.db"
+ )
+ parser.add_argument("--debug", action="store_true", help="Enable debug mode")
+ parser.add_argument(
+ "--test-migration",
+ action="store_true",
+ help="Test migration by checking database contents",
+ )
+ parser.add_argument(
+ "--schema-upgrade",
+ action="store_true",
+ help="Run schema upgrades on the database (e.g., remove redundant tables)",
+ )
+
+ args = parser.parse_args()
+
+ if args.debug:
+ logging.basicConfig(level=logging.DEBUG)
+ else:
+ logging.basicConfig(level=logging.INFO)
+
+ if args.migrate_db:
+ try:
+ # First ensure data directory exists
+ from src.local_deep_research.setup_data_dir import setup_data_dir
+
+ setup_data_dir()
+
+ # Then run the migration
+ from src.local_deep_research.web.database.migrate_to_ldr_db import (
+ migrate_to_ldr_db,
+ )
+
+ print("Starting database migration...")
+ success = migrate_to_ldr_db()
+ if success:
+ print("Database migration completed successfully")
+ sys.exit(0)
+ else:
+ print("Database migration failed")
+ sys.exit(1)
+ except Exception as e:
+ print(f"Error running database migration: {e}")
+ sys.exit(1)
+
+ if args.test_migration:
+ try:
+ from src.local_deep_research.test_migration import main as test_main
+
+ sys.exit(test_main())
+ except Exception as e:
+ print(f"Error running migration test: {e}")
+ sys.exit(1)
+
+ if args.schema_upgrade:
+ try:
+ from src.local_deep_research.web.database.schema_upgrade import (
+ run_schema_upgrades,
+ )
+
+ print("Running database schema upgrades...")
+ success = run_schema_upgrades()
+ if success:
+ print("Schema upgrades completed successfully")
+ sys.exit(0)
+ else:
+ print("Schema upgrades failed")
+ sys.exit(1)
+ except Exception as e:
+ print(f"Error running schema upgrades: {e}")
+ sys.exit(1)
+
+ if args.web:
+ from src.local_deep_research.web.app import main as web_main
+
+ web_main()
+ else:
+ # Default to web if no command specified
+ from src.local_deep_research.web.app import main as web_main
+
+ web_main()
diff --git a/src/local_deep_research/migrate_db.py b/src/local_deep_research/migrate_db.py
new file mode 100644
index 0000000000..818740101d
--- /dev/null
+++ b/src/local_deep_research/migrate_db.py
@@ -0,0 +1,149 @@
+#!/usr/bin/env python
+"""
+Database migration script for Local Deep Research.
+Migrates data from legacy databases (deep_research.db and research_history.db) to the new unified database (ldr.db).
+"""
+
+import argparse
+import logging
+import os
+import sys
+
+# Configure logging
+logging.basicConfig(
+ level=logging.INFO,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
+ handlers=[logging.StreamHandler()],
+)
+logger = logging.getLogger("migrate_db")
+
+# Add proper paths for import
+current_dir = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.dirname(os.path.dirname(current_dir)))
+
+
+def main():
+ """Main migration function that parses arguments and runs the migration"""
+ parser = argparse.ArgumentParser(
+ description="Local Deep Research Database Migration"
+ )
+ parser.add_argument(
+ "--backup",
+ action="store_true",
+ help="Create backup of existing databases before migration",
+ )
+ parser.add_argument(
+ "--force",
+ action="store_true",
+ help="Force migration even if target database exists",
+ )
+ parser.add_argument(
+ "--dry-run",
+ action="store_true",
+ help="Only check what would be migrated, don't perform actual migration",
+ )
+ parser.add_argument("--verbose", action="store_true", help="Enable verbose logging")
+
+ args = parser.parse_args()
+
+ if args.verbose:
+ logging.getLogger().setLevel(logging.DEBUG)
+
+ print("=" * 80)
+ print("LOCAL DEEP RESEARCH DATABASE MIGRATION")
+ print("=" * 80)
+
+ try:
+ # First try the normal import
+ try:
+ from web.models.database import (
+ DB_PATH,
+ LEGACY_DEEP_RESEARCH_DB,
+ LEGACY_RESEARCH_HISTORY_DB,
+ )
+ except ImportError:
+ # If that fails, try with the full module path
+ from src.local_deep_research.web.models.database import (
+ DB_PATH,
+ LEGACY_DEEP_RESEARCH_DB,
+ LEGACY_RESEARCH_HISTORY_DB,
+ )
+
+ print(f"Target database will be created at: {DB_PATH}")
+
+ # Check if migration is needed
+ if os.path.exists(DB_PATH) and not args.force:
+ print(f"Target database already exists at: {DB_PATH}")
+ if (
+ input(
+ "Do you want to continue anyway? This may overwrite data. (y/n): "
+ ).lower()
+ != "y"
+ ):
+ print("Migration aborted.")
+ return 1
+
+ # Check if source databases exist
+ deep_research_exists = os.path.exists(LEGACY_DEEP_RESEARCH_DB)
+ research_history_exists = os.path.exists(LEGACY_RESEARCH_HISTORY_DB)
+
+ if not deep_research_exists and not research_history_exists:
+ print("No legacy databases found. Nothing to migrate.")
+ return 0
+
+ print("Found legacy databases:")
+ if deep_research_exists:
+ print(f" - {LEGACY_DEEP_RESEARCH_DB}")
+ if research_history_exists:
+ print(f" - {LEGACY_RESEARCH_HISTORY_DB}")
+
+ # Create backups if requested
+ if args.backup:
+ if deep_research_exists:
+ backup_path = f"{LEGACY_DEEP_RESEARCH_DB}.bak"
+ import shutil
+
+ shutil.copy2(LEGACY_DEEP_RESEARCH_DB, backup_path)
+ print(f"Created backup: {backup_path}")
+
+ if research_history_exists:
+ backup_path = f"{LEGACY_RESEARCH_HISTORY_DB}.bak"
+ import shutil
+
+ shutil.copy2(LEGACY_RESEARCH_HISTORY_DB, backup_path)
+ print(f"Created backup: {backup_path}")
+
+ # Run migration or dry run
+ if args.dry_run:
+ print("\nDRY RUN - No changes will be made.")
+ print(f"Would migrate data to: {DB_PATH}")
+ return 0
+ else:
+ print(f"\nStarting migration to: {DB_PATH}")
+ from web.database.migrate_to_ldr_db import migrate_to_ldr_db
+
+ success = migrate_to_ldr_db()
+
+ if success:
+ print("\nMigration completed successfully.")
+ print(
+ "You can now start the application with the new unified database."
+ )
+ return 0
+ else:
+ print("\nMigration failed. Check the logs for details.")
+ return 1
+
+ except ImportError as e:
+ logger.error(f"Import error: {e}")
+ print("Error: Could not import required modules.")
+ print("Make sure you're running this script from the correct directory.")
+ return 1
+ except Exception as e:
+ logger.error(f"Migration error: {e}", exc_info=True)
+ print(f"Error during migration: {e}")
+ return 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/src/local_deep_research/setup_data_dir.py b/src/local_deep_research/setup_data_dir.py
new file mode 100644
index 0000000000..3b5a470148
--- /dev/null
+++ b/src/local_deep_research/setup_data_dir.py
@@ -0,0 +1,35 @@
+#!/usr/bin/env python
+"""
+Data directory setup script for Local Deep Research.
+Creates the data directory for the application database if it doesn't exist.
+"""
+
+import os
+
+
+def setup_data_dir():
+ """Set up the data directory for the application."""
+ # Get the project root directory (3 levels up from this file)
+ current_dir = os.path.dirname(os.path.abspath(__file__))
+ project_root = os.path.abspath(os.path.join(current_dir, "..", ".."))
+
+ # Define the data directory path
+ data_dir = os.path.join(project_root, "data")
+
+ # Create the data directory if it doesn't exist
+ if not os.path.exists(data_dir):
+ os.makedirs(data_dir)
+ print(f"Created data directory at: {data_dir}")
+ else:
+ print(f"Data directory already exists at: {data_dir}")
+
+ # Return the path to the data directory
+ return data_dir
+
+
+if __name__ == "__main__":
+ data_dir = setup_data_dir()
+ db_path = os.path.join(data_dir, "ldr.db")
+ print(f"Database path: {db_path}")
+ print("Run the following command to migrate your database:")
+ print("python -m src.local_deep_research.migrate_db --backup")
diff --git a/src/local_deep_research/test_migration.py b/src/local_deep_research/test_migration.py
new file mode 100644
index 0000000000..549786886e
--- /dev/null
+++ b/src/local_deep_research/test_migration.py
@@ -0,0 +1,178 @@
+#!/usr/bin/env python
+"""
+Migration test script for Local Deep Research.
+This script checks the contents of both the legacy and new databases to diagnose migration issues.
+"""
+
+import os
+import sqlite3
+import sys
+import time
+
+
+def check_db_content(db_path, description):
+ """Check what tables and how many rows are in a database."""
+ if not os.path.exists(db_path):
+ print(f"❌ {description} database not found at: {db_path}")
+ return False
+
+ print(f"📊 Examining {description} database at: {db_path}")
+ try:
+ conn = sqlite3.connect(db_path)
+ cursor = conn.cursor()
+
+ # Get list of tables
+ cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
+ tables = [
+ row[0] for row in cursor.fetchall() if not row[0].startswith("sqlite_")
+ ]
+
+ if not tables:
+ print(" ℹ️ No user tables found in database")
+ conn.close()
+ return False
+
+ print(f" 📋 Tables found: {', '.join(tables)}")
+
+ # For each table, count rows
+ for table in tables:
+ cursor.execute(f"SELECT COUNT(*) FROM {table}")
+ count = cursor.fetchone()[0]
+ print(f" 📝 Table '{table}' has {count} rows")
+
+ # If table has rows, show sample
+ if count > 0:
+ cursor.execute(f"SELECT * FROM {table} LIMIT 1")
+ columns = [description[0] for description in cursor.description]
+ print(f" Columns: {', '.join(columns)}")
+
+ # For specific tables, get key columns
+ if table in [
+ "research_history",
+ "research_logs",
+ "research",
+ "settings",
+ ]:
+ key_cols = (
+ "id, query, status"
+ if table == "research_history"
+ else "id, key, value" if table == "settings" else "id, message"
+ )
+ cursor.execute(f"SELECT {key_cols} FROM {table} LIMIT 3")
+ sample = cursor.fetchall()
+ for row in sample:
+ print(f" Sample data: {row}")
+
+ conn.close()
+ return True
+ except Exception as e:
+ print(f"❌ Error examining database: {e}")
+ return False
+
+
+def main():
+ """Main function to test the migration."""
+ # Import necessary constants
+ try:
+ # Set up paths
+ current_dir = os.path.dirname(os.path.abspath(__file__))
+ project_root = os.path.abspath(os.path.join(current_dir, "..", ".."))
+
+ # Determine paths
+ data_dir = os.path.join(project_root, "data")
+ new_db_path = os.path.join(data_dir, "ldr.db")
+
+ legacy_research_history_db = os.path.join(
+ project_root, "src", "local_deep_research", "research_history.db"
+ )
+ legacy_deep_research_db = os.path.join(data_dir, "deep_research.db")
+
+ # Print paths for verification
+ print("=" * 60)
+ print("DATABASE PATHS")
+ print("=" * 60)
+ print(f"New database path: {new_db_path}")
+ print(f"Legacy research history DB: {legacy_research_history_db}")
+ print(f"Legacy deep research DB: {legacy_deep_research_db}")
+ print("=" * 60)
+
+ # Check all databases
+ check_db_content(legacy_research_history_db, "Legacy research_history")
+ check_db_content(legacy_deep_research_db, "Legacy deep_research")
+
+ # Now check for the new database or create it if needed
+ if os.path.exists(new_db_path):
+ check_db_content(new_db_path, "New ldr")
+ else:
+ print(f"ℹ️ New database doesn't exist yet at: {new_db_path}")
+ print("Would you like to run a test migration? (y/n)")
+ choice = input("> ").lower()
+ if choice == "y":
+ # Run the migration script directly
+ try:
+ from src.local_deep_research.setup_data_dir import setup_data_dir
+ except ImportError:
+ # If that fails, try with the direct import
+ sys.path.append(
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ )
+ from local_deep_research.setup_data_dir import setup_data_dir
+
+ setup_data_dir()
+
+ # Import migration function
+ try:
+ from src.local_deep_research.web.database.migrate_to_ldr_db import (
+ migrate_to_ldr_db,
+ )
+ except ImportError:
+ # If that fails, try with the direct import
+ from local_deep_research.web.database.migrate_to_ldr_db import (
+ migrate_to_ldr_db,
+ )
+
+ print("Running migration...")
+ success = migrate_to_ldr_db()
+
+ # Wait briefly to ensure file system has time to update
+ time.sleep(1)
+
+ if success:
+ print("\n✅ Migration completed. Checking new database:")
+ check_db_content(new_db_path, "New ldr")
+ else:
+ print("❌ Migration failed")
+
+ # Get the paths from the migration script to verify
+ try:
+ try:
+ from src.local_deep_research.web.models.database import (
+ DB_PATH,
+ LEGACY_DEEP_RESEARCH_DB,
+ LEGACY_RESEARCH_HISTORY_DB,
+ )
+ except ImportError:
+ from local_deep_research.web.models.database import (
+ DB_PATH,
+ LEGACY_DEEP_RESEARCH_DB,
+ LEGACY_RESEARCH_HISTORY_DB,
+ )
+
+ print("\n" + "=" * 60)
+ print("PATHS FROM DATABASE MODULE")
+ print("=" * 60)
+ print(f"DB_PATH: {DB_PATH}")
+ print(f"LEGACY_RESEARCH_HISTORY_DB: {LEGACY_RESEARCH_HISTORY_DB}")
+ print(f"LEGACY_DEEP_RESEARCH_DB: {LEGACY_DEEP_RESEARCH_DB}")
+ except ImportError as e:
+ print(f"Could not import paths from database module: {e}")
+
+ except Exception as e:
+ print(f"Error in test script: {e}")
+ return 1
+
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.py
index 5007f2657c..2e243cf0fb 100644
--- a/src/local_deep_research/web/app.py
+++ b/src/local_deep_research/web/app.py
@@ -1,12 +1,52 @@
import logging
import os
+import sys
from ..config.config_files import settings
+from ..setup_data_dir import setup_data_dir
from .app_factory import create_app
+from .models.database import (
+ DB_PATH,
+ LEGACY_DEEP_RESEARCH_DB,
+ LEGACY_RESEARCH_HISTORY_DB,
+)
# Initialize logger
logger = logging.getLogger(__name__)
+# Ensure data directory exists
+setup_data_dir()
+
+# Run schema upgrades if database exists
+if os.path.exists(DB_PATH):
+ try:
+ logger.info("Running schema upgrades on existing database")
+ from .database.schema_upgrade import run_schema_upgrades
+
+ run_schema_upgrades()
+ except Exception as e:
+ logger.error(f"Error running schema upgrades: {e}")
+ logger.warning("Continuing without schema upgrades")
+
+
+# Check if we need to run database migration
+def check_migration_needed():
+ """Check if database migration is needed, based on presence of legacy files and absence of new DB"""
+ if not os.path.exists(DB_PATH):
+ # The new database doesn't exist, check if legacy databases exist
+ legacy_files_exist = os.path.exists(LEGACY_DEEP_RESEARCH_DB) or os.path.exists(
+ LEGACY_RESEARCH_HISTORY_DB
+ )
+
+ if legacy_files_exist:
+ logger.info(
+ "Legacy database files found, but ldr.db doesn't exist. Migration needed."
+ )
+ return True
+
+ return False
+
+
# Create the Flask app and SocketIO instance
app, socketio = create_app()
@@ -16,6 +56,40 @@ def main():
Entry point for the web application when run as a command.
This function is needed for the package's entry point to work properly.
"""
+ # Check if migration is needed
+ if check_migration_needed():
+ logger.info(
+ "Database migration required. Run migrate_db.py before starting the application."
+ )
+ print("=" * 80)
+ print("DATABASE MIGRATION REQUIRED")
+ print(
+ "Legacy database files were found, but the new unified database doesn't exist."
+ )
+ print(
+ "Please run 'python -m src.local_deep_research.web.database.migrate_to_ldr_db' to migrate your data."
+ )
+ print(
+ "You can continue without migration, but your previous data won't be available."
+ )
+ print("=" * 80)
+
+ # If --auto-migrate flag is passed, run migration automatically
+ if "--auto-migrate" in sys.argv:
+ logger.info("Auto-migration flag detected, running migration...")
+ try:
+ from .database.migrate_to_ldr_db import migrate_to_ldr_db
+
+ success = migrate_to_ldr_db()
+ if success:
+ logger.info("Database migration completed successfully.")
+ else:
+ logger.warning("Database migration failed.")
+ except Exception as e:
+ logger.error(f"Error running database migration: {e}")
+ print(f"Error: {e}")
+ print("Please run migration manually.")
+
# Get web server settings with defaults
port = settings.web.port
host = settings.web.host
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index 7f71e471c2..28c6c9f1d2 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -14,7 +14,7 @@ from flask import (
from flask_socketio import SocketIO
from flask_wtf.csrf import CSRFProtect
-from .models.database import init_db
+from .models.database import DB_PATH, init_db
# Initialize logger
logger = logging.getLogger(__name__)
@@ -30,6 +30,9 @@ def create_app():
# Configure logging
logging.basicConfig(level=logging.INFO)
+ # Set Werkzeug logger to WARNING level to suppress Socket.IO polling logs
+ logging.getLogger("werkzeug").setLevel(logging.WARNING)
+
try:
# Get directories based on package installation
PACKAGE_DIR = importlib_resources.files("local_deep_research") / "web"
@@ -58,14 +61,10 @@ def create_app():
# Exempt Socket.IO from CSRF protection
csrf.exempt("research.socket_io")
- # Database configuration
- db_path = os.path.abspath(
- os.path.join(
- os.path.dirname(__file__), "..", "..", "..", "data", "deep_research.db"
- )
- )
- os.makedirs(os.path.dirname(db_path), exist_ok=True)
+ # Database configuration - Use unified ldr.db from the database module
+ db_path = DB_PATH
app.config["SQLALCHEMY_DATABASE_URI"] = f"sqlite:///{db_path}"
+ logger.info(f"Using database at {db_path}")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["SQLALCHEMY_ECHO"] = False
@@ -75,8 +74,8 @@ def create_app():
cors_allowed_origins="*",
async_mode="threading",
path="/research/socket.io",
- logger=True,
- engineio_logger=True,
+ logger=False,
+ engineio_logger=False,
ping_timeout=20,
ping_interval=5,
)
diff --git a/src/local_deep_research/web/database/README.md b/src/local_deep_research/web/database/README.md
new file mode 100644
index 0000000000..7fe9a97504
Binary files /dev/null and b/src/local_deep_research/web/database/README.md differ
diff --git a/src/local_deep_research/web/database/migrate_to_ldr_db.py b/src/local_deep_research/web/database/migrate_to_ldr_db.py
new file mode 100644
index 0000000000..3f3850930b
--- /dev/null
+++ b/src/local_deep_research/web/database/migrate_to_ldr_db.py
@@ -0,0 +1,289 @@
+"""
+Migration script to merge deep_research.db and research_history.db into ldr.db
+"""
+
+# Standard library imports
+# import json # Remove unused imports
+import logging
+import os
+import sqlite3
+import sys
+import traceback
+
+# from pathlib import Path # Remove unused imports
+
+# Set up logging
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)
+
+# Add the parent directory to sys.path to allow relative imports
+sys.path.append(
+ os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
+)
+
+# Import the database module after adding to sys path
+# pylint: disable=wrong-import-position
+from src.local_deep_research.web.models.database import ( # noqa: E402
+ DB_PATH,
+ LEGACY_DEEP_RESEARCH_DB,
+ LEGACY_RESEARCH_HISTORY_DB,
+)
+
+
+def migrate_to_ldr_db():
+ """
+ Migrates data from deep_research.db and research_history.db to ldr.db
+ """
+ # Ensure data directory exists
+ try:
+ from src.local_deep_research.setup_data_dir import setup_data_dir
+
+ setup_data_dir()
+ except ImportError:
+ # If we can't import directly, check the path manually
+ logger.info("Creating data directory manually")
+ data_dir = os.path.dirname(DB_PATH)
+ os.makedirs(data_dir, exist_ok=True)
+
+ logger.info(f"Using database path: {DB_PATH}")
+
+ # Check if ldr.db already exists
+ if os.path.exists(DB_PATH):
+ logger.info(f"Target database {DB_PATH} already exists")
+
+ # Ask for confirmation
+ if (
+ input(
+ f"Target database {DB_PATH} already exists. Do you want to continue migration? (y/n): "
+ ).lower()
+ != "y"
+ ):
+ logger.info("Migration aborted by user")
+ return False
+
+ # Connect to the target database
+ try:
+ ldr_conn = sqlite3.connect(DB_PATH)
+ ldr_cursor = ldr_conn.cursor()
+ logger.info(f"Connected to target database: {DB_PATH}")
+ except Exception as e:
+ logger.error(f"Failed to connect to target database: {e}")
+ return False
+
+ # Enable foreign keys
+ ldr_cursor.execute("PRAGMA foreign_keys = OFF")
+
+ # Initialize the database schema
+ try:
+ from src.local_deep_research.web.models.database import init_db
+
+ init_db()
+ logger.info("Initialized database schema")
+ except Exception as e:
+ logger.error(f"Failed to initialize database schema: {e}")
+ ldr_conn.close()
+ return False
+
+ # Migrate from research_history.db
+ migrated_research = migrate_research_history_db(
+ ldr_conn, LEGACY_RESEARCH_HISTORY_DB
+ )
+
+ # Migrate from deep_research.db
+ migrated_deep_research = migrate_deep_research_db(ldr_conn, LEGACY_DEEP_RESEARCH_DB)
+
+ # Re-enable foreign keys and commit
+ ldr_cursor.execute("PRAGMA foreign_keys = ON")
+ ldr_conn.commit()
+ ldr_conn.close()
+
+ logger.info(
+ f"Migration completed - Research History: {migrated_research}, Deep Research: {migrated_deep_research}"
+ )
+ return True
+
+
+def migrate_research_history_db(ldr_conn, legacy_path):
+ """
+ Migrates data from research_history.db to ldr.db
+
+ Args:
+ ldr_conn: Connection to the target ldr.db
+ legacy_path: Path to legacy research_history.db
+
+ Returns:
+ bool: True if migration was successful, False otherwise
+ """
+ if not os.path.exists(legacy_path):
+ logger.warning(f"Legacy database not found: {legacy_path}")
+ return False
+
+ try:
+ # Connect to legacy database
+ legacy_conn = sqlite3.connect(legacy_path)
+ legacy_cursor = legacy_conn.cursor()
+ ldr_cursor = ldr_conn.cursor()
+
+ logger.info(f"Connected to legacy database: {legacy_path}")
+
+ # Get tables from legacy database
+ legacy_cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
+ tables = [row[0] for row in legacy_cursor.fetchall()]
+
+ for table in tables:
+ # Skip sqlite internal tables
+ if table.startswith("sqlite_"):
+ continue
+
+ logger.info(f"Migrating table: {table}")
+
+ # Check if table exists in target database
+ ldr_cursor.execute(
+ f"SELECT name FROM sqlite_master WHERE type='table' AND name='{table}'"
+ )
+ if not ldr_cursor.fetchone():
+ # Create the table in the target database
+ legacy_cursor.execute(
+ f"SELECT sql FROM sqlite_master WHERE type='table' AND name='{table}'"
+ )
+ create_sql = legacy_cursor.fetchone()[0]
+ logger.info(f"Creating table {table} with SQL: {create_sql}")
+ ldr_cursor.execute(create_sql)
+ logger.info(f"Created table {table} in target database")
+
+ # Get column names
+ legacy_cursor.execute(f"PRAGMA table_info({table})")
+ columns = [row[1] for row in legacy_cursor.fetchall()]
+
+ # Get all data from legacy table
+ legacy_cursor.execute(f"SELECT * FROM {table}")
+ rows = legacy_cursor.fetchall()
+
+ logger.info(f"Found {len(rows)} rows in {table}")
+
+ if rows:
+ # Create placeholders for the SQL query
+ placeholders = ", ".join(["?" for _ in columns])
+ columns_str = ", ".join(columns)
+
+ # Insert data into target database
+ for row in rows:
+ try:
+ ldr_cursor.execute(
+ f"INSERT OR IGNORE INTO {table} ({columns_str}) VALUES ({placeholders})",
+ row,
+ )
+ except sqlite3.Error as e:
+ logger.error(f"Error inserting into {table}: {e}")
+ logger.error(f"Row data: {row}")
+ continue
+
+ # Verify data was inserted
+ ldr_cursor.execute(f"SELECT COUNT(*) FROM {table}")
+ count = ldr_cursor.fetchone()[0]
+ logger.info(f"Migrated {count} rows to {table} (expected {len(rows)})")
+ else:
+ logger.info(f"No data to migrate from {table}")
+
+ legacy_conn.close()
+ return True
+
+ except Exception as e:
+ logger.error(f"Failed to migrate from {legacy_path}: {e}")
+ logger.error(f"Exception details: {traceback.format_exc()}")
+ return False
+
+
+def migrate_deep_research_db(ldr_conn, legacy_path):
+ """
+ Migrates data from deep_research.db to ldr.db
+
+ Args:
+ ldr_conn: Connection to the target ldr.db
+ legacy_path: Path to legacy deep_research.db
+
+ Returns:
+ bool: True if migration was successful, False otherwise
+ """
+ if not os.path.exists(legacy_path):
+ logger.warning(f"Legacy database not found: {legacy_path}")
+ return False
+
+ try:
+ # Connect to legacy database
+ legacy_conn = sqlite3.connect(legacy_path)
+ legacy_cursor = legacy_conn.cursor()
+ ldr_cursor = ldr_conn.cursor()
+
+ logger.info(f"Connected to legacy database: {legacy_path}")
+
+ # Get tables from legacy database
+ legacy_cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
+ tables = [row[0] for row in legacy_cursor.fetchall()]
+
+ # Migrate each table
+ for table in tables:
+ # Skip sqlite internal tables
+ if table.startswith("sqlite_"):
+ continue
+
+ # Skip the research_log table as it's redundant with research_logs
+ if table == "research_log":
+ logger.info(
+ "Skipping redundant table 'research_log', using 'research_logs' instead"
+ )
+ continue
+
+ logger.info(f"Migrating table: {table}")
+
+ # Check if table exists in target database
+ ldr_cursor.execute(
+ f"SELECT name FROM sqlite_master WHERE type='table' AND name='{table}'"
+ )
+ if not ldr_cursor.fetchone():
+ # Create the table in the target database
+ legacy_cursor.execute(
+ f"SELECT sql FROM sqlite_master WHERE type='table' AND name='{table}'"
+ )
+ create_sql = legacy_cursor.fetchone()[0]
+ ldr_cursor.execute(create_sql)
+ logger.info(f"Created table {table} in target database")
+
+ # Get column names
+ legacy_cursor.execute(f"PRAGMA table_info({table})")
+ columns = [row[1] for row in legacy_cursor.fetchall()]
+
+ # Get all data from legacy table
+ legacy_cursor.execute(f"SELECT * FROM {table}")
+ rows = legacy_cursor.fetchall()
+
+ if rows:
+ # Create placeholders for the SQL query
+ placeholders = ", ".join(["?" for _ in columns])
+ columns_str = ", ".join(columns)
+
+ # Insert data into target database
+ for row in rows:
+ try:
+ ldr_cursor.execute(
+ f"INSERT OR IGNORE INTO {table} ({columns_str}) VALUES ({placeholders})",
+ row,
+ )
+ except sqlite3.Error as e:
+ logger.error(f"Error inserting into {table}: {e}")
+ continue
+
+ logger.info(f"Migrated {len(rows)} rows from {table}")
+ else:
+ logger.info(f"No data to migrate from {table}")
+
+ legacy_conn.close()
+ return True
+
+ except Exception as e:
+ logger.error(f"Failed to migrate from {legacy_path}: {e}")
+ return False
+
+
+if __name__ == "__main__":
+ migrate_to_ldr_db()
diff --git a/src/local_deep_research/web/database/models.py b/src/local_deep_research/web/database/models.py
index 2eb7aaf2f0..7edffbaaff 100644
--- a/src/local_deep_research/web/database/models.py
+++ b/src/local_deep_research/web/database/models.py
@@ -52,9 +52,6 @@ class Research(Base):
error_message = Column(Text, nullable=True)
# Relationships
- logs = relationship(
- "ResearchLog", back_populates="research", cascade="all, delete-orphan"
- )
report = relationship(
"ResearchReport",
back_populates="research",
@@ -63,22 +60,6 @@ class Research(Base):
)
-class ResearchLog(Base):
- __tablename__ = "research_log"
-
- id = Column(Integer, primary_key=True, index=True)
- research_id = Column(
- Integer, ForeignKey("research.id", ondelete="CASCADE"), nullable=False
- )
- message = Column(Text, nullable=False)
- timestamp = Column(DateTime, server_default=func.now(), nullable=False)
- level = Column(String, default="info", nullable=False) # info, warning, error
- details = Column(JSON, nullable=True)
-
- # Relationships
- research = relationship("Research", back_populates="logs")
-
-
class ResearchReport(Base):
__tablename__ = "research_report"
diff --git a/src/local_deep_research/web/database/schema_upgrade.py b/src/local_deep_research/web/database/schema_upgrade.py
new file mode 100644
index 0000000000..c5268be7fb
--- /dev/null
+++ b/src/local_deep_research/web/database/schema_upgrade.py
@@ -0,0 +1,107 @@
+"""
+Schema upgrade script for Local Deep Research database.
+Handles schema upgrades for existing ldr.db databases.
+"""
+
+import logging
+import os
+import sqlite3
+import sys
+
+# Set up logging
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)
+
+# Add the parent directory to sys.path to allow relative imports
+sys.path.append(
+ os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
+)
+
+try:
+ from src.local_deep_research.web.models.database import DB_PATH
+except ImportError:
+ # Fallback path if import fails
+ current_dir = os.path.dirname(os.path.abspath(__file__))
+ project_root = os.path.abspath(os.path.join(current_dir, "..", "..", "..", ".."))
+ DB_PATH = os.path.join(project_root, "src", "data", "ldr.db")
+
+
+def check_table_exists(conn, table_name):
+ """
+ Check if a table exists in the database
+
+ Args:
+ conn: SQLite connection
+ table_name: Name of the table
+
+ Returns:
+ bool: True if table exists, False otherwise
+ """
+ cursor = conn.cursor()
+ cursor.execute(
+ "SELECT name FROM sqlite_master WHERE type='table' AND name=?", (table_name,)
+ )
+ return cursor.fetchone() is not None
+
+
+def remove_research_log_table(conn):
+ """
+ Remove the redundant research_log table if it exists
+
+ Args:
+ conn: SQLite connection
+
+ Returns:
+ bool: True if operation was successful, False otherwise
+ """
+ try:
+ cursor = conn.cursor()
+
+ # Check if table exists
+ if check_table_exists(conn, "research_log"):
+ # For SQLite, DROP TABLE is the way to remove a table
+ cursor.execute("DROP TABLE research_log")
+ conn.commit()
+ logger.info("Successfully removed redundant 'research_log' table")
+ return True
+ else:
+ logger.info("Table 'research_log' does not exist, no action needed")
+ return True
+ except Exception as e:
+ logger.error(f"Error removing research_log table: {e}")
+ return False
+
+
+def run_schema_upgrades():
+ """
+ Run all schema upgrade operations on the database
+
+ Returns:
+ bool: True if all upgrades successful, False otherwise
+ """
+ # Check if database exists
+ if not os.path.exists(DB_PATH):
+ logger.warning(f"Database not found at {DB_PATH}, skipping schema upgrades")
+ return False
+
+ logger.info(f"Running schema upgrades on {DB_PATH}")
+
+ try:
+ # Connect to the database
+ conn = sqlite3.connect(DB_PATH)
+
+ # 1. Remove the redundant research_log table
+ remove_research_log_table(conn)
+
+ # Close connection
+ conn.close()
+
+ logger.info("Schema upgrades completed successfully")
+ return True
+ except Exception as e:
+ logger.error(f"Error during schema upgrades: {e}")
+ return False
+
+
+if __name__ == "__main__":
+ run_schema_upgrades()
diff --git a/src/local_deep_research/web/models/database.py b/src/local_deep_research/web/models/database.py
index 03aee45d98..dcf832190e 100644
--- a/src/local_deep_research/web/models/database.py
+++ b/src/local_deep_research/web/models/database.py
@@ -1,5 +1,6 @@
import json
import logging
+import os
import sqlite3
import traceback
from datetime import datetime
@@ -8,7 +9,23 @@ from datetime import datetime
logger = logging.getLogger(__name__)
# Database path
-DB_PATH = "research_history.db"
+# Use unified database in data directory
+DATA_DIR = os.path.abspath(
+ os.path.join(os.path.dirname(__file__), "..", "..", "..", "data")
+)
+os.makedirs(DATA_DIR, exist_ok=True)
+DB_PATH = os.path.join(DATA_DIR, "ldr.db")
+
+# Legacy database paths (for migration)
+LEGACY_RESEARCH_HISTORY_DB = os.path.abspath(
+ os.path.join(os.path.dirname(__file__), "..", "..", "..", "research_history.db")
+)
+LEGACY_DEEP_RESEARCH_DB = os.path.join(
+ os.path.abspath(
+ os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "data")
+ ),
+ "deep_research.db",
+)
def get_db_connection():
diff --git a/src/local_deep_research/web/services/settings_manager.py b/src/local_deep_research/web/services/settings_manager.py
index 6c767c862a..cc9d3b0d7a 100644
--- a/src/local_deep_research/web/services/settings_manager.py
+++ b/src/local_deep_research/web/services/settings_manager.py
@@ -42,43 +42,64 @@ class SettingsManager:
self.search_engines_file = self.config_dir / "search_engines.toml"
self.collections_file = self.config_dir / "local_collections.toml"
self.secrets_file = self.config_dir / ".secrets.toml"
+ self.db_first = True # Always prioritize DB settings
# In-memory cache for settings
self._settings_cache: Dict[str, Any] = {}
- # Load settings if session is provided
+ # Load settings from database first
if db_session:
self._load_settings_from_db()
- # If cache is empty, fall back to file-based settings
- if not self._settings_cache:
- self._load_settings_from_files()
+ # Always load from files as fallback
+ self._load_settings_from_files_as_fallback()
def get_setting(self, key: str, default: Any = None) -> Any:
"""
- Get the value of a setting by key
+ Get a setting value
Args:
key: Setting key
default: Default value if setting is not found
Returns:
- Setting value or default
+ Setting value or default if not found
"""
- # Check in-memory cache first
+ # Check in-memory cache first (highest priority)
if key in self._settings_cache:
return self._settings_cache[key]
- # Try to get from database
- if self.db_session:
- setting = self.db_session.query(Setting).filter(Setting.key == key).first()
- if setting:
- # Cache the setting
- self._settings_cache[key] = setting.value
- return setting.value
+ # If using database first approach and session available, check database
+ if self.db_first and self.db_session:
+ try:
+ setting = (
+ self.db_session.query(Setting).filter(Setting.key == key).first()
+ )
+ if setting:
+ # Update cache and return
+ self._settings_cache[key] = setting.value
+ return setting.value
+ except SQLAlchemyError as e:
+ logger.error(f"Error retrieving setting {key} from database: {e}")
- # Fall back to dynaconf
- return dynaconf_settings.get(key, default)
+ # Fall back to Dynaconf settings
+ try:
+ # Split the key into sections
+ parts = key.split(".")
+ if len(parts) == 2:
+ section, setting = parts
+ if hasattr(dynaconf_settings, section) and hasattr(
+ getattr(dynaconf_settings, section), setting
+ ):
+ value = getattr(getattr(dynaconf_settings, section), setting)
+ # Update cache and return
+ self._settings_cache[key] = value
+ return value
+ except Exception as e:
+ logger.debug(f"Error retrieving setting {key} from Dynaconf: {e}")
+
+ # Return default if not found
+ return default
def set_setting(self, key: str, value: Any, commit: bool = True) -> bool:
"""
@@ -92,10 +113,10 @@ class SettingsManager:
Returns:
True if successful, False otherwise
"""
- # Update cache
+ # Always update cache
self._settings_cache[key] = value
- # Update database if available
+ # Always update database if available
if self.db_session:
try:
setting = (
@@ -138,49 +159,37 @@ class SettingsManager:
# No database session, only update cache
return True
- def get_all_settings(
- self, setting_type: Optional[SettingType] = None
- ) -> Dict[str, Any]:
+ def get_all_settings(self) -> Dict[str, Any]:
"""
- Get all settings, optionally filtered by type
-
- Args:
- setting_type: Optional filter by setting type
+ Get all settings
Returns:
- Dictionary of settings
+ Dictionary of all settings
"""
result = {}
- # Get from database if available
- if self.db_session:
- query = self.db_session.query(Setting)
- if setting_type:
- query = query.filter(Setting.type == setting_type)
-
- for setting in query.all():
- result[setting.key] = setting.value
-
- # Merge with cache (cache takes precedence)
+ # Start with memory cache (highest priority)
result.update(self._settings_cache)
- # Fall back to dynaconf for any settings not in DB or cache
- if not result:
- # Get from dynaconf
- if setting_type:
- # Try to get section from dynaconf
- section_name = setting_type.value.lower()
- section = getattr(dynaconf_settings, section_name, {})
- for key, value in section.items():
- full_key = f"{section_name}.{key}"
- result[full_key] = value
- else:
- # Get all settings from dynaconf
- for section in ["llm", "search", "report", "app"]:
- section_obj = getattr(dynaconf_settings, section, {})
- for key, value in section_obj.items():
+ # Add database settings if available
+ if self.db_session:
+ try:
+ for setting in self.db_session.query(Setting).all():
+ result[setting.key] = setting.value
+ except SQLAlchemyError as e:
+ logger.error(f"Error retrieving all settings from database: {e}")
+
+ # Fill in missing values from Dynaconf (lowest priority)
+ for section in ["llm", "search", "report", "app", "web"]:
+ if hasattr(dynaconf_settings, section):
+ section_obj = getattr(dynaconf_settings, section)
+ for key in dir(section_obj):
+ if not key.startswith("_") and not callable(
+ getattr(section_obj, key)
+ ):
full_key = f"{section}.{key}"
- result[full_key] = value
+ if full_key not in result:
+ result[full_key] = getattr(section_obj, key)
return result
@@ -322,7 +331,7 @@ class SettingsManager:
"""
try:
# Get settings
- settings = self.get_all_settings(setting_type)
+ settings = self.get_all_settings()
# Group by section
sections = {}
@@ -457,11 +466,12 @@ class SettingsManager:
try:
for setting in self.db_session.query(Setting).all():
self._settings_cache[setting.key] = setting.value
+ logger.info(f"Loaded {len(self._settings_cache)} settings from database")
except SQLAlchemyError as e:
logger.error(f"Error loading settings from database: {e}")
- def _load_settings_from_files(self):
- """Load settings from files into memory cache"""
+ def _load_settings_from_files_as_fallback(self):
+ """Load settings from files into memory cache, but only for keys not already in the database"""
# Load from main settings file
if os.path.exists(self.settings_file):
try:
@@ -469,7 +479,10 @@ class SettingsManager:
data = toml.load(f)
for section, values in data.items():
for key, value in values.items():
- self._settings_cache[f"{section}.{key}"] = value
+ full_key = f"{section}.{key}"
+ # Only add if not already in cache (from DB)
+ if full_key not in self._settings_cache:
+ self._settings_cache[full_key] = value
except Exception as e:
logger.error(f"Error loading settings from {self.settings_file}: {e}")
@@ -480,7 +493,10 @@ class SettingsManager:
data = toml.load(f)
if "search" in data:
for key, value in data["search"].items():
- self._settings_cache[f"search.{key}"] = value
+ full_key = f"search.{key}"
+ # Only add if not already in cache (from DB)
+ if full_key not in self._settings_cache:
+ self._settings_cache[full_key] = value
except Exception as e:
logger.error(
f"Error loading settings from {self.search_engines_file}: {e}"