local-deep-research 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. local_deep_research/__init__.py +24 -0
  2. local_deep_research/citation_handler.py +113 -0
  3. local_deep_research/config.py +166 -0
  4. local_deep_research/defaults/__init__.py +44 -0
  5. local_deep_research/defaults/llm_config.py +269 -0
  6. local_deep_research/defaults/local_collections.toml +47 -0
  7. local_deep_research/defaults/main.toml +57 -0
  8. local_deep_research/defaults/search_engines.toml +244 -0
  9. local_deep_research/local_collections.py +141 -0
  10. local_deep_research/main.py +113 -0
  11. local_deep_research/report_generator.py +206 -0
  12. local_deep_research/search_system.py +241 -0
  13. local_deep_research/utilties/__init__.py +0 -0
  14. local_deep_research/utilties/enums.py +9 -0
  15. local_deep_research/utilties/llm_utils.py +116 -0
  16. local_deep_research/utilties/search_utilities.py +115 -0
  17. local_deep_research/utilties/setup_utils.py +6 -0
  18. local_deep_research/web/__init__.py +2 -0
  19. local_deep_research/web/app.py +1209 -0
  20. local_deep_research/web/static/css/styles.css +1008 -0
  21. local_deep_research/web/static/js/app.js +2078 -0
  22. local_deep_research/web/templates/api_keys_config.html +82 -0
  23. local_deep_research/web/templates/collections_config.html +90 -0
  24. local_deep_research/web/templates/index.html +312 -0
  25. local_deep_research/web/templates/llm_config.html +120 -0
  26. local_deep_research/web/templates/main_config.html +89 -0
  27. local_deep_research/web/templates/search_engines_config.html +154 -0
  28. local_deep_research/web/templates/settings.html +519 -0
  29. local_deep_research/web/templates/settings_dashboard.html +207 -0
  30. local_deep_research/web_search_engines/__init__.py +0 -0
  31. local_deep_research/web_search_engines/engines/__init__.py +0 -0
  32. local_deep_research/web_search_engines/engines/full_search.py +128 -0
  33. local_deep_research/web_search_engines/engines/meta_search_engine.py +274 -0
  34. local_deep_research/web_search_engines/engines/search_engine_arxiv.py +367 -0
  35. local_deep_research/web_search_engines/engines/search_engine_brave.py +245 -0
  36. local_deep_research/web_search_engines/engines/search_engine_ddg.py +123 -0
  37. local_deep_research/web_search_engines/engines/search_engine_github.py +663 -0
  38. local_deep_research/web_search_engines/engines/search_engine_google_pse.py +283 -0
  39. local_deep_research/web_search_engines/engines/search_engine_guardian.py +337 -0
  40. local_deep_research/web_search_engines/engines/search_engine_local.py +901 -0
  41. local_deep_research/web_search_engines/engines/search_engine_local_all.py +153 -0
  42. local_deep_research/web_search_engines/engines/search_engine_medrxiv.py +623 -0
  43. local_deep_research/web_search_engines/engines/search_engine_pubmed.py +992 -0
  44. local_deep_research/web_search_engines/engines/search_engine_serpapi.py +230 -0
  45. local_deep_research/web_search_engines/engines/search_engine_wayback.py +474 -0
  46. local_deep_research/web_search_engines/engines/search_engine_wikipedia.py +242 -0
  47. local_deep_research/web_search_engines/full_search.py +254 -0
  48. local_deep_research/web_search_engines/search_engine_base.py +197 -0
  49. local_deep_research/web_search_engines/search_engine_factory.py +233 -0
  50. local_deep_research/web_search_engines/search_engines_config.py +54 -0
  51. local_deep_research-0.1.0.dist-info/LICENSE +21 -0
  52. local_deep_research-0.1.0.dist-info/METADATA +328 -0
  53. local_deep_research-0.1.0.dist-info/RECORD +56 -0
  54. local_deep_research-0.1.0.dist-info/WHEEL +5 -0
  55. local_deep_research-0.1.0.dist-info/entry_points.txt +3 -0
  56. local_deep_research-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,233 @@
