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.

docs: Add architecture, extension guide, and troubleshooting documentation

LearningCircuit465b0f3e9e7d
diff --git a/docs/architecture/DATABASE_SCHEMA.md b/docs/architecture/DATABASE_SCHEMA.md
new file mode 100644
index 0000000000..596fe7c969
--- /dev/null
+++ b/docs/architecture/DATABASE_SCHEMA.md
@@ -0,0 +1,639 @@
+# Database Schema
+
+This document describes the database models and their relationships in Local Deep Research.
+
+## Table of Contents
+
+- [Overview](#overview)
+- [Entity Relationship Diagram](#entity-relationship-diagram)
+- [Model Groups](#model-groups)
+ - [Research Domain](#research-domain)
+ - [Authentication](#authentication)
+ - [Settings](#settings)
+ - [Library & Documents](#library--documents)
+ - [Queue Management](#queue-management)
+ - [Metrics & Analytics](#metrics--analytics)
+ - [News System](#news-system)
+ - [Benchmarking](#benchmarking)
+ - [Rate Limiting](#rate-limiting)
+ - [Caching](#caching)
+ - [File Integrity](#file-integrity)
+
+---
+
+## Overview
+
+Local Deep Research uses **SQLAlchemy ORM** with **SQLCipher** for encryption.
+
+**Key Characteristics:**
+- **Per-user databases**: Each user has their own encrypted SQLite database
+- **AES-256 encryption**: User password derives the encryption key
+- **HMAC verification**: Ensures database integrity
+- **Central auth database**: Only stores usernames (no passwords)
+
+**Location:** `src/local_deep_research/database/models/`
+
+---
+
+## Entity Relationship Diagram
+
+```mermaid
+erDiagram
+ %% Research Domain
+ ResearchTask ||--o{ SearchQuery : contains
+ ResearchTask ||--o{ SearchResult : produces
+ ResearchTask ||--o{ Report : generates
+ SearchQuery ||--o{ SearchResult : returns
+
+ Research ||--o{ ResearchHistory : tracks
+ Research ||--o{ ResearchResource : uses
+
+ Report ||--o{ ReportSection : contains
+
+ %% Library
+ Document ||--o{ DocumentChunk : splits_into
+ Document }o--o{ Collection : belongs_to
+ Collection ||--o{ RAGIndex : indexes
+
+ %% News
+ NewsSubscription ||--o{ NewsCard : produces
+ NewsCard ||--o{ UserRating : receives
+
+ %% Benchmarks
+ BenchmarkRun ||--o{ BenchmarkResult : contains
+ BenchmarkRun ||--o{ BenchmarkProgress : tracks
+
+ %% Queue
+ QueuedResearch ||--o| TaskMetadata : has
+
+ %% Metrics
+ Research ||--o{ TokenUsage : tracks
+ Research ||--o{ SearchCall : logs
+```
+
+---
+
+## Model Groups
+
+### Research Domain
+
+The core models for conducting research.
+
+#### ResearchTask
+
+Top-level research container.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `title` | String(500) | Research title |
+| `description` | Text | Detailed description |
+| `status` | String(50) | pending, in_progress, completed, failed |
+| `priority` | Integer | Priority level (higher = more urgent) |
+| `tags` | JSON | List of categorization tags |
+| `research_metadata` | JSON | Flexible metadata storage |
+| `created_at` | DateTime | Creation timestamp |
+| `updated_at` | DateTime | Last update timestamp |
+| `started_at` | DateTime | When research started |
+| `completed_at` | DateTime | When research completed |
+
+**Relationships:** `searches`, `results`, `reports`
+
+#### SearchQuery
+
+Individual search queries within a research task.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `research_task_id` | Integer | FK to ResearchTask |
+| `query` | Text | The search query text |
+| `search_engine` | String(50) | Engine used (duckduckgo, arxiv, etc.) |
+| `search_type` | String(50) | Type (web, academic, news) |
+| `parameters` | JSON | Additional search parameters |
+| `status` | String(50) | pending, executing, completed, failed |
+| `error_message` | Text | Error details if failed |
+| `retry_count` | Integer | Number of retry attempts |
+| `executed_at` | DateTime | When query was executed |
+
+**Indexes:** `idx_research_task_status`, `idx_search_engine`
+
+#### SearchResult
+
+Individual results from search queries.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `research_task_id` | Integer | FK to ResearchTask |
+| `search_query_id` | Integer | FK to SearchQuery |
+| `title` | String(500) | Result title |
+| `url` | Text | Result URL (indexed) |
+| `snippet` | Text | Brief preview |
+| `content` | Text | Full fetched content |
+| `content_type` | String(50) | html, pdf, text, etc. |
+| `content_hash` | String(64) | For deduplication |
+| `relevance_score` | Float | Calculated relevance |
+| `position` | Integer | Position in results |
+| `domain` | String(255) | Source domain (indexed) |
+| `language` | String(10) | Content language |
+| `published_date` | DateTime | Publication date |
+| `fetch_status` | String(50) | pending, fetched, failed, skipped |
+
+#### Research
+
+Simplified research record (alternative to ResearchTask).
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `query` | Text | Original query |
+| `mode` | Enum | ResearchMode value |
+| `strategy` | Enum | ResearchStrategy value |
+| `status` | Enum | ResearchStatus value |
+| `result` | Text | Final result/summary |
+| `iterations` | Integer | Iterations completed |
+| `created_at` | DateTime | Creation timestamp |
+
+**Enums:**
+- `ResearchMode`: quick, detailed, report
+- `ResearchStatus`: pending, running, completed, failed, cancelled
+- `ResearchStrategy`: source-based, focused-iteration, etc.
+
+#### ResearchHistory
+
+Tracks research iterations and progress.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `research_id` | Integer | FK to Research |
+| `iteration` | Integer | Iteration number |
+| `questions` | JSON | Questions asked |
+| `findings` | JSON | Findings discovered |
+| `created_at` | DateTime | When recorded |
+
+#### Report / ReportSection
+
+Generated research reports.
+
+| Column (Report) | Type | Description |
+|-----------------|------|-------------|
+| `id` | Integer | Primary key |
+| `research_task_id` | Integer | FK to ResearchTask |
+| `title` | String(500) | Report title |
+| `format` | String(50) | markdown, pdf, latex |
+| `content` | Text | Full report content |
+| `created_at` | DateTime | Generation time |
+
+| Column (ReportSection) | Type | Description |
+|------------------------|------|-------------|
+| `id` | Integer | Primary key |
+| `report_id` | Integer | FK to Report |
+| `title` | String(255) | Section title |
+| `content` | Text | Section content |
+| `order` | Integer | Display order |
+
+---
+
+### Authentication
+
+User management with per-user encrypted databases.
+
+#### User
+
+Central user registry (stored in auth database, not user database).
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `username` | String(80) | Unique username (indexed) |
+| `created_at` | DateTime | Registration date |
+| `last_login` | DateTime | Last login time |
+| `database_version` | Integer | Schema version |
+
+**Note:** Passwords are NEVER stored. They derive encryption keys.
+
+#### APIKey
+
+API keys for programmatic access.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `key_hash` | String(64) | Hashed API key |
+| `name` | String(100) | Key description |
+| `created_at` | DateTime | Creation date |
+| `last_used` | DateTime | Last usage |
+| `expires_at` | DateTime | Expiration date |
+| `is_active` | Boolean | Whether key is valid |
+
+---
+
+### Settings
+
+Configuration storage.
+
+#### Setting
+
+Global application settings.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `key` | String(255) | Setting key (unique, indexed) |
+| `value` | Text | Setting value |
+| `type` | Enum | SettingType (string, int, bool, json) |
+| `category` | String(100) | Setting category |
+| `description` | Text | Human-readable description |
+| `updated_at` | DateTime | Last update |
+
+#### UserSettings
+
+Per-user setting overrides.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `key` | String(255) | Setting key |
+| `value` | Text | User's value |
+| `updated_at` | DateTime | Last update |
+
+---
+
+### Library & Documents
+
+Document management for RAG.
+
+#### Document
+
+Documents in the research library.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `title` | String(500) | Document title |
+| `source_type` | Enum | SourceType (upload, url, api) |
+| `source_url` | Text | Original source URL |
+| `file_path` | Text | Local file path |
+| `file_hash` | String(64) | Content hash |
+| `mime_type` | String(100) | MIME type |
+| `file_size` | Integer | Size in bytes |
+| `text_content` | Text | Extracted text |
+| `metadata` | JSON | Additional metadata |
+| `created_at` | DateTime | When added |
+| `indexed_at` | DateTime | When indexed for RAG |
+
+**Enum SourceType:** upload, url, doi, arxiv, pubmed, semantic_scholar
+
+#### Collection
+
+Document collections for organization.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `name` | String(255) | Collection name |
+| `description` | Text | Description |
+| `is_default` | Boolean | Default collection flag |
+| `created_at` | DateTime | Creation date |
+
+#### DocumentCollection
+
+Junction table for document-collection relationship.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `document_id` | Integer | FK to Document |
+| `collection_id` | Integer | FK to Collection |
+
+#### DocumentChunk
+
+Text chunks for RAG indexing.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `document_id` | Integer | FK to Document |
+| `chunk_index` | Integer | Position in document |
+| `content` | Text | Chunk text |
+| `embedding` | BLOB | Vector embedding |
+| `metadata` | JSON | Chunk metadata |
+
+#### RAGIndex
+
+Vector index metadata.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `collection_id` | Integer | FK to Collection |
+| `status` | Enum | RAGIndexStatus |
+| `embedding_model` | String(100) | Model used |
+| `chunk_count` | Integer | Number of chunks |
+| `created_at` | DateTime | Creation time |
+| `updated_at` | DateTime | Last update |
+
+---
+
+### Queue Management
+
+Background task processing.
+
+#### QueuedResearch
+
+Research waiting to be processed.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `query` | Text | Research query |
+| `mode` | String(50) | Research mode |
+| `strategy` | String(50) | Strategy name |
+| `status` | Enum | QueueStatus |
+| `priority` | Integer | Queue priority |
+| `created_at` | DateTime | When queued |
+| `started_at` | DateTime | When started |
+| `completed_at` | DateTime | When finished |
+| `error` | Text | Error message if failed |
+
+**Enum QueueStatus:** pending, running, completed, failed, cancelled
+
+#### TaskMetadata
+
+Additional task information.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `queued_research_id` | Integer | FK to QueuedResearch |
+| `key` | String(255) | Metadata key |
+| `value` | Text | Metadata value |
+
+---
+
+### Metrics & Analytics
+
+Usage tracking and analytics.
+
+#### TokenUsage
+
+LLM token consumption.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `research_id` | Integer | FK to Research |
+| `model` | String(100) | Model name |
+| `provider` | String(50) | Provider name |
+| `input_tokens` | Integer | Input token count |
+| `output_tokens` | Integer | Output token count |
+| `cost` | Float | Estimated cost |
+| `created_at` | DateTime | When recorded |
+
+#### SearchCall
+
+Search API call logging.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `research_id` | Integer | FK to Research |
+| `engine` | String(50) | Search engine |
+| `query` | Text | Query text |
+| `result_count` | Integer | Results returned |
+| `duration_ms` | Integer | Request duration |
+| `success` | Boolean | Whether succeeded |
+| `created_at` | DateTime | When called |
+
+#### ModelUsage
+
+Aggregated model usage statistics.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `model` | String(100) | Model name |
+| `provider` | String(50) | Provider name |
+| `total_input_tokens` | Integer | Cumulative input |
+| `total_output_tokens` | Integer | Cumulative output |
+| `total_cost` | Float | Cumulative cost |
+| `request_count` | Integer | Number of requests |
+| `date` | Date | Aggregation date |
+
+#### ResearchRating
+
+User ratings for research quality.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `research_id` | Integer | FK to Research |
+| `rating` | Integer | 1-5 rating |
+| `feedback` | Text | Optional feedback |
+| `created_at` | DateTime | When rated |
+
+---
+
+### News System
+
+News subscription and recommendation.
+
+#### NewsSubscription
+
+User news subscriptions.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `topic` | String(255) | Subscription topic |
+| `type` | Enum | SubscriptionType |
+| `status` | Enum | SubscriptionStatus |
+| `frequency` | String(50) | Update frequency |
+| `last_fetched` | DateTime | Last fetch time |
+| `created_at` | DateTime | Creation date |
+
+#### NewsCard
+
+Individual news items.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `subscription_id` | Integer | FK to NewsSubscription |
+| `title` | String(500) | News title |
+| `summary` | Text | News summary |
+| `url` | Text | Source URL |
+| `source` | String(100) | Source name |
+| `published_at` | DateTime | Publication date |
+| `card_type` | Enum | CardType |
+| `created_at` | DateTime | When fetched |
+
+#### UserRating / UserPreference / NewsInterest
+
+User interaction tracking for recommendations.
+
+---
+
+### Benchmarking
+
+Performance benchmarking system.
+
+#### BenchmarkRun
+
+Benchmark execution record.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `name` | String(255) | Run name |
+| `dataset_type` | Enum | DatasetType (SimpleQA, BrowseComp) |
+| `strategy` | String(100) | Strategy tested |
+| `status` | Enum | BenchmarkStatus |
+| `config` | JSON | Configuration used |
+| `started_at` | DateTime | Start time |
+| `completed_at` | DateTime | End time |
+
+#### BenchmarkResult
+
+Individual benchmark results.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `run_id` | Integer | FK to BenchmarkRun |
+| `question` | Text | Test question |
+| `expected_answer` | Text | Expected answer |
+| `actual_answer` | Text | Model's answer |
+| `is_correct` | Boolean | Whether correct |
+| `score` | Float | Quality score |
+| `latency_ms` | Integer | Response time |
+| `tokens_used` | Integer | Tokens consumed |
+
+#### BenchmarkProgress
+
+Progress tracking during runs.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `run_id` | Integer | FK to BenchmarkRun |
+| `completed` | Integer | Questions completed |
+| `total` | Integer | Total questions |
+| `current_accuracy` | Float | Running accuracy |
+| `updated_at` | DateTime | Last update |
+
+---
+
+### Rate Limiting
+
+Adaptive rate limiting data.
+
+#### RateLimitAttempt
+
+Individual rate limit events.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `engine` | String(50) | Search engine |
+| `wait_time` | Float | Wait time used |
+| `success` | Boolean | Whether request succeeded |
+| `created_at` | DateTime | When occurred |
+
+#### RateLimitEstimate
+
+Learned rate limit estimates.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `engine` | String(50) | Search engine |
+| `estimated_wait` | Float | Optimal wait time |
+| `confidence` | Float | Estimate confidence |
+| `sample_count` | Integer | Data points used |
+| `updated_at` | DateTime | Last update |
+
+---
+
+### Caching
+
+Result caching for performance.
+
+#### SearchCache
+
+Cached search results.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `query_hash` | String(64) | Query hash (indexed) |
+| `engine` | String(50) | Search engine |
+| `results` | JSON | Cached results |
+| `expires_at` | DateTime | Cache expiration |
+| `created_at` | DateTime | When cached |
+
+#### Cache
+
+General-purpose cache.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `key` | String(255) | Cache key (unique) |
+| `value` | Text | Cached value |
+| `expires_at` | DateTime | Expiration time |
+| `created_at` | DateTime | When created |
+
+---
+
+### File Integrity
+
+File verification for security.
+
+#### FileIntegrityRecord
+
+File hash records.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `file_path` | Text | File path |
+| `sha256_hash` | String(64) | SHA256 hash |
+| `blake3_hash` | String(64) | BLAKE3 hash |
+| `file_size` | Integer | Size in bytes |
+| `verified_at` | DateTime | Last verification |
+| `created_at` | DateTime | First recorded |
+
+#### FileVerificationFailure
+
+Failed verification attempts.
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `id` | Integer | Primary key |
+| `file_path` | Text | File path |
+| `expected_hash` | String(64) | Expected hash |
+| `actual_hash` | String(64) | Computed hash |
+| `failure_type` | String(50) | Type of failure |
+| `created_at` | DateTime | When detected |
+
+---
+
+## Database Location
+
+```
+~/.local/share/local-deep-research/
+├── auth.db # Central auth database (unencrypted)
+└── users/
+ └── <username>/
+ └── research.db # User's encrypted database
+```
+
+---
+
+## See Also
+
+- [Architecture Overview](./OVERVIEW.md) - System architecture
+- [Extension Guide](../developing/EXTENDING.md) - Adding custom components
+- [Troubleshooting](../troubleshooting.md) - Common issues
diff --git a/docs/architecture/OVERVIEW.md b/docs/architecture/OVERVIEW.md
new file mode 100644
index 0000000000..a27594f913
--- /dev/null
+++ b/docs/architecture/OVERVIEW.md
@@ -0,0 +1,437 @@
+# Architecture Overview
+
+This document provides a comprehensive overview of Local Deep Research's system architecture.
+
+## Table of Contents
+
+- [System Components](#system-components)
+- [Entry Points](#entry-points)
+- [Research Execution Flow](#research-execution-flow)
+- [Module Responsibilities](#module-responsibilities)
+- [Threading Model](#threading-model)
+- [Configuration System](#configuration-system)
+- [Key Interfaces](#key-interfaces)
+
+---
+
+## System Components
+
+```mermaid
+graph TB
+ subgraph "Entry Points"
+ CLI[ldr CLI]
+ WEB[ldr-web Flask App]
+ API[REST API /api/v1]
+ end
+
+ subgraph "Core Research Engine"
+ SS[SearchSystem<br/>search_system.py]
+ SSF[StrategyFactory<br/>search_system_factory.py]
+ RG[ReportGenerator<br/>report_generator.py]
+ end
+
+ subgraph "Search Layer"
+ STRAT[32 Search Strategies<br/>advanced_search_system/strategies/]
+ ENG[30+ Search Engines<br/>web_search_engines/engines/]
+ RL[Rate Limiter<br/>rate_limiting/]
+ end
+
+ subgraph "Data Layer"
+ DB[(SQLCipher DB<br/>Per-User Encrypted)]
+ MODELS[20+ ORM Models<br/>database/models/]
+ CACHE[Memory Cache]
+ end
+
+ subgraph "LLM Layer"
+ PROV[LLM Providers<br/>Ollama, OpenAI, etc.]
+ EMB[Embeddings<br/>embeddings/]
+ RERANK[Reranker<br/>reranker/]
+ end
+
+ CLI --> SS
+ WEB --> SS
+ API --> SS
+
+ SS --> SSF
+ SS --> RG
+ SSF --> STRAT
+ STRAT --> ENG
+ ENG --> RL
+
+ SS --> PROV
+ SS --> DB
+ MODELS --> DB
+
+ RG --> PROV
+ ENG --> CACHE
+```
+
+---
+
+## Entry Points
+
+### Web Application (`ldr-web`)
+
+**Location:** `src/local_deep_research/web/app.py`
+
+The primary user interface. Launches a Flask server with SocketIO for real-time updates.
+
+```mermaid
+graph LR
+ A[Browser] -->|HTTP/WS| B[Flask App]
+ B --> C[Blueprints]
+ C --> D[research_routes]
+ C --> E[api_routes]
+ C --> F[settings_routes]
+ C --> G[auth_routes]
+ B -->|Real-time| H[SocketIO]
+```
+
+**Key files:**
+- `web/app.py` - Main entry, starts server
+- `web/app_factory.py` - Flask app creation with middleware
+- `web/routes/` - Blueprint route handlers
+- `web/services/` - Business logic services
+
+### CLI (`ldr`)
+
+**Location:** `src/local_deep_research/main.py`
+
+Command-line interface for headless research operations.
+
+### REST API (`/api/v1`)
+
+**Location:** `src/local_deep_research/web/api.py`
+
+Programmatic access for integrations.
+
+| Endpoint | Method | Purpose |
+|----------|--------|---------|
+| `/api/v1/quick_summary` | POST | Quick research summary |
+| `/api/v1/generate_report` | POST | Full research report |
+| `/api/v1/analyze_documents` | POST | Search local collections |
+| `/api/v1/health` | GET | Health check |
+
+---
+
+## Research Execution Flow
+
+```mermaid
+sequenceDiagram
+ participant User
+ participant Web as Flask App
+ participant SS as SearchSystem
+ participant SF as StrategyFactory
+ participant Strat as Strategy
+ participant Eng as SearchEngine
+ participant LLM as LLM Provider
+ participant DB as Database
+
+ User->>Web: Submit Query
+ Web->>SS: start_research()
+ SS->>SF: create_strategy(name)
+ SF-->>SS: Strategy instance
+
+ loop Research Iterations
+ SS->>Strat: analyze_topic(query)
+ Strat->>LLM: Generate questions
+ LLM-->>Strat: Questions
+
+ loop Per Question
+ Strat->>Eng: search(question)
+ Eng-->>Strat: Results
+ end
+
+ Strat->>LLM: Synthesize findings
+ LLM-->>Strat: Synthesis
+ Strat-->>SS: Findings
+ end
+
+ SS->>DB: Save results
+ SS-->>Web: Research complete
+ Web-->>User: Results via SocketIO
+```
+
+---
+
+## Module Responsibilities
+
+### Core Modules
+
+| Module | Location | Responsibility |
+|--------|----------|----------------|
+| **SearchSystem** | `search_system.py` | Orchestrates research, coordinates strategies and engines |
+| **StrategyFactory** | `search_system_factory.py` | Creates strategy instances based on configuration |
+| **ReportGenerator** | `report_generator.py` | Generates structured reports from research findings |
+| **CitationHandler** | `citation_handler.py` | Processes and validates citations |
+
+### Search System
+
+| Module | Location | Responsibility |
+|--------|----------|----------------|
+| **BaseSearchEngine** | `web_search_engines/search_engine_base.py` | Abstract base for all search engines |
+| **SearchEngineFactory** | `web_search_engines/search_engine_factory.py` | Creates engine instances |
+| **RateLimitTracker** | `web_search_engines/rate_limiting/tracker.py` | Adaptive rate limiting |
+| **RetrieverRegistry** | `web_search_engines/retriever_registry.py` | LangChain retriever integration |
+
+### Strategy System
+
+| Module | Location | Responsibility |
+|--------|----------|----------------|
+| **BaseSearchStrategy** | `advanced_search_system/strategies/base_strategy.py` | Abstract base for strategies |
+| **FindingsRepository** | `advanced_search_system/findings/` | Accumulates research findings |
+| **QuestionGenerator** | `advanced_search_system/questions/` | Generates research questions |
+
+### Web Application
+
+| Module | Location | Responsibility |
+|--------|----------|----------------|
+| **SocketIOService** | `web/services/socket_service.py` | Real-time communication |
+| **ResearchService** | `web/services/research_service.py` | Research execution |
+| **QueueManager** | `web/queue/` | Background task queue |
+| **SessionManager** | `web/auth/session_manager.py` | User session handling |
+
+### Data Layer
+
+| Module | Location | Responsibility |
+|--------|----------|----------------|
+| **Models** | `database/models/` | SQLAlchemy ORM models |
+| **SessionContext** | `database/session_context.py` | Thread-safe DB sessions |
+| **EncryptedDB** | `database/encrypted_db.py` | SQLCipher integration |
+
+### LLM Integration
+
+| Module | Location | Responsibility |
+|--------|----------|----------------|
+| **LLM Providers** | `llm/providers/implementations/` | Provider-specific LLM wrappers |
+| **AutoDiscovery** | `llm/providers/auto_discovery.py` | Dynamic provider detection |
+| **LLMRegistry** | `llm/llm_registry.py` | Custom LLM registration |
+
+---
+
+## Threading Model
+
+```mermaid
+graph TB
+ subgraph "Main Thread"
+ FLASK[Flask Server]
+ SOCKETIO[SocketIO Handler]
+ end
+
+ subgraph "Research Threads"
+ RT1[Research Thread 1]
+ RT2[Research Thread 2]
+ RTN[Research Thread N]
+ end
+
+ subgraph "Queue Processor"
+ QP[Queue Processor Thread]
+ end
+
+ subgraph "Thread-Local Storage"
+ TC[Thread Context<br/>Settings Snapshot]
+ DBS[DB Session<br/>Per-User]
+ end
+
+ FLASK --> RT1
+ FLASK --> RT2
+ FLASK --> RTN
+
+ RT1 --> TC
+ RT2 --> TC
+ RTN --> TC
+
+ QP --> RT1
+
+ RT1 -.-> SOCKETIO
+ RT2 -.-> SOCKETIO
+```
+
+**Key Threading Concepts:**
+
+1. **Thread Context** (`config/thread_settings.py`)
+ - Each research thread has its own settings snapshot
+ - Prevents race conditions on configuration changes
+
+2. **Per-User DB Sessions** (`database/session_context.py`)
+ - Each user has an isolated SQLCipher database
+ - Sessions are thread-local via context manager
+
+3. **Queue Processing** (`web/queue/`)
+ - Background queue for long-running research
+ - Processes items from `QueuedResearch` table
+
+4. **SocketIO Updates**
+ - Research threads emit progress via SocketIO
+ - Uses threading async mode (not asyncio)
+
+---
+
+## Configuration System
+
+```mermaid
+graph TB
+ subgraph "Configuration Sources"
+ ENV[Environment Variables<br/>.env files]
+ DB[(Database Settings<br/>per-user)]
+ TOML[Default TOML<br/>settings.toml]
+ end
+
+ subgraph "Settings Management"
+ DYNACONF[Dynaconf<br/>env_registry.py]
+ SM[SettingsManager<br/>manager.py]
+ end
+
+ subgraph "Runtime Access"
+ SNAP[Settings Snapshot<br/>Thread-safe copy]
+ TC[Thread Context<br/>thread_settings.py]
+ end
+
+ ENV --> DYNACONF
+ TOML --> DYNACONF
+ DYNACONF --> SM
+ DB --> SM
+ SM --> SNAP
+ SNAP --> TC
+```
+
+**Configuration Flow:**
+
+1. **Bootstrap** - Environment variables loaded via Dynaconf
+2. **Database** - User settings loaded from encrypted per-user DB
+3. **Snapshot** - Thread-safe copy created for each research
+4. **Access** - Code reads from snapshot via thread context
+
+**Key Settings Categories:**
+
+| Category | Examples |
+|----------|----------|
+| `llm.*` | Provider, model, temperature, API keys |
+| `search.*` | Engine selection, max results, rate limits |
+| `app.*` | Debug mode, logging, UI preferences |
+| `notifications.*` | Email, webhook configurations |
+
+---
+
+## Key Interfaces
+
+### Search Engine Interface
+
+All search engines implement `BaseSearchEngine`:
+
+```python
+class BaseSearchEngine(ABC):
+ # Classification flags
+ is_public: bool = True
+ is_generic: bool = True
+ is_scientific: bool = False
+ is_local: bool = False
+ is_news: bool = False
+ is_code: bool = False
+
+ @abstractmethod
+ def run(self, query: str) -> List[Dict[str, Any]]:
+ """Execute search and return results."""
+ # Returns: [{"title": ..., "link": ..., "snippet": ...}]
+```
+
+### Strategy Interface
+
+All strategies implement `BaseSearchStrategy`:
+
+```python
+class BaseSearchStrategy(ABC):
+ def __init__(self, search, model, all_links_of_system,
+ settings_snapshot, **kwargs):
+ ...
+
+ @abstractmethod
+ def analyze_topic(self, query: str) -> Dict:
+ """Execute research strategy."""
+ # Returns: {
+ # "findings": [...],
+ # "iterations": int,
+ # "questions": {...},
+ # "formatted_findings": str,
+ # "current_knowledge": {...}
+ # }
+```
+
+### LLM Provider Interface
+
+All providers extend `OpenAICompatibleProvider`:
+
+```python
+class OpenAICompatibleProvider:
+ provider_name: str
+ api_key_setting: str
+ url_setting: str
+ default_base_url: str
+ default_model: str
+
+ @classmethod
+ def create_llm(cls, model_name, temperature, **kwargs) -> BaseChatModel:
+ """Create LangChain LLM instance."""
+```
+
+---
+
+## Directory Structure
+
+```
+src/local_deep_research/
+├── search_system.py # Main orchestrator
+├── search_system_factory.py # Strategy factory
+├── report_generator.py # Report generation
+├── citation_handler.py # Citation processing
+│
+├── web/ # Flask application
+│ ├── app.py # Entry point
+│ ├── app_factory.py # App creation
+│ ├── routes/ # Blueprint handlers
+│ ├── services/ # Business logic
+│ ├── queue/ # Task queue
+│ └── auth/ # Authentication
+│
+├── advanced_search_system/ # Search strategies
+│ ├── strategies/ # 32 strategy implementations
+│ ├── questions/ # Question generation
+│ ├── findings/ # Findings management
+│ └── ...
+│
+├── web_search_engines/ # Search engines
+│ ├── engines/ # 30+ engine implementations
+│ ├── search_engine_base.py # Abstract base
+│ ├── search_engine_factory.py
+│ └── rate_limiting/ # Adaptive rate limiting
+│
+├── database/ # Data layer
+│ ├── models/ # 20+ ORM models
+│ ├── session_context.py # Session management
+│ └── encrypted_db.py # SQLCipher
+│
+├── llm/ # LLM integration
+│ ├── providers/ # Provider implementations
+│ └── llm_registry.py # Custom LLM registration
+│
+├── config/ # Configuration
+│ ├── llm_config.py # LLM setup
+│ ├── search_config.py # Search setup
+│ └── thread_settings.py # Thread context
+│
+├── settings/ # Settings management
+│ ├── manager.py # SettingsManager
+│ └── env_registry.py # Dynaconf setup
+│
+└── api/ # Programmatic API
+ ├── client.py # HTTP client
+ └── research_functions.py # Direct functions
+```
+
+---
+
+## See Also
+
+- [Database Schema](./DATABASE_SCHEMA.md) - Detailed data model documentation
+- [Extension Guide](../developing/EXTENDING.md) - How to add custom components
+- [Troubleshooting](../troubleshooting.md) - Common issues and solutions
diff --git a/docs/developing/EXTENDING.md b/docs/developing/EXTENDING.md
new file mode 100644
index 0000000000..ac4d17946b
--- /dev/null
+++ b/docs/developing/EXTENDING.md
@@ -0,0 +1,621 @@
+# Extension Guide
+
+This guide explains how to extend Local Deep Research with custom components.
+
+## Table of Contents
+
+- [Adding Custom Search Engines](#adding-custom-search-engines)
+- [Adding Custom Search Strategies](#adding-custom-search-strategies)
+- [Using LangChain Retrievers](#using-langchain-retrievers)
+- [Adding Custom LLM Providers](#adding-custom-llm-providers)
+- [Registering Custom LLMs](#registering-custom-llms)
+
+---
+
+## Adding Custom Search Engines
+
+Search engines are responsible for fetching results from external sources. All engines extend `BaseSearchEngine`.
+
+### Basic Search Engine
+
+Create a new file in `src/local_deep_research/web_search_engines/engines/`:
+
+```python
+# search_engine_custom.py
+from typing import Any, Dict, List, Optional
+
+from langchain_core.language_models import BaseLLM
+from loguru import logger
+
+from ..search_engine_base import BaseSearchEngine
+
+
+class CustomSearchEngine(BaseSearchEngine):
+ """Custom search engine implementation."""
+
+ # Classification flags - set appropriately for your engine
+ is_public = True # Searches public internet
+ is_generic = False # Specialized (vs general web search)
+ is_scientific = False # Academic/scientific content
+ is_local = False # Local document search
+ is_news = False # News content
+ is_code = False # Code repositories
+
+ def __init__(
+ self,
+ max_results: int = 10,
+ credential: Optional[str] = None,
+ llm: Optional[BaseLLM] = None,
+ max_filtered_results: Optional[int] = None,
+ **kwargs,
+ ):
+ """
+ Initialize the search engine.
+
+ Args:
+ max_results: Maximum number of results to return
+ credential: API credential for the service (if required)
+ llm: Language model for relevance filtering
+ max_filtered_results: Max results after filtering
+ **kwargs: Additional parameters
+ """
+ super().__init__(
+ llm=llm,
+ max_filtered_results=max_filtered_results,
+ max_results=max_results,
+ )
+ self.credential = credential
+
+ def _get_previews(self, query: str) -> List[Dict[str, Any]]:
+ """
+ Get preview results (first phase of two-phase retrieval).
+
+ Args:
+ query: Search query
+
+ Returns:
+ List of preview dictionaries with keys:
+ - id: Unique identifier
+ - title: Result title
+ - snippet: Brief description/summary
+ - link: URL to the content
+ - source: Source name (e.g., "CustomEngine")
+ """
+ logger.info(f"Searching custom engine for: {query}")
+
+ # Apply rate limiting before request
+ self._last_wait_time = self.rate_tracker.apply_rate_limit(self.engine_type)
+
+ # Your search implementation here
+ results = self._call_api(query)
+
+ previews = []
+ for item in results:
+ previews.append({
+ "id": item["id"],
+ "title": item["title"],
+ "snippet": item["description"],
+ "link": item["url"],
+ "source": "CustomEngine",
+ })
+
+ return previews
+
+ def _get_full_content(
+ self, relevant_items: List[Dict[str, Any]]
+ ) -> List[Dict[str, Any]]:
+ """
+ Get full content for relevant items (second phase).
+
+ Args:
+ relevant_items: Items that passed relevance filtering
+
+ Returns:
+ Items enriched with full content
+ """
+ results = []
+ for item in relevant_items:
+ # Apply rate limiting
+ self._last_wait_time = self.rate_tracker.apply_rate_limit(self.engine_type)
+
+ # Fetch full content
+ full_content = self._fetch_content(item["link"])
+
+ result = item.copy()
+ result["content"] = full_content
+ result["full_content"] = full_content
+ results.append(result)
+
+ return results
+
+ def _call_api(self, query: str) -> List[Dict]:
+ """Your API implementation."""
+ # Implement your search logic here
+ pass
+
+ def _fetch_content(self, url: str) -> str:
+ """Fetch full content from URL."""
+ # Implement content fetching
+ pass
+```
+
+### Registering the Engine
+
+**Option 1: Via Settings Database (Web UI)**
+
+Add the engine configuration through the settings:
+
+```python
+# Key: search.engine.web.custom_engine
+config = {
+ "module_path": "local_deep_research.web_search_engines.engines.search_engine_custom",
+ "class_name": "CustomSearchEngine",
+ "requires_api_key": True,
+ "requires_llm": False,
+ "description": "Custom search engine for specific use case",
+ "strengths": ["Feature 1", "Feature 2"],
+ "weaknesses": ["Limitation 1"],
+ "reliability": "High",
+ "default_params": {
+ "max_results": 10
+ }
+}
+```
+
+**Option 2: Modify Factory (For Core Engines)**
+
+Add to `search_engine_factory.py`:
+
+```python
+def create_search_engine(engine_name: str, ...) -> BaseSearchEngine:
+ # ... existing code ...
+
+ if engine_name.lower() == "custom_engine":
+ from .engines.search_engine_custom import CustomSearchEngine
+ return CustomSearchEngine(
+ max_results=max_results,
+ api_key=api_key,
+ llm=llm,
+ **kwargs
+ )
+```
+
+### Search Engine Best Practices
+
+1. **Always apply rate limiting** before API calls:
+ ```python
+ self._last_wait_time = self.rate_tracker.apply_rate_limit(self.engine_type)
+ ```
+
+2. **Set classification flags** accurately - they affect engine selection
+
+3. **Handle errors gracefully** - return empty list on failure, don't crash
+
+4. **Use logging** for debugging:
+ ```python
+ from loguru import logger
+ logger.info(f"Searching for: {query}")
+ logger.error(f"API error: {e}")
+ ```
+
+5. **Support snippet-only mode** by checking the config:
+ ```python
+ from ...config import search_config
+ if search_config.SEARCH_SNIPPETS_ONLY:
+ return relevant_items # Skip full content
+ ```
+
+---
+
+## Adding Custom Search Strategies
+
+Strategies define how research is conducted - question generation, iteration, and synthesis.
+
+### Basic Strategy
+
+Create a new file in `src/local_deep_research/advanced_search_system/strategies/`:
+
+```python
+# my_custom_strategy.py
+from typing import Dict, List, Optional
+from loguru import logger
+
+from .base_strategy import BaseSearchStrategy
+
+
+class MyCustomStrategy(BaseSearchStrategy):
+ """Custom search strategy implementation."""
+
+ def __init__(
+ self,
+ search=None,
+ model=None,
+ all_links_of_system=None,
+ settings_snapshot=None,
+ max_iterations: int = 3,
+ **kwargs,
+ ):
+ """
+ Initialize the strategy.
+
+ Args:
+ search: Search engine instance
+ model: LLM for question generation and synthesis
+ all_links_of_system: Shared list for discovered links
+ settings_snapshot: Configuration snapshot
+ max_iterations: Maximum research iterations
+ **kwargs: Additional parameters
+ """
+ super().__init__(
+ all_links_of_system=all_links_of_system,
+ settings_snapshot=settings_snapshot,
+ )
+ self.search = search
+ self.model = model
+ self.max_iterations = max_iterations
+
+ def analyze_topic(self, query: str) -> Dict:
+ """
+ Execute the research strategy.
+
+ Args:
+ query: Research query
+
+ Returns:
+ Dict with:
+ - findings: List of research findings
+ - iterations: Number of iterations completed
+ - questions: Dict of questions by iteration
+ - formatted_findings: Formatted output string
+ - current_knowledge: Accumulated knowledge dict
+ - error: Optional error message
+ """
+ logger.info(f"Starting custom strategy for: {query}")
+
+ findings = []
+ current_knowledge = {}
+
+ try:
+ for iteration in range(1, self.max_iterations + 1):
+ # Update progress
+ self._update_progress(
+ f"Iteration {iteration}/{self.max_iterations}",
+ progress_percent=int(iteration / self.max_iterations * 100),
+ metadata={"iteration": iteration}
+ )
+
+ # Generate questions for this iteration
+ questions = self._generate_questions(query, current_knowledge)
+ self.questions_by_iteration[iteration] = questions
+
+ # Search for each question
+ for question in questions:
+ results = self._search(question)
+ findings.extend(results)
+
+ # Track links
+ for result in results:
+ if result.get("link"):
+ self.all_links_of_system.append(result["link"])
+
+ # Synthesize findings
+ current_knowledge = self._synthesize(findings)
+
+ # Check if we should stop early
+ if self._should_stop(current_knowledge):
+ logger.info(f"Early stopping at iteration {iteration}")
+ break
+
+ # Format final output
+ formatted = self._format_findings(findings, current_knowledge)
+
+ return {
+ "findings": findings,
+ "iterations": iteration,
+ "questions": self.questions_by_iteration,
+ "formatted_findings": formatted,
+ "current_knowledge": current_knowledge,
+ }
+
+ except Exception as e:
+ logger.error(f"Strategy error: {e}")
+ return {
+ "findings": findings,
+ "iterations": 0,
+ "questions": self.questions_by_iteration,
+ "formatted_findings": "",
+ "current_knowledge": current_knowledge,
+ "error": str(e),
+ }
+
+ def _generate_questions(self, query: str, knowledge: Dict) -> List[str]:
+ """Generate research questions using the LLM."""
+ prompt = f"""Given the query: {query}
+ And current knowledge: {knowledge}
+ Generate 3 specific research questions."""
+
+ response = self.model.invoke(prompt)
+ # Parse response into questions
+ return self._parse_questions(response.content)
+
+ def _search(self, question: str) -> List[Dict]:
+ """Execute search for a question."""
+ return self.search.run(question)
+
+ def _synthesize(self, findings: List[Dict]) -> Dict:
+ """Synthesize findings into knowledge."""
+ # Implement synthesis logic
+ return {"summary": "...", "key_points": [...]}
+
+ def _should_stop(self, knowledge: Dict) -> bool:
+ """Check if research should stop early."""
+ # Implement stopping criteria
+ return False
+
+ def _format_findings(self, findings: List[Dict], knowledge: Dict) -> str:
+ """Format findings as output string."""
+ # Implement formatting
+ return "Formatted research results..."
+
+ def _parse_questions(self, content: str) -> List[str]:
+ """Parse LLM response into question list."""
+ # Implement parsing
+ return content.strip().split("\n")
+```
+
+### Registering the Strategy
+
+Add to `search_system_factory.py`:
+
+```python
+def create_strategy(strategy_name: str, ...) -> BaseSearchStrategy:
+ strategy_name_lower = strategy_name.lower()
+
+ # ... existing strategies ...
+
+ elif strategy_name_lower in ["my-custom", "mycustom", "custom"]:
+ from .advanced_search_system.strategies.my_custom_strategy import (
+ MyCustomStrategy,
+ )
+ return MyCustomStrategy(
+ search=search,
+ model=model,
+ all_links_of_system=all_links_of_system,
+ settings_snapshot=settings_snapshot,
+ **kwargs
+ )
+```
+
+### Strategy Best Practices
+
+1. **Use progress callbacks** to update the UI:
+ ```python
+ self._update_progress("Searching...", progress_percent=50)
+ ```
+
+2. **Track all discovered links** in `self.all_links_of_system`
+
+3. **Store questions by iteration** in `self.questions_by_iteration`
+
+4. **Access settings** via the snapshot:
+ ```python
+ max_results = self.get_setting("search.max_results", default=10)
+ ```
+
+5. **Handle errors gracefully** - return partial results with error message
+
+---
+
+## Using LangChain Retrievers
+
+The easiest way to add custom search is through LangChain retrievers.
+
+### Registering a Retriever
+
+```python
+from langchain_community.vectorstores import FAISS
+from langchain_openai import OpenAIEmbeddings
+from local_deep_research.web_search_engines.retriever_registry import retriever_registry
+
+# Create your retriever
+embeddings = OpenAIEmbeddings()
+vectorstore = FAISS.from_documents(documents, embeddings)
+retriever = vectorstore.as_retriever(search_kwargs={"k": 10})
+
+# Register globally
+retriever_registry.register("my_documents", retriever)
+
+# Now use in research
+from local_deep_research.api import quick_summary
+
+result = quick_summary(
+ query="What does the documentation say about X?",
+ search_tool="my_documents", # Use registered retriever
+ programmatic_mode=True
+)
+```
+
+### Passing Retrievers Directly
+
+```python
+from local_deep_research.api import quick_summary
+
+# Create retriever
+retriever = my_vectorstore.as_retriever()
+
+# Pass directly to API
+result = quick_summary(
+ query="Search my documents",
+ retrievers={"private_docs": retriever},
+ search_tool="private_docs",
+ programmatic_mode=True
+)
+```
+
+### Registry Methods
+
+```python
+from local_deep_research.web_search_engines.retriever_registry import retriever_registry
+
+# Register
+retriever_registry.register("name", retriever)
+retriever_registry.register_multiple({"a": ret1, "b": ret2})
+
+# Query
+retriever_registry.get("name")
+retriever_registry.is_registered("name")
+retriever_registry.list_registered()
+
+# Remove
+retriever_registry.unregister("name")
+retriever_registry.clear()
+```
+
+---
+
+## Adding Custom LLM Providers
+
+LLM providers wrap language model APIs for use in LDR.
+
+### Basic Provider
+
+Create in `src/local_deep_research/llm/providers/implementations/`:
+
+```python
+# my_provider.py
+from typing import Any, Dict, Optional
+
+from langchain_core.language_models import BaseChatModel
+from langchain_openai import ChatOpenAI
+
+from ..openai_compatible import OpenAICompatibleProvider
+
+
+class MyProvider(OpenAICompatibleProvider):
+ """Custom LLM provider."""
+
+ provider_name = "My Provider"
+ api_key_setting = "llm.my_provider.api_key"
+ url_setting = "llm.my_provider.url"
+ default_base_url = "https://api.myprovider.com/v1"
+ default_model = "my-model-v1"
+
+ @classmethod
+ def create_llm(
+ cls,
+ model_name: Optional[str] = None,
+ temperature: float = 0.7,
+ settings_snapshot: Optional[Dict] = None,
+ **kwargs
+ ) -> BaseChatModel:
+ """
+ Create LLM instance.
+
+ Args:
+ model_name: Model to use
+ temperature: Sampling temperature
+ settings_snapshot: Configuration
+ **kwargs: Additional parameters
+
+ Returns:
+ LangChain chat model instance
+ """
+ settings_snapshot = settings_snapshot or {}
+
+ # Get API key from settings
+ api_key = cls._get_setting(settings_snapshot, cls.api_key_setting)
+ if not api_key:
+ raise ValueError(f"API key not found in {cls.api_key_setting}")
+
+ # Get base URL
+ base_url = cls._get_setting(
+ settings_snapshot, cls.url_setting, cls.default_base_url
+ )
+
+ return ChatOpenAI(
+ model=model_name or cls.default_model,
+ temperature=temperature,
+ api_key=api_key,
+ base_url=base_url,
+ **kwargs
+ )
+
+ @classmethod
+ def list_models(cls, settings_snapshot: Optional[Dict] = None) -> list[str]:
+ """List available models."""
+ return ["my-model-v1", "my-model-v2", "my-model-large"]
+```
+
+### Register in Auto-Discovery
+
+Add to `auto_discovery.py`:
+
+```python
+PROVIDER_METADATA = {
+ # ... existing providers ...
+ "my_provider": ProviderMetadata(
+ provider_id="my_provider",
+ provider_name="My Provider",
+ company_name="My Company",
+ region="US",
+ country="United States",
+ data_location="US",
+ gdpr_compliant=False,
+ is_cloud=True,
+ ),
+}
+```
+
+---
+
+## Registering Custom LLMs
+
+For programmatic use, register LLMs directly:
+
+```python
+from langchain_openai import ChatOpenAI
+from local_deep_research.llm.llm_registry import register_llm, get_llm_from_registry
+
+# Create custom LLM
+custom_llm = ChatOpenAI(
+ model="gpt-4",
+ temperature=0.5,
+ api_key="...",
+)
+
+# Register it
+register_llm("my_gpt4", custom_llm)
+
+# Use in research
+from local_deep_research.api import quick_summary
+
+result = quick_summary(
+ query="Research topic",
+ llms={"my_gpt4": custom_llm}, # Or use registered name
+ provider_name="my_gpt4",
+ programmatic_mode=True
+)
+```
+
+### Factory Functions
+
+You can also register factory functions:
+
+```python
+def create_my_llm(temperature=0.7):
+ return ChatOpenAI(model="gpt-4", temperature=temperature)
+
+register_llm("my_factory", create_my_llm)
+
+# Will be called when needed
+llm = get_llm_from_registry("my_factory")
+```
+
+---
+
+## See Also
+
+- [Architecture Overview](../architecture/OVERVIEW.md) - System architecture
+- [Database Schema](../architecture/DATABASE_SCHEMA.md) - Data models
+- [Troubleshooting](../troubleshooting.md) - Common issues
+- [API Quickstart](../api-quickstart.md) - Using the API
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
new file mode 100644
index 0000000000..fe45debede
--- /dev/null
+++ b/docs/troubleshooting.md
@@ -0,0 +1,556 @@
+# Troubleshooting Guide
+
+This guide covers common issues and their solutions.
+
+## Table of Contents
+
+- [LLM Connection Issues](#llm-connection-issues)
+- [Search Engine Issues](#search-engine-issues)
+- [Rate Limiting](#rate-limiting)
+- [Database Issues](#database-issues)
+- [WebSocket/Real-time Updates](#websocketreal-time-updates)
+- [Docker Issues](#docker-issues)
+- [API Issues](#api-issues)
+- [Performance Issues](#performance-issues)
+
+---
+
+## LLM Connection Issues
+
+### Ollama Not Connecting
+
+**Symptoms:**
+- "Failed to connect to Ollama"
+- "Connection refused" errors
+- Empty responses from LLM
+
+**Solutions:**
+
+1. **Verify Ollama is running:**
+ ```bash
+ curl http://localhost:11434/api/tags
+ ```
+
+2. **Check the URL configuration:**
+ - Default: `http://localhost:11434`
+ - For Docker: Use `http://host.docker.internal:11434` or your host IP
+ - Settings location: `llm.ollama.url`
+
+3. **Verify the model is pulled:**
+ ```bash
+ ollama list
+ ollama pull llama3.2
+ ```
+
+4. **Check Docker networking:**
+ ```bash
+ # If running LDR in Docker, Ollama on host:
+ docker run --add-host=host.docker.internal:host-gateway ...
+ ```
+
+### OpenAI API Errors
+
+**Symptoms:**
+- "Invalid API key"
+- "Rate limit exceeded"
+- "Model not found"
+
+**Solutions:**
+
+1. **Verify API key format:**
+ - Should start with `sk-`
+ - Check for leading/trailing whitespace
+
+2. **Check API key permissions:**
+ - Ensure key has access to the model you're using
+ - Verify organization ID if using org-scoped keys
+
+3. **Rate limits:**
+ - Wait and retry for rate limit errors
+ - Consider using a higher tier API key
+ - Reduce `questions_per_iteration` setting
+
+4. **Model availability:**
+ - Verify model name is correct (e.g., `gpt-4`, not `gpt4`)
+ - Check if model is available in your region
+
+### OpenRouter Issues
+
+**Symptoms:**
+- Authentication failures
+- Model not available
+
+**Solutions:**
+
+1. **API key format:**
+ ```
+ # Settings
+ llm.openrouter.api_key = <your-key-here>
+ ```
+
+2. **Model naming:**
+ - Use full model paths: `anthropic/claude-3-opus`
+ - Check available models at openrouter.ai/docs
+
+---
+
+## Search Engine Issues
+
+### DuckDuckGo Returning No Results
+
+**Symptoms:**
+- Empty search results
+- "No results found" consistently
+
+**Solutions:**
+
+1. **Rate limiting:** DuckDuckGo aggressively rate limits. Solutions:
+ - Switch to SearXNG or another engine
+ - Increase wait time in rate limiting settings
+ - Use `search.rate_limiting.profile = conservative`
+
+2. **Check network:** Verify you can access DuckDuckGo directly
+
+3. **Try alternative engines:**
+ ```python
+ # In settings
+ search.tool = "searxng" # or "brave", "tavily", etc.
+ ```
+
+### SearXNG Setup Issues
+
+**Symptoms:**
+- "Connection refused"
+- "404 Not Found"
+
+**Solutions:**
+
+1. **Verify SearXNG is running:**
+ ```bash
+ curl http://localhost:8080/search?q=test&format=json
+ ```
+
+2. **Check URL configuration:**
+ ```
+ search.engine.searxng.url = http://localhost:8080
+ ```
+
+3. **Ensure JSON format is enabled** in SearXNG settings
+
+4. **Docker networking:** Same as Ollama - use proper host references
+
+### API Key Issues for Search Engines
+
+**Symptoms:**
+- "API key required"
+- "Unauthorized" errors
+
+**Solutions:**
+
+1. **Verify key is set:**
+ - Check in Settings > Search > [Engine Name]
+ - Or via environment variable
+
+2. **Engine-specific settings:**
+ | Engine | Setting Key |
+ |--------|-------------|
+ | Brave | `search.engine.brave.api_key` |
+ | Tavily | `search.engine.tavily.api_key` |
+ | Serper | `search.engine.serper.api_key` |
+ | SerpAPI | `search.engine.serpapi.api_key` |
+
+---
+
+## Rate Limiting
+
+### "Rate limit exceeded" Errors
+
+**Symptoms:**
+- Searches failing with rate limit errors
+- Long waits between searches
+- Inconsistent search performance
+
+**Solutions:**
+
+1. **View current rate limit status:**
+ ```bash
+ python -m local_deep_research.web_search_engines.rate_limiting status
+ ```
+
+2. **Reset rate limits for an engine:**
+ ```bash
+ python -m local_deep_research.web_search_engines.rate_limiting reset --engine duckduckgo
+ ```
+
+3. **Adjust rate limiting profile:**
+ ```
+ # Options: conservative, balanced, aggressive
+ search.rate_limiting.profile = conservative
+ ```
+
+4. **Use multiple search engines** to distribute load:
+ ```
+ search.tool = auto # Automatically selects engines
+ ```
+
+### Rate Limiting CLI Commands
+
+```bash
+# View status
+python -m local_deep_research.web_search_engines.rate_limiting status
+python -m local_deep_research.web_search_engines.rate_limiting status --engine arxiv
+
+# Reset learned rates
+python -m local_deep_research.web_search_engines.rate_limiting reset --engine duckduckgo
+
+# Clean old data
+python -m local_deep_research.web_search_engines.rate_limiting cleanup --days 30
+
+# Export data
+python -m local_deep_research.web_search_engines.rate_limiting export --format csv
+```
+
+---
+
+## Database Issues
+
+### "Database is locked" Errors
+
+**Symptoms:**
+- SQLite lock errors
+- Operations timing out
+- Concurrent access failures
+
+**Solutions:**
+
+1. **Check for zombie processes:**
+ ```bash
+ ps aux | grep python
+ # Kill any stuck LDR processes
+ ```
+
+2. **Increase timeout:**
+ - Database operations have built-in retry logic
+ - Check logs for persistent issues
+
+3. **Verify disk space:**
+ ```bash
+ df -h
+ ```
+
+### Encryption/SQLCipher Issues
+
+**Symptoms:**
+- "file is not a database"
+- "database disk image is malformed"
+- Cannot open user database
+
+**Solutions:**
+
+1. **Verify SQLCipher is installed:**
+ ```bash
+ pip show sqlcipher3-binary
+ ```
+
+2. **Check password/key:**
+ - User databases are encrypted with derived keys
+ - Password changes require re-encryption
+
+3. **For corrupted databases:**
+ - Check `~/.local/share/local-deep-research/users/` for backups
+ - Consider creating a new user account
+
+4. **Integrity check:**
+ - Use the `/auth/integrity-check` endpoint
+ - Or run manual SQLite integrity checks
+
+### Migration Issues
+
+**Symptoms:**
+- Schema version mismatch
+- Missing tables or columns
+
+**Solutions:**
+
+1. **Check version:**
+ ```python
+ from local_deep_research import __version__
+ print(__version__)
+ ```
+
+2. **Run migrations** (if applicable):
+ - Migrations are typically automatic on startup
+ - Check logs for migration errors
+
+---
+
+## WebSocket/Real-time Updates
+
+### Progress Updates Not Showing
+
+**Symptoms:**
+- Research starts but no progress shown
+- UI appears stuck
+- Results appear suddenly at end
+
+**Solutions:**
+
+1. **Check browser console** for WebSocket errors
+
+2. **Verify SocketIO connection:**
+ - Open browser DevTools > Network > WS
+ - Look for `/socket.io` connections
+
+3. **Firewall/proxy issues:**
+ - WebSocket needs persistent connections
+ - Some proxies don't support WebSocket
+ - Try direct connection (no proxy)
+
+4. **Fallback to polling:**
+ - The client automatically falls back to HTTP polling
+ - Check if polling requests are working
+
+### Connection Drops
+
+**Symptoms:**
+- Frequent disconnections
+- "transport close" errors
+
+**Solutions:**
+
+1. **Check network stability**
+
+2. **Adjust timeout settings:**
+ - Default ping timeout: 20 seconds
+ - Default ping interval: 5 seconds
+
+3. **For reverse proxy setups:**
+ ```nginx
+ # Nginx example
+ location /socket.io {
+ proxy_pass http://localhost:5000;
+ proxy_http_version 1.1;
+ proxy_set_header Upgrade $http_upgrade;
+ proxy_set_header Connection "upgrade";
+ proxy_set_header Host $host;
+ proxy_read_timeout 86400;
+ }
+ ```
+
+---
+
+## Docker Issues
+
+### Container Won't Start
+
+**Symptoms:**
+- Container exits immediately
+- "exec format error"
+- Port already in use
+
+**Solutions:**
+
+1. **Check logs:**
+ ```bash
+ docker logs local-deep-research
+ ```
+
+2. **Port conflicts:**
+ ```bash
+ # Check what's using port 5000
+ lsof -i :5000
+
+ # Use different port
+ docker run -p 8080:5000 ...
+ ```
+
+3. **Architecture mismatch:**
+ - Ensure image matches your CPU architecture (amd64/arm64)
+
+### GPU Not Working
+
+**Symptoms:**
+- Ollama running on CPU instead of GPU
+- "CUDA not available"
+
+**Solutions:**
+
+1. **Use GPU-specific compose file:**
+ ```bash
+ docker compose -f docker-compose.yml -f docker-compose.gpu.override.yml up
+ ```
+
+2. **Verify NVIDIA runtime:**
+ ```bash
+ docker run --rm --gpus all nvidia/cuda:11.0-base nvidia-smi
+ ```
+
+3. **Install nvidia-container-toolkit:**
+ ```bash
+ # Ubuntu/Debian
+ sudo apt-get install -y nvidia-container-toolkit
+ sudo systemctl restart docker
+ ```
+
+### Volume/Permission Issues
+
+**Symptoms:**
+- "Permission denied" errors
+- Data not persisting
+
+**Solutions:**
+
+1. **Check volume ownership:**
+ ```bash
+ ls -la ~/.local/share/local-deep-research/
+ ```
+
+2. **Fix permissions:**
+ ```bash
+ sudo chown -R $(id -u):$(id -g) ~/.local/share/local-deep-research/
+ ```
+
+---
+
+## API Issues
+
+### CSRF Token Errors
+
+**Symptoms:**
+- "CSRF token missing"
+- "CSRF validation failed"
+
+**Solutions:**
+
+1. **Fetch token before requests:**
+ ```python
+ # Get CSRF token from server
+ resp = session.get("http://localhost:5000/auth/csrf-token")
+ csrf = resp.json()["csrf_token"]
+
+ # Include in requests
+ session.post(
+ "http://localhost:5000/api/v1/quick_summary",
+ json={"query": "..."},
+ headers={"X-CSRFToken": csrf}
+ )
+ ```
+
+2. **Use the LDRClient** which handles CSRF automatically:
+ ```python
+ from local_deep_research.api.client import LDRClient
+
+ with LDRClient() as client:
+ client.login(username, password)
+ result = client.quick_research("query")
+ ```
+
+### Authentication Failures
+
+**Symptoms:**
+- "Login required"
+- Session expires unexpectedly
+
+**Solutions:**
+
+1. **Verify credentials:**
+ - Username is case-sensitive
+ - Check for password special characters
+
+2. **Session issues:**
+ - Clear cookies and re-login
+ - Check session timeout settings
+
+3. **For API access:**
+ - Consider using API keys instead of sessions
+ - Check `api.enabled` setting
+
+---
+
+## Performance Issues
+
+### Slow Research
+
+**Symptoms:**
+- Research taking too long
+- High memory usage
+- Timeouts
+
+**Solutions:**
+
+1. **Reduce iterations:**
+ ```
+ search.iterations = 2 # Instead of default 4
+ ```
+
+2. **Reduce questions per iteration:**
+ ```
+ search.questions_per_iteration = 3 # Instead of 5
+ ```
+
+3. **Use faster strategy:**
+ ```
+ search.strategy = rapid # Instead of source-based
+ ```
+
+4. **Limit search results:**
+ ```
+ search.max_results = 5 # Instead of 10
+ ```
+
+5. **Use snippet-only mode:**
+ ```
+ search.snippets_only = true # Skip full content retrieval
+ ```
+
+### Memory Issues
+
+**Symptoms:**
+- Out of memory errors
+- System becomes unresponsive
+
+**Solutions:**
+
+1. **Limit concurrent research:**
+ - Reduce queue size
+ - Wait for research to complete before starting new ones
+
+2. **Use smaller models:**
+ - `llama3.2:3b` instead of larger variants
+ - Quantized models (Q4, Q5)
+
+3. **Increase swap space** (Linux):
+ ```bash
+ sudo fallocate -l 8G /swapfile
+ sudo chmod 600 /swapfile
+ sudo mkswap /swapfile
+ sudo swapon /swapfile
+ ```
+
+---
+
+## Getting Help
+
+If you're still experiencing issues:
+
+1. **Check logs:**
+ - Console output
+ - `~/.local/share/local-deep-research/logs/`
+
+2. **Search existing issues:**
+ - [GitHub Issues](https://github.com/LearningCircuit/local-deep-research/issues)
+
+3. **Create a new issue** with:
+ - LDR version
+ - Operating system
+ - Docker/native installation
+ - Steps to reproduce
+ - Relevant logs
+
+---
+
+## See Also
+
+- [Architecture Overview](./architecture/OVERVIEW.md) - System architecture
+- [FAQ](./faq.md) - Frequently asked questions
+- [Search Engines Guide](./search-engines.md) - Detailed engine documentation