1
+ import os
2
+ import importlib
3
+ import inspect
4
+ import logging
5
+ from typing import Dict, List, Any, Optional
6
+
7
+ from .search_engine_base import BaseSearchEngine
8
+ from .search_engines_config import SEARCH_ENGINES, DEFAULT_SEARCH_ENGINE
9
+
10
+ # Setup logging
11
+ logging.basicConfig(level=logging.INFO)
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ def create_search_engine(engine_name: str, llm=None, **kwargs) -> Optional[BaseSearchEngine]:
16
+ """
17
+ Create a search engine instance based on the engine name.
18
+
19
+ Args:
20
+ engine_name: Name of the search engine to create
21
+ llm: Language model instance (required for some engines like meta)
22
+ **kwargs: Additional parameters to override defaults
23
+
24
+ Returns:
25
+ Initialized search engine instance or None if creation failed
26
+ """
27
+ # If engine name not found, use default
28
+ if engine_name not in SEARCH_ENGINES:
29
+ logger.warning(f"Search engine '{engine_name}' not found, using default: {DEFAULT_SEARCH_ENGINE}")
30
+ engine_name = DEFAULT_SEARCH_ENGINE
31
+
32
+ # Get engine configuration
33
+ engine_config = SEARCH_ENGINES[engine_name]
34
+ from local_deep_research.config import settings
35
+
36
+ # Set default max_results from config if not provided in kwargs
37
+ if 'max_results' not in kwargs:
38
+ max_results = settings.search.max_results
39
+ if max_results == None: max_results=20
40
+ kwargs['max_results'] = max_results
41
+
42
+ # Check for API key requirements
43
+ if engine_config.get("requires_api_key", False):
44
+ api_key_env = engine_config.get("api_key_env")
45
+ api_key = os.getenv(api_key_env) if api_key_env else None
46
+
47
+ if not api_key:
48
+ logger.info(f"Required API key for {engine_name} not found in environment variable: {api_key_env}")
49
+ return None
50
+
51
+ # Check for LLM requirements
52
+ if engine_config.get("requires_llm", False) and not llm:
53
+ logger.info(f"Engine {engine_name} requires an LLM instance but none was provided")
54
+ return None
55
+
56
+ try:
57
+ # Load the engine class
58
+ module_path = engine_config["module_path"]
59
+ class_name = engine_config["class_name"]
60
+
61
+ module = importlib.import_module(module_path)
62
+ engine_class = getattr(module, class_name)
63
+
64
+ # Get the engine class's __init__ parameters to filter out unsupported ones
65
+ engine_init_signature = inspect.signature(engine_class.__init__)
66
+ engine_init_params = list(engine_init_signature.parameters.keys())
67
+
68
+ # Combine default parameters with provided ones
69
+ all_params = {**engine_config.get("default_params", {}), **kwargs}
70
+
71
+ # Filter out parameters that aren't accepted by the engine class
72
+ # Note: 'self' is always the first parameter of instance methods, so we skip it
73
+ filtered_params = {k: v for k, v in all_params.items() if k in engine_init_params[1:]}
74
+
75
+ # Add LLM if required
76
+ if engine_config.get("requires_llm", False):
77
+ filtered_params["llm"] = llm
78
+
79
+ # Add API key if required and not already in filtered_params
80
+ if engine_config.get("requires_api_key", False) and "api_key" not in filtered_params:
81
+ api_key_env = engine_config.get("api_key_env")
82
+ if api_key_env:
83
+ api_key = os.getenv(api_key_env)
84
+ if api_key:
85
+ filtered_params["api_key"] = api_key
86
+
87
+ logger.info(f"Creating {engine_name} with filtered parameters: {filtered_params.keys()}")
88
+
89
+ # Create the engine instance with filtered parameters
90
+ engine = engine_class(**filtered_params)
91
+
92
+ # Check if we need to wrap with full search capabilities
93
+ if kwargs.get("use_full_search", False) and engine_config.get("supports_full_search", False):
94
+ return _create_full_search_wrapper(engine_name, engine, llm, kwargs)
95
+
96
+ return engine
97
+
98
+ except Exception as e:
99
+ logger.info(f"Failed to create search engine '{engine_name}': {str(e)}")
100
+ return None
101
+
102
+
103
+ def _create_full_search_wrapper(engine_name: str, base_engine: BaseSearchEngine, llm, params: Dict[str, Any]) -> Optional[BaseSearchEngine]:
104
+ """Create a full search wrapper for the base engine if supported"""
105
+ try:
106
+ engine_config = SEARCH_ENGINES[engine_name]
107
+
108
+ # Get full search class details
109
+ module_path = engine_config.get("full_search_module")
110
+ class_name = engine_config.get("full_search_class")
111
+
112
+ if not module_path or not class_name:
113
+ logger.warning(f"Full search configuration missing for {engine_name}")
114
+ return base_engine
115
+
116
+ # Import the full search class
117
+ module = importlib.import_module(module_path)
118
+ full_search_class = getattr(module, class_name)
119
+
120
+ # Get the wrapper's __init__ parameters to filter out unsupported ones
121
+ wrapper_init_signature = inspect.signature(full_search_class.__init__)
122
+ wrapper_init_params = list(wrapper_init_signature.parameters.keys())[1:] # Skip 'self'
123
+
124
+ # Extract relevant parameters for the full search wrapper
125
+ wrapper_params = {k: v for k, v in params.items() if k in wrapper_init_params}
126
+
127
+ # Special case for SerpAPI which needs the API key directly
128
+ if engine_name == "serpapi" and "serpapi_api_key" in wrapper_init_params:
129
+ serpapi_api_key = os.getenv("SERP_API_KEY")
130
+ if serpapi_api_key:
131
+ wrapper_params["serpapi_api_key"] = serpapi_api_key
132
+
133
+ # Map some parameter names to what the wrapper expects
134
+ if "language" in params and "search_language" not in params and "language" in wrapper_init_params:
135
+ wrapper_params["language"] = params["language"]
136
+
137
+ if "safesearch" not in wrapper_params and "safe_search" in params and "safesearch" in wrapper_init_params:
138
+ wrapper_params["safesearch"] = "active" if params["safe_search"] else "off"
139
+
140
+ # Special case for Brave which needs the API key directly
141
+ if engine_name == "brave" and "api_key" in wrapper_init_params:
142
+ brave_api_key = os.getenv("BRAVE_API_KEY")
143
+ if brave_api_key:
144
+ wrapper_params["api_key"] = brave_api_key
145
+
146
+ # Map some parameter names to what the wrapper expects
147
+ if "language" in params and "search_language" not in params and "language" in wrapper_init_params:
148
+ wrapper_params["language"] = params["language"]
149
+
150
+ if "safesearch" not in wrapper_params and "safe_search" in params and "safesearch" in wrapper_init_params:
151
+ wrapper_params["safesearch"] = "moderate" if params["safe_search"] else "off"
152
+
153
+ # Always include llm if it's a parameter
154
+ if "llm" in wrapper_init_params:
155
+ wrapper_params["llm"] = llm
156
+
157
+ # If the wrapper needs the base engine and has a parameter for it
158
+ if "web_search" in wrapper_init_params:
159
+ wrapper_params["web_search"] = base_engine
160
+
161
+ logger.debug(f"Creating full search wrapper for {engine_name} with filtered parameters: {wrapper_params.keys()}")
162
+
163
+ # Create the full search wrapper with filtered parameters
164
+ full_search = full_search_class(**wrapper_params)
165
+
166
+ return full_search
167
+
168
+ except Exception as e:
169
+ logger.error(f"Failed to create full search wrapper for {engine_name}: {str(e)}")
170
+ return base_engine
171
+
172
+
173
+
174
+ def get_available_engines(include_api_key_services: bool = True):
175
+ """Get a list of available engine names"""
176
+ if include_api_key_services:
177
+ return list(SEARCH_ENGINES.keys())
178
+ else:
179
+ return [name for name, config in SEARCH_ENGINES.items()
180
+ if not config.get("requires_api_key", False)]
181
+
182
+
183
+ def get_search(search_tool: str, llm_instance,
184
+ max_results: int = 10,
185
+ region: str = "us",
186
+ time_period: str = "y",
187
+ safe_search: bool = True,
188
+ search_snippets_only: bool = False,
189
+ search_language: str = "English",
190
+ max_filtered_results: Optional[int] = None):
191
+ """
192
+ Get search tool instance based on the provided parameters.
193
+
194
+ Args:
195
+ search_tool: Name of the search engine to use
196
+ llm_instance: Language model instance
197
+ max_results: Maximum number of search results
198
+ region: Search region/locale
199
+ time_period: Time period for search results
200
+ safe_search: Whether to enable safe search
201
+ search_snippets_only: Whether to return just snippets (vs. full content)
202
+ search_language: Language for search results
203
+ max_filtered_results: Maximum number of results to keep after filtering
204
+
205
+ Returns:
206
+ Initialized search engine instance
207
+ """
208
+ # Common parameters
209
+ params = {
210
+ "max_results": max_results,
211
+ "llm": llm_instance, # Only used by engines that need it
212
+ }
213
+
214
+ # Add max_filtered_results if provided
215
+ if max_filtered_results is not None:
216
+ params["max_filtered_results"] = max_filtered_results
217
+
218
+ # Add engine-specific parameters
219
+ if search_tool in ["duckduckgo", "serpapi", "google_pse", "brave"]:
220
+ params.update({
221
+ "region": region,
222
+ "safe_search": safe_search,
223
+ "use_full_search": not search_snippets_only
224
+ })
225
+
226
+ if search_tool in ["serpapi", "brave", "google_pse"]:
227
+ params["search_language"] = search_language
228
+
229
+ if search_tool == "serpapi":
230
+ params["time_period"] = time_period
231
+
232
+ # Create and return the search engine
233
+ return create_search_engine(search_tool, **params)
@@ -0,0 +1,54 @@
1
+ """
2
+ Configuration file for search engines.
3
+ Loads search engine definitions from the user's configuration.
4
+ """
5
+ import logging
6
+ import os
7
+ import toml
8
+ from pathlib import Path
9
+ from local_deep_research.config import CONFIG_DIR
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ # Get search engines configuration directly from TOML file
14
+ SEARCH_ENGINES = {}
15
+ DEFAULT_SEARCH_ENGINE = "wikipedia" # Default fallback if not specified in config
16
+
17
+ # Path to the search engines configuration file
18
+ SEARCH_ENGINES_FILE = CONFIG_DIR / "search_engines.toml"
19
+
20
+ # Load directly from TOML file
21
+ if os.path.exists(SEARCH_ENGINES_FILE):
22
+ try:
23
+ # Load the TOML file directly
24
+ config_data = toml.load(SEARCH_ENGINES_FILE)
25
+
26
+ # Extract search engine definitions
27
+ for key, value in config_data.items():
28
+ if key == "DEFAULT_SEARCH_ENGINE":
29
+ DEFAULT_SEARCH_ENGINE = value
30
+ elif isinstance(value, dict):
31
+ SEARCH_ENGINES[key] = value
32
+
33
+ logger.info(f"Loaded {len(SEARCH_ENGINES)} search engines from configuration file")
34
+ except Exception as e:
35
+ logger.error(f"Error loading search engines from TOML file: {e}")
36
+ else:
37
+ logger.warning(f"Search engines configuration file not found: {SEARCH_ENGINES_FILE}")
38
+
39
+ # Add alias for 'auto' if it exists
40
+ if 'auto' in SEARCH_ENGINES and 'meta' not in SEARCH_ENGINES:
41
+ SEARCH_ENGINES['meta'] = SEARCH_ENGINES['auto']
42
+
43
+ # Register local document collections
44
+ try:
45
+ from local_deep_research.local_collections import register_local_collections
46
+ register_local_collections(SEARCH_ENGINES)
47
+ logger.info(f"Registered local document collections as search engines")
48
+ except ImportError:
49
+ logger.info("No local collections configuration found. Local document search is disabled.")
50
+
51
+ # Ensure the meta search engine is still available at the end if it exists
52
+ if 'auto' in SEARCH_ENGINES:
53
+ meta_config = SEARCH_ENGINES["auto"]
54
+ SEARCH_ENGINES["auto"] = meta_config
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 LearningCircuit
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,328 @@
1
+ Metadata-Version: 2.2
2
+ Name: local-deep-research
3
+ Version: 0.1.0
4
+ Summary: AI-powered research assistant with deep, iterative analysis using LLMs and web searches
5
+ Author-email: LearningCircuit <185559241+LearningCircuit@users.noreply.github.com>, HashedViking <6432677+HashedViking@users.noreply.github.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2025 LearningCircuit
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/LearningCircuit/local-deep-research
29
+ Project-URL: Bug Tracker, https://github.com/LearningCircuit/local-deep-research/issues
30
+ Classifier: Programming Language :: Python :: 3
31
+ Classifier: License :: OSI Approved :: MIT License
32
+ Classifier: Operating System :: OS Independent
33
+ Requires-Python: >=3.8
34
+ Description-Content-Type: text/markdown
35
+ License-File: LICENSE
36
+ Requires-Dist: langchain>=0.3.18
37
+ Requires-Dist: langchain-community>=0.3.17
38
+ Requires-Dist: langchain-core>=0.3.34
39
+ Requires-Dist: langchain-ollama>=0.2.3
40
+ Requires-Dist: langchain-openai>=0.3.5
41
+ Requires-Dist: langchain_anthropic>=0.3.7
42
+ Requires-Dist: duckduckgo_search>=7.3.2
43
+ Requires-Dist: python-dateutil>=2.9.0
44
+ Requires-Dist: typing_extensions>=4.12.2
45
+ Requires-Dist: justext
46
+ Requires-Dist: playwright
47
+ Requires-Dist: beautifulsoup4
48
+ Requires-Dist: flask>=2.0.1
49
+ Requires-Dist: flask-cors>=3.0.10
50
+ Requires-Dist: flask-socketio>=5.1.1
51
+ Requires-Dist: sqlalchemy>=1.4.23
52
+ Requires-Dist: wikipedia
53
+ Requires-Dist: arxiv>=1.4.3
54
+ Requires-Dist: PyPDF2>=2.0.0
55
+ Requires-Dist: sentence-transformers
56
+ Requires-Dist: faiss-cpu
57
+ Requires-Dist: pydantic>=2.0.0
58
+ Requires-Dist: pydantic-settings>=2.0.0
59
+ Requires-Dist: toml>=0.10.2
60
+ Requires-Dist: platformdirs>=3.0.0
61
+ Requires-Dist: dynaconf
62
+
63
+ # Local Deep Research
64
+
65
+ 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.
66
+
67
+ ## Features
68
+
69
+ - 🔍 **Advanced Research Capabilities**
70
+ - Automated deep research with intelligent follow-up questions
71
+ - Citation tracking and source verification
72
+ - Multi-iteration analysis for comprehensive coverage
73
+ - Full webpage content analysis (not just snippets)
74
+
75
+ - 🤖 **Flexible LLM Support**
76
+ - Local AI processing with Ollama models
77
+ - Cloud LLM support (Claude, GPT)
78
+ - Supports all Langchain models
79
+ - Configurable model selection based on needs
80
+
81
+ - 📊 **Rich Output Options**
82
+ - Detailed research findings with citations
83
+ - Comprehensive research reports
84
+ - Quick summaries for rapid insights
85
+ - Source tracking and verification
86
+
87
+ - 🔒 **Privacy-Focused**
88
+ - Runs entirely on your machine when using local models
89
+ - Configurable search settings
90
+ - Transparent data handling
91
+
92
+ - 🌐 **Enhanced Search Integration**
93
+ - **Auto-selection of search sources**: The "auto" search engine intelligently analyzes your query and selects the most appropriate search engine based on the query content
94
+ - Wikipedia integration for factual knowledge
95
+ - arXiv integration for scientific papers and academic research
96
+ - PubMed integration for biomedical literature and medical research
97
+ - DuckDuckGo integration for web searches (may experience rate limiting)
98
+ - SerpAPI integration for Google search results (requires API key)
99
+ - **Google Programmable Search Engine** integration for custom search experiences (requires API key)
100
+ - The Guardian integration for news articles and journalism (requires API key)
101
+ - **Local RAG search for private documents** - search your own documents with vector embeddings
102
+ - Full webpage content retrieval
103
+ - Source filtering and validation
104
+ - Configurable search parameters
105
+
106
+ - 📑 **Local Document Search (RAG)**
107
+ - Vector embedding-based search of your local documents
108
+ - Create custom document collections for different topics
109
+ - Privacy-preserving - your documents stay on your machine
110
+ - Intelligent chunking and retrieval
111
+ - Compatible with various document formats (PDF, text, markdown, etc.)
112
+ - Automatic integration with meta-search for unified queries
113
+
114
+ ## Example Research: Fusion Energy Developments
115
+
116
+ The repository includes complete research examples demonstrating the tool's capabilities. For instance, our [fusion energy research analysis](https://github.com/LearningCircuit/local-deep-research/blob/main/examples/fusion-energy-research-developments.md) provides a comprehensive overview of:
117
+
118
+ - Latest scientific breakthroughs in fusion research (2022-2025)
119
+ - Private sector funding developments exceeding $6 billion
120
+ - Expert projections for commercial fusion energy timelines
121
+ - Regulatory frameworks being developed for fusion deployment
122
+ - Technical challenges that must be overcome for commercial viability
123
+
124
+ This example showcases the system's ability to perform multiple research iterations, follow evidence trails across scientific and commercial domains, and synthesize information from diverse sources while maintaining proper citation.
125
+
126
+ ## Installation
127
+
128
+ 1. Clone the repository:
129
+ ```bash
130
+ git clone https://github.com/yourusername/local-deep-research.git
131
+ cd local-deep-research
132
+ ```
133
+
134
+ 2. Install dependencies:
135
+ ```bash
136
+ pip install -r requirements.txt
137
+ playwright install
138
+ ```
139
+
140
+ 3. Install Ollama (for local models):
141
+ ```bash
142
+ # Install Ollama from https://ollama.ai
143
+ ollama pull mistral # Default model - many work really well choose best for your hardware (fits in GPU)
144
+ ```
145
+
146
+ 4. Configure environment variables:
147
+ ```bash
148
+ # Copy the template
149
+ cp .env.template .env
150
+
151
+ # Edit .env with your API keys (if using cloud LLMs)
152
+ ANTHROPIC_API_KEY=your-api-key-here # For Claude
153
+ OPENAI_API_KEY=your-openai-key-here # For GPT models
154
+ GUARDIAN_API_KEY=your-guardian-api-key-here # For The Guardian search
155
+ ```
156
+
157
+ ## Usage
158
+ Terminal usage (not recommended):
159
+ ```bash
160
+ python main.py
161
+ ```
162
+
163
+ ### Web Interface
164
+
165
+ The project includes a web interface for a more user-friendly experience:
166
+
167
+ ```bash
168
+ python app.py
169
+ ```
170
+
171
+ This will start a local web server, accessible at `http://127.0.0.1:5000` in your browser.
172
+
173
+ #### Web Interface Features:
174
+
175
+ - **Dashboard**: Intuitive interface for starting and managing research queries
176
+ - **Real-time Updates**: Track research progress with live updates
177
+ - **Research History**: Access and manage past research queries
178
+ - **PDF Export**: Download completed research reports as PDF documents
179
+ - **Research Management**: Terminate ongoing research processes or delete past records
180
+
181
+ ![Web Interface](./web1.png)
182
+ ![Web Interface](./web2.png)
183
+ ### Configuration
184
+ **Please report your best settings in issues so we can improve the default settings.**
185
+
186
+ Key settings in `config.py`:
187
+ ```python
188
+ # LLM Configuration
189
+ DEFAULT_MODEL = "mistral" # Change based on your needs
190
+ DEFAULT_TEMPERATURE = 0.7
191
+ MAX_TOKENS = 8000
192
+
193
+ # Search Configuration
194
+ MAX_SEARCH_RESULTS = 40
195
+ SEARCH_REGION = "us-en"
196
+ TIME_PERIOD = "y"
197
+ SAFE_SEARCH = True
198
+ SEARCH_SNIPPETS_ONLY = False
199
+
200
+ # Choose search tool: "wiki", "arxiv", "duckduckgo", "guardian", "serp", "local_all", or "auto"
201
+ search_tool = "auto" # "auto" will intelligently select the best search engine for your query
202
+ ```
203
+
204
+ ## Local Document Search (RAG)
205
+
206
+ The system includes powerful local document search capabilities using Retrieval-Augmented Generation (RAG). This allows you to search and retrieve content from your own document collections.
207
+
208
+ ### Setting Up Local Collections
209
+
210
+ Create a file named `local_collections.py` in the project root directory:
211
+
212
+ ```python
213
+ # local_collections.py
214
+ import os
215
+ from typing import Dict, Any
216
+
217
+ # Registry of local document collections
218
+ LOCAL_COLLECTIONS = {
219
+ # Research Papers Collection
220
+ "research_papers": {
221
+ "name": "Research Papers",
222
+ "description": "Academic research papers and articles",
223
+ "paths": [os.path.abspath("local_search_files/research_papers")], # Use absolute paths
224
+ "enabled": True,
225
+ "embedding_model": "all-MiniLM-L6-v2",
226
+ "embedding_device": "cpu",
227
+ "embedding_model_type": "sentence_transformers",
228
+ "max_results": 20,
229
+ "max_filtered_results": 5,
230
+ "chunk_size": 800, # Smaller chunks for academic content
231
+ "chunk_overlap": 150,
232
+ "cache_dir": ".cache/local_search/research_papers"
233
+ },
234
+
235
+ # Personal Notes Collection
236
+ "personal_notes": {
237
+ "name": "Personal Notes",
238
+ "description": "Personal notes and documents",
239
+ "paths": [os.path.abspath("local_search_files/personal_notes")], # Use absolute paths
240
+ "enabled": True,
241
+ "embedding_model": "all-MiniLM-L6-v2",
242
+ "embedding_device": "cpu",
243
+ "embedding_model_type": "sentence_transformers",
244
+ "max_results": 30,
245
+ "max_filtered_results": 10,
246
+ "chunk_size": 500, # Smaller chunks for notes
247
+ "chunk_overlap": 100,
248
+ "cache_dir": ".cache/local_search/personal_notes"
249
+ }
250
+ }
251
+ ```
252
+
253
+ Create directories for your collections:
254
+
255
+ ```bash
256
+ mkdir -p local_search_files/research_papers
257
+ mkdir -p local_search_files/personal_notes
258
+ ```
259
+
260
+ Add your documents to these folders, and the system will automatically index them and make them available for searching.
261
+
262
+ ### Using Local Search
263
+
264
+ You can use local search in several ways:
265
+
266
+ 1. **Auto-selection**: Set `search_tool = "auto"` in `config.py` and the system will automatically use your local collections when appropriate for the query.
267
+
268
+ 2. **Explicit Selection**: Set `search_tool = "research_papers"` to search only that specific collection.
269
+
270
+ 3. **Search All Local Collections**: Set `search_tool = "local_all"` to search across all your local document collections.
271
+
272
+ 4. **Query Syntax**: Use `collection:collection_name your query` to target a specific collection within a query.
273
+
274
+ ### Search Engine Options
275
+
276
+ The system supports multiple search engines that can be selected by changing the `search_tool` variable in `config.py`:
277
+
278
+ - **Auto** (`auto`): Intelligent search engine selector that analyzes your query and chooses the most appropriate source (Wikipedia, arXiv, local collections, etc.)
279
+ - **Wikipedia** (`wiki`): Best for general knowledge, facts, and overview information
280
+ - **arXiv** (`arxiv`): Great for scientific and academic research, accessing preprints and papers
281
+ - **PubMed** (`pubmed`): Excellent for biomedical literature, medical research, and health information
282
+ - **DuckDuckGo** (`duckduckgo`): General web search that doesn't require an API key
283
+ - **The Guardian** (`guardian`): Quality journalism and news articles (requires an API key)
284
+ - **SerpAPI** (`serp`): Google search results (requires an API key)
285
+ - **Google Programmable Search Engine** (`google_pse`): Custom search experiences with control over search scope and domains (requires API key and search engine ID)
286
+ - **Local Collections**: Any collections defined in your `local_collections.py` file
287
+
288
+ > **Note:** The "auto" option will intelligently select the best search engine based on your query. For example, if you ask about physics research papers, it might select arXiv or your research_papers collection, while if you ask about current events, it might select The Guardian or DuckDuckGo.
289
+
290
+ > **Support Free Knowledge:** If you frequently use the search engines in this tool, please consider making a donation to these organizations. They provide valuable services and rely on user support to maintain their operations:
291
+ > - [Donate to Wikipedia](https://donate.wikimedia.org)
292
+ > - [Support The Guardian](https://support.theguardian.com)
293
+ > - [Support arXiv](https://arxiv.org/about/give)
294
+ > - [Donate to DuckDuckGo](https://duckduckgo.com/donations)
295
+ > - [Support PubMed/NCBI](https://www.nlm.nih.gov/pubs/donations/donations.html)
296
+
297
+ ## License
298
+
299
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
300
+
301
+ ## Acknowledgments
302
+ - Built with [Ollama](https://ollama.ai) for local AI processing
303
+ - Search powered by multiple sources:
304
+ - [Wikipedia](https://www.wikipedia.org/) for factual knowledge (default search engine)
305
+ - [arXiv](https://arxiv.org/) for scientific papers
306
+ - [PubMed](https://pubmed.ncbi.nlm.nih.gov/) for biomedical literature
307
+ - [DuckDuckGo](https://duckduckgo.com) for web search
308
+ - [The Guardian](https://www.theguardian.com/) for quality journalism
309
+ - [SerpAPI](https://serpapi.com) for Google search results (requires API key)
310
+ - Built on [LangChain](https://github.com/hwchase17/langchain) framework
311
+ - Uses [justext](https://github.com/miso-belica/justext) for content extraction
312
+ - [Playwright](https://playwright.dev) for web content retrieval
313
+ - Uses [FAISS](https://github.com/facebookresearch/faiss) for vector similarity search
314
+ - Uses [sentence-transformers](https://github.com/UKPLab/sentence-transformers) for embeddings
315
+
316
+ ## Contributing
317
+
318
+ Contributions are welcome! Please feel free to submit a Pull Request.
319
+
320
+ 1. Fork the repository
321
+ 2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
322
+ 3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
323
+ 4. Push to the branch (`git push origin feature/AmazingFeature`)
324
+ 5. Open a Pull Request
325
+
326
+ ## Star History
327
+
328
+ [![Star History Chart](https://api.star-history.com/svg?repos=LearningCircuit/local-deep-research&type=Date)](https://www.star-history.com/#LearningCircuit/local-deep-research&Date)