~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
not fully working yet
LearningCircuit965dcec84f5e
diff --git a/pyproject.toml b/pyproject.tomlindex f4c64a4456..4c8bd099d8 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -39,6 +39,11 @@ dependencies = ["PyPDF2>=2.0.0","sentence-transformers","faiss-cpu",+ "pydantic>=2.0.0",+ "pydantic-settings>=2.0.0",+ "toml>=0.10.2",+ "platformdirs>=3.0.0",+][project.urls]@@ -54,3 +59,4 @@ include-package-data = true[tool.setuptools.package-data]"local_deep_research.web" = ["templates/*", "static/*", "static/**/*"]+"local_deep_research.defaults" = ["*.toml", "*.py"]\ No newline at end of filediff --git a/src/local_deep_research/__init__.py b/src/local_deep_research/__init__.pyindex 13b93d4d87..4cc0f43cd7 100644--- a/src/local_deep_research/__init__.py+++ b/src/local_deep_research/__init__.py@@ -7,8 +7,25 @@ and multiple search engines integration.__version__ = "0.1.0"+# Initialize configuration on module import+from .utilties.setup_utils import setup_user_directories+setup_user_directories()++# Import main componentsfrom .search_system import AdvancedSearchSystemfrom .report_generator import IntegratedReportGenerator+from .model_loader import get_model, get_llm+from .config_manager import get_config+++from .config_manager import get_config, get_llm, get_search-# Expose main classes-__all__ = ["AdvancedSearchSystem", "IntegratedReportGenerator"]+# Export it+__all__ = [+ "AdvancedSearchSystem",+ "IntegratedReportGenerator",+ "get_model",+ "get_llm",+ "get_config",+ "get_search"+]\ No newline at end of filediff --git a/src/local_deep_research/config.py b/src/local_deep_research/config.pyindex e5e7acc8c2..7947a25516 100644--- a/src/local_deep_research/config.py+++ b/src/local_deep_research/config.py@@ -1,291 +1,66 @@-"""-Local Deep Research Configuration Guide--This configuration file controls the behavior of the research system.--MAIN SETTINGS:-- search_tool (str): Choose which search engine to use- - "auto": Intelligent selection based on query content (recommended)- - "local_all": Search only local document collections- - "wikipedia": General knowledge and facts- - "arxiv": Scientific papers and research- - "duckduckgo": General web search (no API key needed)- - "serp": Google search via SerpAPI (requires API key)- - "google_pse": Google Programmable Search Engine for custom search experiences (requires API key)- - "guardian": News articles (requires API key)- - Any collection name from your local_collections.py--- DEFAULT_MODEL (str): LLM to use for analysis- - "mistral": Default local model via Ollama- - "deepseek-r1:14b": Alternative larger model- - "claude-3-5-sonnet-latest": Claude model (requires API key)- - "gpt-4o": OpenAI model (requires API key)- - "mpt-7b": MPT model via VLLM-API KEYS:-For search engines requiring API keys, set these in your .env file:-- SERP_API_KEY: For Google search via SerpAPI-- GUARDIAN_API_KEY: For The Guardian news search-- GOOGLE_PSE_API_KEY: For Google Programmable Search Engine-- GOOGLE_PSE_ENGINE_ID: Search Engine ID from Google PSE Control Panel--RESEARCH SETTINGS:-- SEARCH_ITERATIONS (int): Number of research cycles-- QUESTIONS_PER_ITERATION (int): Questions per cycle-- SEARCHES_PER_SECTION (int): Searches per report section-- MAX_SEARCH_RESULTS (int): Results per search query-- MAX_FILTERED_RESULTS (int): Results after relevance filtering+"""+Legacy configuration module for backward compatibility.-For full documentation, see the README.md+This module forwards imports to the new config_manager module.+It will be deprecated in a future version."""-from langchain_anthropic import ChatAnthropic-from langchain_openai import ChatOpenAI-from langchain_ollama import ChatOllama-from langchain_community.llms import VLLM # Added VLLM import-from dotenv import load_dotenv+import logging+import warnings+from .config_manager import (+ get_llm,+ load_main_config,+ get_search+)++logger = logging.getLogger(__name__)+warnings.warn(+ "The 'config' module is deprecated. Please import from 'config_manager' instead.",+ DeprecationWarning,+ stacklevel=2+)++# Load configuration+config = load_main_config()++# Export constants from the main configuration+# These are used by various modules+SEARCH_ITERATIONS = config["search"]["iterations"]+QUESTIONS_PER_ITERATION = config["search"]["questions_per_iteration"]+SEARCHES_PER_SECTION = config["search"]["searches_per_section"]+MAX_SEARCH_RESULTS = config["search"]["max_results"]+MAX_FILTERED_RESULTS = config["search"]["max_filtered_results"]+SEARCH_REGION = config["search"]["region"]+TIME_PERIOD = config["search"]["time_period"]+SAFE_SEARCH = config["search"]["safe_search"]+SEARCH_LANGUAGE = config["search"]["search_language"]+SEARCH_SNIPPETS_ONLY = config["search"]["snippets_only"]+SKIP_RELEVANCE_FILTER = config["search"]["skip_relevance_filter"]+QUALITY_CHECK_DDG_URLS = config["search"]["quality_check_urls"]++# Get general settings+general_config = config["general"]+ENABLE_FACT_CHECKING = general_config["enable_fact_checking"]+KNOWLEDGE_ACCUMULATION_CONTEXT_LIMIT = general_config["knowledge_accumulation_context_limit"]+OUTPUT_DIR = general_config["output_dir"]++# Define knowledge accumulation approachfrom .utilties.enums import KnowledgeAccumulationApproach-import json-import os-import re-from typing import Dict, List, Any, Optional, Callable--# Load environment variables-load_dotenv()-# Choose search tool: "serp" or "duckduckgo" (serp requires API key)-search_tool = "auto" # Change this variable to switch between search tools; for only local search "local-all"--KNOWLEDGE_ACCUMULATION = KnowledgeAccumulationApproach.ITERATION # None doesnt work with detailed report. It basically means the questions are seperate on the topic.-KNOWLEDGE_ACCUMULATION_CONTEXT_LIMIT = 2000000--# LLM Configuration-OPENAIENDPOINT=False # True + URL + Model Name-OPENROUTER_BASE_URL= "https://openrouter.ai/api/v1"--DEFAULT_MODEL = "mistral" # try to use the largest model that fits into your GPU memory-DEFAULT_TEMPERATURE = 0.7-MAX_TOKENS = 30000--# VLLM Configuration-VLLM_MAX_NEW_TOKENS = 128-VLLM_TOP_K = 10-VLLM_TOP_P = 0.95-VLLM_TEMPERATURE = 0.8--# Search System Settings-SEARCH_ITERATIONS = 2-QUESTIONS_PER_ITERATION = 2--# Report settings-SEARCHES_PER_SECTION = 2-#CONTEXT_CUT_OFF = 10000--# citation handler-ENABLE_FACT_CHECKING = False # comes with pros and cons. Maybe works better with larger LLMs?--# URL Quality Check (applies to both DDG and SerpAPI)-QUALITY_CHECK_DDG_URLS = True # Keep True for better quality results.--SEARCH_SNIPPETS_ONLY = False-SKIP_RELEVANCE_FILTER = False--# Search Configuration (applies to both DDG and SerpAPI)-MAX_SEARCH_RESULTS = 50-MAX_FILTERED_RESULTS = 5-SEARCH_REGION = "us"-TIME_PERIOD = "y"-SAFE_SEARCH = True-SEARCH_LANGUAGE = "English"--# Output Configuration-OUTPUT_DIR = "research_outputs"--# Make OpenAI integration optional with lazy loading-def is_openai_available():- """Check if OpenAI is available without importing it at module level"""- try:- # Only import when checking- import os- api_key = os.environ.get("OPENAI_API_KEY")- if not api_key:- return False-- # Only try to import if we have an API key- try:- from langchain_openai import ChatOpenAI- return True- except ImportError:- return False- except:- return False--# Models map-MODELS = {- # Local models- "ollama-llama3": "Local Llama3 model (requires Ollama)",- "ollama-mixtral": "Local Mixtral model (requires Ollama)",- "ollama-mistral": "Local Mistral model (requires Ollama)",-- # API-based models- "gpt-4o": "OpenAI model (requires API key)",- "gpt-3.5-turbo": "OpenAI model (requires API key)",-}--# Available model providers-MODEL_PROVIDERS = ["local", "openai"]--def get_model(model_name: str, **kwargs):- """Get model instance based on the model name"""- # Common parameters for all models- common_params = {- "temperature": kwargs.get("temperature", 0.0),- "verbose": kwargs.get("verbose", False),- }-- # Ollama models (local)- if model_name.startswith("ollama-"):- try:- from langchain_community.llms import Ollama- base_url = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")- return Ollama(model=model_name.replace("ollama-", ""), base_url=base_url, **common_params)- except ImportError:- raise ValueError("Langchain Ollama integration not available. Please install it with: pip install langchain-community")-- # OpenAI models- elif model_name in ["gpt-4o", "gpt-3.5-turbo"]:- if not is_openai_available():- raise ValueError("OpenAI integration not available. Please install langchain-openai and set OPENAI_API_KEY environment variable.")-- api_key = os.getenv("OPENAI_API_KEY")- if not api_key:- raise ValueError("OPENAI_API_KEY not found in environment variables")- return ChatOpenAI(model=model_name, api_key=api_key, **common_params)-- else:- raise ValueError(f"Unsupported model: {model_name}")--def get_available_models() -> Dict[str, str]:- """Return available models based on installed packages and environment variables"""- available_models = {}-- # Check Ollama models- try:- import langchain_community- # Check if Ollama is running- ollama_running = False- try:- import requests- base_url = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")- requests.get(f"{base_url}/api/tags", timeout=2)- ollama_running = True- except:- pass-- if ollama_running:- for model in [k for k in MODELS.keys() if k.startswith("ollama-")]:- available_models[model] = MODELS[model]- except ImportError:- pass-- # Check OpenAI models- if is_openai_available():- for model in ["gpt-4o", "gpt-3.5-turbo"]:- available_models[model] = MODELS[model]-- return available_models--def get_llm(model_name=DEFAULT_MODEL, temperature=DEFAULT_TEMPERATURE):- """Get LLM instance - easy to switch between models"""- common_params = {- "temperature": temperature,- "max_tokens": MAX_TOKENS,- }-- if "claude" in model_name:- api_key = os.getenv("ANTHROPIC_API_KEY")- if not api_key:- raise ValueError("ANTHROPIC_API_KEY not found in environment variables")- return ChatAnthropic(- model=model_name, anthropic_api_key=api_key, **common_params- )- elif OPENAIENDPOINT:- api_key = os.getenv("OPENAI_ENDPOINT_API_KEY")- if not api_key:- raise ValueError("OPENAI_API_KEY not found in environment variables")- return ChatOpenAI(model=model_name, api_key=api_key,openai_api_base=OPENROUTER_BASE_URL, **common_params)-- elif "gpt" in model_name:- if not is_openai_available():- raise ValueError("OpenAI integration not available or API key not set. Please install langchain-openai and set OPENAI_API_KEY.")-- api_key = os.getenv("OPENAI_API_KEY")- if not api_key:- raise ValueError("OPENAI_API_KEY not found in environment variables")- return ChatOpenAI(model=model_name, api_key=api_key, **common_params)-- elif model_name == "mpt-7b":- # VLLM configuration for the MPT model- return VLLM(- model="mosaicml/mpt-7b",- trust_remote_code=True, # mandatory for hf models- max_new_tokens=VLLM_MAX_NEW_TOKENS,- top_k=VLLM_TOP_K,- top_p=VLLM_TOP_P,- temperature=VLLM_TEMPERATURE,- )-- else:- return ChatOllama(model=model_name, base_url="http://localhost:11434", **common_params)---def get_search():- """Get search tool instance based on config settings"""- # Import here to avoid circular import- from local_deep_research.web_search_engines.search_engine_factory import get_search as factory_get_search-- print(f"Creating search engine with tool: {search_tool}")- engine = factory_get_search(- search_tool=search_tool,- llm_instance=get_llm(),- max_results=MAX_SEARCH_RESULTS,- region=SEARCH_REGION,- time_period=TIME_PERIOD,- safe_search=SAFE_SEARCH,- search_snippets_only=SEARCH_SNIPPETS_ONLY,- search_language=SEARCH_LANGUAGE,- max_filtered_results=MAX_FILTERED_RESULTS- )-- if engine is None:- print(f"Failed to create search engine with tool: {search_tool}")-- return engine-USER_CONFIG_PATH = os.path.expanduser("~/.local_deep_research/config.json")--def get_config():- """Get current configuration as dictionary"""- config_dict = {}- # Get all uppercase variables (conventional config variables)- for key, value in globals().items():- if key.isupper() and not key.startswith('_'):- config_dict[key] = value- return config_dict--def save_config(config_dict):- """Save user configuration"""- os.makedirs(os.path.dirname(USER_CONFIG_PATH), exist_ok=True)- with open(USER_CONFIG_PATH, 'w') as f:- json.dump(config_dict, f, indent=2)--# Load user config at module import time-if os.path.exists(USER_CONFIG_PATH):- try:- with open(USER_CONFIG_PATH, 'r') as f:- user_config = json.load(f)- # Update globals with user settings- for key, value in user_config.items():- if key in globals() and key.isupper():- globals()[key] = value- print(f"Loaded user configuration from {USER_CONFIG_PATH}")- except Exception as e:- print(f"Error loading user config: {e}")\ No newline at end of file+KNOWLEDGE_ACCUMULATION = getattr(+ KnowledgeAccumulationApproach,+ general_config["knowledge_accumulation"],+ KnowledgeAccumulationApproach.ITERATION+)++# Get other settings from LLM config+from .config_manager import load_llm_config+llm_config = load_llm_config()+DEFAULT_MODEL = llm_config.get("DEFAULT_MODEL", "mistral")+DEFAULT_TEMPERATURE = llm_config.get("DEFAULT_TEMPERATURE", 0.7)+MAX_TOKENS = llm_config.get("MAX_TOKENS", 30000)+OPENAIENDPOINT = llm_config.get("USE_OPENAI_ENDPOINT", False)+OPENROUTER_BASE_URL = llm_config.get("OPENAI_ENDPOINT_URL", "https://openrouter.ai/api/v1")++# For backward compatibility+search_tool = config["search"]["tool"]\ No newline at end of filediff --git a/src/local_deep_research/config.py__old b/src/local_deep_research/config.py__oldnew file mode 100644index 0000000000..10eda52b44--- /dev/null+++ b/src/local_deep_research/config.py__old@@ -0,0 +1,291 @@+"""+Local Deep Research Configuration Guide++This configuration file controls the behavior of the research system.++MAIN SETTINGS:+- search_tool (str): Choose which search engine to use+ - "auto": Intelligent selection based on query content (recommended)+ - "local_all": Search only local document collections+ - "wikipedia": General knowledge and facts+ - "arxiv": Scientific papers and research+ - "duckduckgo": General web search (no API key needed)+ - "serp": Google search via SerpAPI (requires API key)+ - "google_pse": Google Programmable Search Engine for custom search experiences (requires API key)+ - "guardian": News articles (requires API key)+ - Any collection name from your local_collections.py++- DEFAULT_MODEL (str): LLM to use for analysis+ - "mistral": Default local model via Ollama+ - "deepseek-r1:14b": Alternative larger model+ - "claude-3-5-sonnet-latest": Claude model (requires API key)+ - "gpt-4o": OpenAI model (requires API key)+ - "mpt-7b": MPT model via VLLM++API KEYS:+For search engines requiring API keys, set these in your .env file:+- SERP_API_KEY: For Google search via SerpAPI+- GUARDIAN_API_KEY: For The Guardian news search+- GOOGLE_PSE_API_KEY: For Google Programmable Search Engine+- GOOGLE_PSE_ENGINE_ID: Search Engine ID from Google PSE Control Panel++RESEARCH SETTINGS:+- SEARCH_ITERATIONS (int): Number of research cycles+- QUESTIONS_PER_ITERATION (int): Questions per cycle+- SEARCHES_PER_SECTION (int): Searches per report section+- MAX_SEARCH_RESULTS (int): Results per search query+- MAX_FILTERED_RESULTS (int): Results after relevance filtering++For full documentation, see the README.md+"""++from langchain_anthropic import ChatAnthropic+from langchain_openai import ChatOpenAI+from langchain_ollama import ChatOllama+from langchain_community.llms import VLLM # Added VLLM import+from dotenv import load_dotenv+from .utilties.enums import KnowledgeAccumulationApproach+import json+import os+import re+from typing import Dict, List, Any, Optional, Callable++# Load environment variables+load_dotenv()+# Choose search tool: "serp" or "duckduckgo" (serp requires API key)+search_tool = "auto" # Change this variable to switch between search tools; for only local search "local-all"++KNOWLEDGE_ACCUMULATION = KnowledgeAccumulationApproach.ITERATION # None doesnt work with detailed report. It basically means the questions are seperate on the topic.+KNOWLEDGE_ACCUMULATION_CONTEXT_LIMIT = 2000000++# LLM Configuration+OPENAIENDPOINT=True # True + URL + Model Name+OPENROUTER_BASE_URL= "https://openrouter.ai/api/v1"++DEFAULT_MODEL = "google/gemini-2.0-flash-001" # try to use the largest model that fits into your GPU memory+DEFAULT_TEMPERATURE = 0.7+MAX_TOKENS = 30000++# VLLM Configuration+VLLM_MAX_NEW_TOKENS = 128+VLLM_TOP_K = 10+VLLM_TOP_P = 0.95+VLLM_TEMPERATURE = 0.8++# Search System Settings+SEARCH_ITERATIONS = 3+QUESTIONS_PER_ITERATION = 3++# Report settings+SEARCHES_PER_SECTION = 3+#CONTEXT_CUT_OFF = 10000++# citation handler+ENABLE_FACT_CHECKING = False # comes with pros and cons. Maybe works better with larger LLMs?++# URL Quality Check (applies to both DDG and SerpAPI)+QUALITY_CHECK_DDG_URLS = True # Keep True for better quality results.++SEARCH_SNIPPETS_ONLY = False+SKIP_RELEVANCE_FILTER = False++# Search Configuration (applies to both DDG and SerpAPI)+MAX_SEARCH_RESULTS = 50+MAX_FILTERED_RESULTS = 5+SEARCH_REGION = "us"+TIME_PERIOD = "y"+SAFE_SEARCH = True+SEARCH_LANGUAGE = "English"++# Output Configuration+OUTPUT_DIR = "research_outputs"++# Make OpenAI integration optional with lazy loading+def is_openai_available():+ """Check if OpenAI is available without importing it at module level"""+ try:+ # Only import when checking+ import os+ api_key = os.environ.get("OPENAI_API_KEY")+ if not api_key:+ return False++ # Only try to import if we have an API key+ try:+ from langchain_openai import ChatOpenAI+ return True+ except ImportError:+ return False+ except:+ return False++# Models map+MODELS = {+ # Local models+ "ollama-llama3": "Local Llama3 model (requires Ollama)",+ "ollama-mixtral": "Local Mixtral model (requires Ollama)",+ "ollama-mistral": "Local Mistral model (requires Ollama)",++ # API-based models+ "gpt-4o": "OpenAI model (requires API key)",+ "gpt-3.5-turbo": "OpenAI model (requires API key)",+}++# Available model providers+MODEL_PROVIDERS = ["local", "openai"]++def get_model(model_name: str, **kwargs):+ """Get model instance based on the model name"""+ # Common parameters for all models+ common_params = {+ "temperature": kwargs.get("temperature", 0.0),+ "verbose": kwargs.get("verbose", False),+ }++ # Ollama models (local)+ if model_name.startswith("ollama-"):+ try:+ from langchain_community.llms import Ollama+ base_url = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")+ return Ollama(model=model_name.replace("ollama-", ""), base_url=base_url, **common_params)+ except ImportError:+ raise ValueError("Langchain Ollama integration not available. Please install it with: pip install langchain-community")++ # OpenAI models+ elif model_name in ["gpt-4o", "gpt-3.5-turbo"]:+ if not is_openai_available():+ raise ValueError("OpenAI integration not available. Please install langchain-openai and set OPENAI_API_KEY environment variable.")++ api_key = os.getenv("OPENAI_API_KEY")+ if not api_key:+ raise ValueError("OPENAI_API_KEY not found in environment variables")+ return ChatOpenAI(model=model_name, api_key=api_key, **common_params)++ else:+ raise ValueError(f"Unsupported model: {model_name}")++def get_available_models() -> Dict[str, str]:+ """Return available models based on installed packages and environment variables"""+ available_models = {}++ # Check Ollama models+ try:+ import langchain_community+ # Check if Ollama is running+ ollama_running = False+ try:+ import requests+ base_url = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")+ requests.get(f"{base_url}/api/tags", timeout=2)+ ollama_running = True+ except:+ pass++ if ollama_running:+ for model in [k for k in MODELS.keys() if k.startswith("ollama-")]:+ available_models[model] = MODELS[model]+ except ImportError:+ pass++ # Check OpenAI models+ if is_openai_available():+ for model in ["gpt-4o", "gpt-3.5-turbo"]:+ available_models[model] = MODELS[model]++ return available_models++def get_llm(model_name=DEFAULT_MODEL, temperature=DEFAULT_TEMPERATURE):+ """Get LLM instance - easy to switch between models"""+ common_params = {+ "temperature": temperature,+ "max_tokens": MAX_TOKENS,+ }++ if "claude" in model_name:+ api_key = os.getenv("ANTHROPIC_API_KEY")+ if not api_key:+ raise ValueError("ANTHROPIC_API_KEY not found in environment variables")+ return ChatAnthropic(+ model=model_name, anthropic_api_key=api_key, **common_params+ )+ elif OPENAIENDPOINT:+ api_key = os.getenv("OPENAI_ENDPOINT_API_KEY")+ if not api_key:+ raise ValueError("OPENAI_API_KEY not found in environment variables")+ return ChatOpenAI(model=model_name, api_key=api_key,openai_api_base=OPENROUTER_BASE_URL, **common_params)++ elif "gpt" in model_name:+ if not is_openai_available():+ raise ValueError("OpenAI integration not available or API key not set. Please install langchain-openai and set OPENAI_API_KEY.")++ api_key = os.getenv("OPENAI_API_KEY")+ if not api_key:+ raise ValueError("OPENAI_API_KEY not found in environment variables")+ return ChatOpenAI(model=model_name, api_key=api_key, **common_params)++ elif model_name == "mpt-7b":+ # VLLM configuration for the MPT model+ return VLLM(+ model="mosaicml/mpt-7b",+ trust_remote_code=True, # mandatory for hf models+ max_new_tokens=VLLM_MAX_NEW_TOKENS,+ top_k=VLLM_TOP_K,+ top_p=VLLM_TOP_P,+ temperature=VLLM_TEMPERATURE,+ )++ else:+ return ChatOllama(model=model_name, base_url="http://localhost:11434", **common_params)+++def get_search():+ """Get search tool instance based on config settings"""+ # Import here to avoid circular import+ from local_deep_research.web_search_engines.search_engine_factory import get_search as factory_get_search++ print(f"Creating search engine with tool: {search_tool}")+ engine = factory_get_search(+ search_tool=search_tool,+ llm_instance=get_llm(),+ max_results=MAX_SEARCH_RESULTS,+ region=SEARCH_REGION,+ time_period=TIME_PERIOD,+ safe_search=SAFE_SEARCH,+ search_snippets_only=SEARCH_SNIPPETS_ONLY,+ search_language=SEARCH_LANGUAGE,+ max_filtered_results=MAX_FILTERED_RESULTS+ )++ if engine is None:+ print(f"Failed to create search engine with tool: {search_tool}")++ return engine+USER_CONFIG_PATH = os.path.expanduser("~/.local_deep_research/config.json")++def get_config():+ """Get current configuration as dictionary"""+ config_dict = {}+ # Get all uppercase variables (conventional config variables)+ for key, value in globals().items():+ if key.isupper() and not key.startswith('_'):+ config_dict[key] = value+ return config_dict++def save_config(config_dict):+ """Save user configuration"""+ os.makedirs(os.path.dirname(USER_CONFIG_PATH), exist_ok=True)+ with open(USER_CONFIG_PATH, 'w') as f:+ json.dump(config_dict, f, indent=2)++# Load user config at module import time+if os.path.exists(USER_CONFIG_PATH):+ try:+ with open(USER_CONFIG_PATH, 'r') as f:+ user_config = json.load(f)+ # Update globals with user settings+ for key, value in user_config.items():+ if key in globals() and key.isupper():+ globals()[key] = value+ print(f"Loaded user configuration from {USER_CONFIG_PATH}")+ except Exception as e:+ print(f"Error loading user config: {e}")\ No newline at end of filediff --git a/src/local_deep_research/config_manager.py b/src/local_deep_research/config_manager.pynew file mode 100644index 0000000000..0b525d8b85--- /dev/null+++ b/src/local_deep_research/config_manager.py@@ -0,0 +1,503 @@+# src/local_deep_research/config_manager.py++"""+Configuration manager for Local Deep Research.++This module handles loading and managing configuration from multiple sources:+- Default values embedded in the code+- TOML configuration files in the user's config directory+- Environment variables+- LLM configuration from the Python module++It provides a unified interface for accessing all configuration settings.+"""++import os+import sys+import json+import toml+import logging+import importlib.util+from pathlib import Path+from typing import Dict, Any, Optional, List++# Setup logging+logger = logging.getLogger(__name__)++# App metadata+APP_NAME = "local_deep_research"+APP_AUTHOR = "LearningCircuit"++# Find the appropriate config directory based on platform+def get_config_dir() -> Path:+ """Get the configuration directory based on platform standards."""+ # Use platformdirs if available+ try:+ from platformdirs import user_config_dir+ return Path(user_config_dir(APP_NAME, APP_AUTHOR))+ except ImportError:+ # Fallback implementation+ if sys.platform == "win32":+ base_dir = os.environ.get("APPDATA", os.path.expanduser("~"))+ return Path(base_dir) / APP_NAME+ elif sys.platform == "darwin":+ return Path(os.path.expanduser("~")) / "Library" / "Application Support" / APP_NAME+ else:+ # Linux and other Unix-like systems+ xdg_config_home = os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config"))+ return Path(xdg_config_home) / APP_NAME++def get_data_dir() -> Path:+ """Get the data directory based on platform standards."""+ try:+ from platformdirs import user_data_dir+ return Path(user_data_dir(APP_NAME, APP_AUTHOR))+ except ImportError:+ return get_config_dir() / "data"++def get_cache_dir() -> Path:+ """Get the cache directory based on platform standards."""+ try:+ from platformdirs import user_cache_dir+ return Path(user_cache_dir(APP_NAME, APP_AUTHOR))+ except ImportError:+ return get_config_dir() / "cache"++# Define main configuration file paths+CONFIG_DIR = get_config_dir() / "config"+MAIN_CONFIG_FILE = CONFIG_DIR / "main.toml"+LOCAL_COLLECTIONS_FILE = CONFIG_DIR / "local_collections.toml"+LLM_CONFIG_FILE = CONFIG_DIR / "llm_config.py"++# Default main configuration+DEFAULT_MAIN_CONFIG = {+ "general": {+ "output_dir": "research_outputs",+ "knowledge_accumulation": "ITERATION",+ "knowledge_accumulation_context_limit": 2000000,+ "enable_fact_checking": False+ },+ "search": {+ "tool": "auto",+ "iterations": 3,+ "questions_per_iteration": 3,+ "searches_per_section": 3,+ "max_results": 50,+ "max_filtered_results": 5,+ "region": "us",+ "time_period": "y",+ "safe_search": True,+ "search_language": "English",+ "snippets_only": False,+ "skip_relevance_filter": False,+ "quality_check_urls": True+ }+}++# Default local collections configuration+DEFAULT_LOCAL_COLLECTIONS = {+ "project_docs": {+ "name": "Project Documents",+ "description": "Project documentation and specifications",+ "paths": [str(get_data_dir() / "documents" / "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": str(get_cache_dir() / "local_search" / "project_docs")+ },+ "research_papers": {+ "name": "Research Papers",+ "description": "Academic research papers and articles",+ "paths": [str(get_data_dir() / "documents" / "research_papers")],+ "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": 800,+ "chunk_overlap": 150,+ "cache_dir": str(get_cache_dir() / "local_search" / "research_papers")+ },+ "personal_notes": {+ "name": "Personal Notes",+ "description": "Personal notes and documents",+ "paths": [str(get_data_dir() / "documents" / "personal_notes")],+ "enabled": True,+ "embedding_model": "all-MiniLM-L6-v2",+ "embedding_device": "cpu",+ "embedding_model_type": "sentence_transformers",+ "max_results": 30,+ "max_filtered_results": 10,+ "chunk_size": 500,+ "chunk_overlap": 100,+ "cache_dir": str(get_cache_dir() / "local_search" / "personal_notes")+ }+}++# Cache for loaded configurations+_config_cache = {+ "main": None,+ "local_collections": None,+ "llm": None+}++def _create_default_configs():+ """Create default configuration files if they don't exist."""+ # Create config directory+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)++ # Main config+ if not MAIN_CONFIG_FILE.exists():+ with open(MAIN_CONFIG_FILE, "w") as f:+ toml.dump(DEFAULT_MAIN_CONFIG, f)+ logger.info(f"Created default main configuration at {MAIN_CONFIG_FILE}")++ # Local collections config+ if not LOCAL_COLLECTIONS_FILE.exists():+ with open(LOCAL_COLLECTIONS_FILE, "w") as f:+ toml.dump(DEFAULT_LOCAL_COLLECTIONS, f)+ logger.info(f"Created default local collections configuration at {LOCAL_COLLECTIONS_FILE}")++ # Create LLM config if needed+ if not LLM_CONFIG_FILE.exists():+ # Try to copy from package resources+ try:+ import importlib.resources+ with importlib.resources.path('local_deep_research.defaults', 'llm_config.py') as default_llm:+ import shutil+ shutil.copy(default_llm, LLM_CONFIG_FILE)+ logger.info(f"Copied default LLM configuration from package to {LLM_CONFIG_FILE}")+ except (ImportError, FileNotFoundError) as e:+ logger.warning(f"Could not copy default LLM config from package: {e}")++ # Create a simple default+ default_content = """# Default LLM configuration+DEFAULT_MODEL = "mistral"+DEFAULT_MODEL_TYPE = "ollama"+DEFAULT_TEMPERATURE = 0.7+MAX_TOKENS = 30000++# OpenAI Endpoint configuration+USE_OPENAI_ENDPOINT = True+OPENAI_ENDPOINT_URL = "https://openrouter.ai/api/v1"+OPENAI_ENDPOINT_REQUIRES_MODEL = True++from langchain_anthropic import ChatAnthropic+from langchain_openai import ChatOpenAI+from langchain_ollama import ChatOllama+from langchain_community.llms import VLLM, Ollama+import os+import logging++def get_llm(model_name=None, model_type=None, temperature=None, **kwargs):+ '''Get LLM instance based on model name and type.'''+ # Use defaults if not specified+ if model_name is None:+ model_name = DEFAULT_MODEL+ if model_type is None:+ model_type = DEFAULT_MODEL_TYPE+ if temperature is None:+ temperature = DEFAULT_TEMPERATURE++ # Common parameters+ common_params = {+ "temperature": temperature,+ "max_tokens": kwargs.get("max_tokens", MAX_TOKENS),+ }+ common_params.update(kwargs)++ # Simple pattern matching for model types+ if model_type == "ollama":+ from langchain_ollama import ChatOllama+ return ChatOllama(model=model_name, **common_params)+ elif model_type == "openai":+ from langchain_openai import ChatOpenAI+ return ChatOpenAI(model=model_name, **common_params)+ else:+ # Default to Ollama+ from langchain_ollama import ChatOllama+ return ChatOllama(model=model_name, **common_params)+"""+ with open(LLM_CONFIG_FILE, "w") as f:+ f.write(default_content)+ logger.info(f"Created simple default LLM configuration at {LLM_CONFIG_FILE}")++ # Create document directories+ for collection in DEFAULT_LOCAL_COLLECTIONS.values():+ for path in collection["paths"]:+ Path(path).mkdir(parents=True, exist_ok=True)++def load_main_config(reload: bool = False) -> Dict[str, Any]:+ """Load main configuration from file."""+ if _config_cache["main"] is not None and not reload:+ return _config_cache["main"]++ # Create default if needed+ if not MAIN_CONFIG_FILE.exists():+ with open(MAIN_CONFIG_FILE, "w") as f:+ toml.dump(DEFAULT_MAIN_CONFIG, f)+ logger.info(f"Created default main configuration at {MAIN_CONFIG_FILE}")++ try:+ # Load from TOML file+ config = toml.load(MAIN_CONFIG_FILE)++ # Apply environment variable overrides+ _apply_env_var_overrides(config)++ # Cache the result+ _config_cache["main"] = config++ return config+ except Exception as e:+ logger.error(f"Error loading main config: {e}")+ return DEFAULT_MAIN_CONFIG.copy()++def load_local_collections(reload: bool = False) -> Dict[str, Dict[str, Any]]:+ """Load local collections configuration from file."""+ if _config_cache["local_collections"] is not None and not reload:+ return _config_cache["local_collections"]++ # Create default if needed+ if not LOCAL_COLLECTIONS_FILE.exists():+ with open(LOCAL_COLLECTIONS_FILE, "w") as f:+ toml.dump(DEFAULT_LOCAL_COLLECTIONS, f)+ logger.info(f"Created default local collections configuration at {LOCAL_COLLECTIONS_FILE}")++ try:+ # Load from TOML file+ collections = toml.load(LOCAL_COLLECTIONS_FILE)++ # Create document directories+ for collection in collections.values():+ for path in collection.get("paths", []):+ Path(path).mkdir(parents=True, exist_ok=True)++ # Cache the result+ _config_cache["local_collections"] = collections++ return collections+ except Exception as e:+ logger.error(f"Error loading local collections config: {e}")+ return DEFAULT_LOCAL_COLLECTIONS.copy()++def load_llm_config(reload: bool = False) -> Dict[str, Any]:+ """Load LLM configuration by importing the Python module."""+ if _config_cache["llm"] is not None and not reload:+ return _config_cache["llm"]++ try:+ # Add config directory to path if needed+ if str(CONFIG_DIR) not in sys.path:+ sys.path.insert(0, str(CONFIG_DIR))++ # Create default if needed+ if not LLM_CONFIG_FILE.exists():+ _create_default_configs()++ # Import the module+ spec = importlib.util.spec_from_file_location("llm_config", LLM_CONFIG_FILE)+ llm_config = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(llm_config)++ # Extract configuration as dictionary+ config = {}+ for key in dir(llm_config):+ if key.isupper() and not key.startswith("_"):+ config[key] = getattr(llm_config, key)++ # Add the get_llm function+ config["get_llm"] = getattr(llm_config, "get_llm", None)++ # Cache the result+ _config_cache["llm"] = config++ return config+ except Exception as e:+ logger.error(f"Error loading LLM config: {e}")++ # Return minimal default config+ return {+ "DEFAULT_MODEL": "mistral",+ "DEFAULT_MODEL_TYPE": "ollama",+ "DEFAULT_TEMPERATURE": 0.7,+ "MAX_TOKENS": 30000,+ "USE_OPENAI_ENDPOINT": True,+ "get_llm": None+ }++def _apply_env_var_overrides(config: Dict[str, Any]) -> None:+ """Apply environment variable overrides to configuration."""+ prefix = "LDR_"+ for env_name, env_value in os.environ.items():+ if env_name.startswith(prefix):+ # Remove prefix and convert to lowercase+ key = env_name[len(prefix):].lower()++ # Handle nested keys with double underscore separator+ if "__" in key:+ parts = key.split("__")+ curr = config+ for part in parts[:-1]:+ if part not in curr:+ curr[part] = {}+ curr = curr[part]++ # Set the value with type conversion+ try:+ # Try to infer the right type+ if env_value.lower() in ("true", "yes", "1"):+ curr[parts[-1]] = True+ elif env_value.lower() in ("false", "no", "0"):+ curr[parts[-1]] = False+ elif env_value.isdigit():+ curr[parts[-1]] = int(env_value)+ elif env_value.replace(".", "", 1).isdigit():+ curr[parts[-1]] = float(env_value)+ else:+ curr[parts[-1]] = env_value+ except Exception as e:+ logger.warning(f"Error setting config value from environment: {e}")+ else:+ # Handle top-level keys+ # Find section containing this key+ for section in config.values():+ if isinstance(section, dict) and key in section:+ try:+ # Try to convert to the right type+ orig_value = section[key]+ if isinstance(orig_value, bool):+ section[key] = env_value.lower() in ("true", "yes", "1")+ elif isinstance(orig_value, int):+ section[key] = int(env_value)+ elif isinstance(orig_value, float):+ section[key] = float(env_value)+ else:+ section[key] = env_value+ except Exception as e:+ logger.warning(f"Error converting environment variable: {e}")++def save_main_config(config: Dict[str, Any]) -> None:+ """Save main configuration to file."""+ try:+ # Ensure directory exists+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)++ # Write to file+ with open(MAIN_CONFIG_FILE, "w") as f:+ toml.dump(config, f)++ # Update cache+ _config_cache["main"] = config++ logger.info(f"Saved main configuration to {MAIN_CONFIG_FILE}")+ except Exception as e:+ logger.error(f"Error saving main config: {e}")++def save_local_collections(collections: Dict[str, Dict[str, Any]]) -> None:+ """Save local collections configuration to file."""+ try:+ # Ensure directory exists+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)++ # Write to file+ with open(LOCAL_COLLECTIONS_FILE, "w") as f:+ toml.dump(collections, f)++ # Update cache+ _config_cache["local_collections"] = collections++ # Create document directories+ for collection in collections.values():+ for path in collection.get("paths", []):+ Path(path).mkdir(parents=True, exist_ok=True)++ logger.info(f"Saved local collections configuration to {LOCAL_COLLECTIONS_FILE}")+ except Exception as e:+ logger.error(f"Error saving local collections config: {e}")++def get_config() -> Dict[str, Any]:+ """Get combined configuration."""+ return {+ "main": load_main_config(),+ "local_collections": load_local_collections(),+ "llm": load_llm_config()+ }++def get_llm(*args, **kwargs):+ """Get LLM instance from llm_config module."""+ llm_config = load_llm_config()+ get_llm_func = llm_config.get("get_llm")++ if get_llm_func is None:+ # Fall back to utility function+ from .utils.llm_utils import get_model+ return get_model(*args, **kwargs)++ return get_llm_func(*args, **kwargs)++def get_search(search_tool=None):+ """+ Get search tool instance based on configuration settings.++ This is a compatibility wrapper for the old config.get_search function.++ Args:+ search_tool: Override the search tool from configuration++ Returns:+ Search engine instance+ """+ # Load configuration+ config = load_main_config()++ # Use specified search tool or default from config+ search_tool = search_tool or config["search"]["tool"]++ # Import here to avoid circular import+ from .web_search_engines.search_engine_factory import get_search as factory_get_search++ # Get the LLM instance for search+ llm_instance = get_llm()++ # Get search parameters from config+ params = {+ "search_tool": search_tool,+ "llm_instance": llm_instance,+ "max_results": config["search"]["max_results"],+ "region": config["search"]["region"],+ "time_period": config["search"]["time_period"],+ "safe_search": config["search"]["safe_search"],+ "search_snippets_only": config["search"]["snippets_only"],+ "search_language": config["search"]["search_language"],+ "max_filtered_results": config["search"]["max_filtered_results"]+ }++ # Create search engine+ engine = factory_get_search(**params)++ if engine is None:+ logger.error(f"Failed to create search engine with tool: {search_tool}")++ return engine++# Initialize configuration files if they don't exist+_create_default_configs()++# Add at the end of config_manager.py+__all__ = [+ "get_config",+ "get_llm",+ "load_main_config",+ "load_local_collections",+ "load_llm_config",+ "save_main_config",+ "save_local_collections",+ "get_search"+]\ No newline at end of filediff --git a/src/local_deep_research/defaults/__init__.py b/src/local_deep_research/defaults/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/src/local_deep_research/defaults/llm_config.py b/src/local_deep_research/defaults/llm_config.pynew file mode 100644index 0000000000..1fbc404e69--- /dev/null+++ b/src/local_deep_research/defaults/llm_config.py@@ -0,0 +1,282 @@+"""+LLM configuration for Local Deep Research.++This file controls which language models are available and how they're configured.+You can customize model selection, parameters, and fallbacks here.++** This file is intentionally kept as Python code (not TOML) for maximum flexibility **+** You can define custom functions, conditionals, and dynamic model selection here **+"""++from langchain_anthropic import ChatAnthropic+from langchain_openai import ChatOpenAI+from langchain_ollama import ChatOllama+from langchain_community.llms import VLLM, Ollama+from dotenv import load_dotenv+import os+import logging++# Initialize environment+load_dotenv()+logger = logging.getLogger(__name__)++# Main LLM settings+DEFAULT_MODEL = "mistral" # Your default model+DEFAULT_MODEL_TYPE = "ollama" # Type of the default model: "openai", "anthropic", "ollama", "openai_endpoint", "vllm"+DEFAULT_TEMPERATURE = 0.7+MAX_TOKENS = 30000++# OpenAI Endpoint configuration (for OpenRouter, llama.cpp server, etc.)+USE_OPENAI_ENDPOINT = True+OPENAI_ENDPOINT_URL = "https://openrouter.ai/api/v1"+OPENAI_ENDPOINT_REQUIRES_MODEL = True # Set to False for llama.cpp server or others that don't need a model name++def is_openai_available():+ """Check if OpenAI is available"""+ try:+ api_key = os.environ.get("OPENAI_API_KEY")+ return bool(api_key)+ except:+ return False++def is_anthropic_available():+ """Check if Anthropic is available"""+ try:+ api_key = os.environ.get("ANTHROPIC_API_KEY")+ return bool(api_key)+ except:+ return False++def is_openai_endpoint_available():+ """Check if OpenAI endpoint is available"""+ try:+ api_key = os.environ.get("OPENAI_ENDPOINT_API_KEY")+ return bool(api_key) and USE_OPENAI_ENDPOINT+ except:+ return False++def is_ollama_available():+ """Check if Ollama is running"""+ try:+ import requests+ base_url = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")+ response = requests.get(f"{base_url}/api/tags", timeout=1.0)+ return response.status_code == 200+ except:+ return False++def get_available_provider_types():+ """Return available model providers"""+ providers = {}++ if is_ollama_available():+ providers["ollama"] = "Ollama (local models)"++ if is_openai_available():+ providers["openai"] = "OpenAI API"++ if is_anthropic_available():+ providers["anthropic"] = "Anthropic API"++ if is_openai_endpoint_available():+ providers["openai_endpoint"] = "OpenAI-compatible Endpoint"++ # Check for VLLM capability+ try:+ import torch+ import transformers+ providers["vllm"] = "VLLM (local models)"+ except ImportError:+ pass++ # Default fallback+ if not providers:+ providers["none"] = "No model providers available"++ return providers++def get_llm(model_name=None, model_type=None, temperature=None, **kwargs):+ """+ Get LLM instance based on model name and type.++ This function allows full flexibility in choosing models by specifying both+ the model name and the type/provider to use.++ Examples:+ # Use default model+ llm = get_llm()++ # Specify model name but use default type+ llm = get_llm(model_name="mistral")++ # Specify both model name and type+ llm = get_llm(model_name="gpt-4", model_type="openai")+ llm = get_llm(model_name="claude-3-opus", model_type="anthropic")+ llm = get_llm(model_name="mistral", model_type="ollama")+ llm = get_llm(model_name="llama-3-70b-instruct", model_type="openai_endpoint")++ # Use llama.cpp server without model name+ llm = get_llm(model_type="openai_endpoint")++ Args:+ model_name: Name of the model to use (if None, uses DEFAULT_MODEL)+ model_type: Type of the model (if None, uses DEFAULT_MODEL_TYPE)+ temperature: Model temperature (if None, uses DEFAULT_TEMPERATURE)+ **kwargs: Additional model parameters++ Returns:+ A LangChain LLM instance+ """+ # Use defaults if parameters are None+ if model_name is None:+ model_name = DEFAULT_MODEL++ if model_type is None:+ model_type = DEFAULT_MODEL_TYPE++ if temperature is None:+ temperature = DEFAULT_TEMPERATURE++ # Common parameters for all models+ common_params = {+ "temperature": temperature,+ "max_tokens": kwargs.get("max_tokens", MAX_TOKENS),+ }++ # Add any additional kwargs+ common_params.update(kwargs)++ # Validate model type+ valid_types = ["openai", "anthropic", "ollama", "openrouter", "vllm"]+ if model_type.lower() not in valid_types:+ logger.warning(f"Unknown model type: {model_type}. Valid types are: {', '.join(valid_types)}")+ model_type = DEFAULT_MODEL_TYPE++ model_type = model_type.lower()++ # Try to load the model based on specified type+ try:+ # Anthropic/Claude models+ if model_type == "anthropic":+ api_key = os.getenv("ANTHROPIC_API_KEY")+ if not api_key:+ logger.warning("ANTHROPIC_API_KEY not found. Falling back to default model.")+ return get_llm(DEFAULT_MODEL, DEFAULT_MODEL_TYPE, temperature, **kwargs)++ return ChatAnthropic(+ model=model_name, anthropic_api_key=api_key, **common_params+ )++ # OpenAI Endpoint (OpenRouter, llama.cpp server, local API servers, etc.)+ elif model_type == "openai_endpoint":+ if not USE_OPENAI_ENDPOINT:+ logger.warning("OpenAI endpoint is disabled. Falling back to default model.")+ return get_llm(DEFAULT_MODEL, DEFAULT_MODEL_TYPE, temperature, **kwargs)++ api_key = os.getenv("OPENAI_ENDPOINT_API_KEY")+ if not api_key:+ logger.warning("OPENAI_ENDPOINT_API_KEY not found. Falling back to default model.")+ return get_llm(DEFAULT_MODEL, DEFAULT_MODEL_TYPE, temperature, **kwargs)++ # Handle cases where model name is not needed (like llama.cpp)+ if model_name is None and not OPENAI_ENDPOINT_REQUIRES_MODEL:+ return ChatOpenAI(+ api_key=api_key,+ openai_api_base=OPENAI_ENDPOINT_URL,+ **common_params+ )+ else:+ return ChatOpenAI(+ model=model_name,+ api_key=api_key,+ openai_api_base=OPENAI_ENDPOINT_URL,+ **common_params+ )++ # OpenAI models+ elif model_type == "openai":+ api_key = os.getenv("OPENAI_API_KEY")+ if not api_key:+ logger.warning("OPENAI_API_KEY not found. Falling back to default model.")+ return get_llm(DEFAULT_MODEL, DEFAULT_MODEL_TYPE, temperature, **kwargs)++ return ChatOpenAI(model=model_name, api_key=api_key, **common_params)++ # VLLM models+ elif model_type == "vllm":+ try:+ # Pass all parameters to VLLM via common_params+ return VLLM(+ model=model_name,+ trust_remote_code=True,+ **common_params+ )+ except Exception as e:+ logger.error(f"Error loading VLLM model: {e}")+ logger.warning("Falling back to default model.")+ return get_llm(DEFAULT_MODEL, DEFAULT_MODEL_TYPE, temperature, **kwargs)++ # Ollama models+ elif model_type == "ollama":+ base_url = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")++ # First try ChatOllama from langchain_ollama+ try:+ return ChatOllama(model=model_name, base_url=base_url, **common_params)+ except (ImportError, Exception) as e:+ logger.debug(f"ChatOllama not available: {e}")++ # Fall back to Ollama from langchain_community+ try:+ return Ollama(model=model_name, base_url=base_url, **common_params)+ except Exception as e2:+ logger.error(f"Error loading Ollama model: {e2}")++ # If both attempts fail, try a fallback model+ return get_fallback_model(temperature, **kwargs)++ # Unknown model type+ else:+ logger.error(f"Unknown model type: {model_type}")+ return get_fallback_model(temperature, **kwargs)++ except Exception as e:+ logger.error(f"Error loading model {model_name} with type {model_type}: {e}")+ return get_fallback_model(temperature, **kwargs)++def get_fallback_model(temperature=DEFAULT_TEMPERATURE, **kwargs):+ """Find a suitable fallback model if requested model is unavailable"""+ providers = get_available_provider_types()++ # Try Ollama first if available+ if "ollama" in providers:+ try:+ return get_llm("mistral", "ollama", temperature, **kwargs)+ except:+ pass++ # Try OpenAI if available+ if "openai" in providers:+ try:+ return get_llm("gpt-3.5-turbo", "openai", temperature, **kwargs)+ except:+ pass++ # Try Anthropic if available+ if "anthropic" in providers:+ try:+ return get_llm("claude-instant-1.2", "anthropic", temperature, **kwargs)+ except:+ pass++ # Last resort: Create a dummy model that just returns fixed responses+ try:+ from langchain_community.llms.fake import FakeListLLM+ return FakeListLLM(+ responses=["No language models are available. Please install Ollama or set up API keys."]+ )+ except:+ # If even that fails, raise a clear error+ raise ValueError(+ "No language models are available. Please install Ollama or set up API keys."+ )\ No newline at end of filediff --git a/src/local_deep_research/defaults/main.toml b/src/local_deep_research/defaults/main.tomlnew file mode 100644index 0000000000..6b39b367ff--- /dev/null+++ b/src/local_deep_research/defaults/main.toml@@ -0,0 +1,57 @@++# Main configuration for Local Deep Research++[general]+# Directory for research outputs (relative to user data directory)+output_dir = "research_outputs"++# Knowledge accumulation approach (NONE, QUESTION, or ITERATION)+knowledge_accumulation = "ITERATION"++# Maximum context size for knowledge accumulation+knowledge_accumulation_context_limit = 2000000++# Enable fact checking (experimental, works better with large LLMs)+enable_fact_checking = false++[search]+# Search tool to use (auto, wikipedia, arxiv, duckduckgo, serp, google_pse, etc.)+# "auto" intelligently selects based on query content (recommended)+# "local_all" searches only local document collections+tool = "auto"++# Number of research cycles+iterations = 3++# Questions generated per cycle+questions_per_iteration = 3++# Searches per report section+searches_per_section = 3++# Results per search query+max_results = 50++# Results after relevance filtering+max_filtered_results = 5++# Search region+region = "us"++# Time period (d=day, w=week, m=month, y=year)+time_period = "y"++# Enable safe search+safe_search = true++# Search language+search_language = "English"++# Return only snippets, not full content (faster but less detailed)+snippets_only = false++# Skip relevance filtering (return all results)+skip_relevance_filter = false++# Check URL quality+quality_check_urls = true\ No newline at end of filediff --git a/src/local_deep_research/main.py b/src/local_deep_research/main.pyindex cde22ded9b..914eae92c5 100644--- a/src/local_deep_research/main.py+++ b/src/local_deep_research/main.py@@ -33,6 +33,20 @@ report_generator = IntegratedReportGenerator()def main():+ import os+ import logging+ from .utilties.setup_utils import setup_user_directories++ # Configure logging+ logging.basicConfig(level=logging.INFO)+ logger = logging.getLogger(__name__)++ # Explicitly run setup+ logger.info("Initializing configuration...")+ setup_user_directories()+++system = AdvancedSearchSystem()print("Welcome to the Advanced Research System")diff --git a/src/local_deep_research/model_loader.py b/src/local_deep_research/model_loader.pynew file mode 100644index 0000000000..ffdb4f9172--- /dev/null+++ b/src/local_deep_research/model_loader.py@@ -0,0 +1,67 @@+# model_loader.py+"""+Model loader for Local Deep Research.++This module provides backward compatibility with the existing code+while leveraging the new configuration system.+"""++import logging+from typing import Any, Optional++logger = logging.getLogger(__name__)++def get_model(model_name: Optional[str] = None, model_type: Optional[str] = None, **kwargs) -> Any:+ """+ Load a language model based on name, type and parameters.++ Args:+ model_name: Name of the model to use+ model_type: Type of model provider to use+ **kwargs: Additional parameters like temperature, max_tokens, etc.++ Returns:+ A LangChain language model instance+ """+ from .config_manager import get_llm+ return get_llm(model_name=model_name, model_type=model_type, **kwargs)++def get_llm(model_name=None, temperature=None, **kwargs):+ """+ Legacy function for backward compatibility.++ This maintains compatibility with the old config.get_llm function+ but uses the new configuration system.++ Args:+ model_name: Name of the model to use+ temperature: Model temperature+ **kwargs: Additional parameters++ Returns:+ A LangChain language model instance+ """+ from .config_manager import get_llm as config_get_llm, load_llm_config++ # Load configuration for defaults+ llm_config = load_llm_config()++ # If model_type not explicitly provided, derive it from model name+ # for backward compatibility with old behavior+ if 'model_type' not in kwargs:+ # Default model type based on configuration+ model_type = llm_config.get('DEFAULT_MODEL_TYPE', 'ollama')++ # Override based on model name patterns (for backward compatibility)+ if model_name and "claude" in model_name.lower():+ model_type = "anthropic"+ elif model_name and "gpt" in model_name.lower():+ model_type = "openai"++ kwargs['model_type'] = model_type++ return config_get_llm(+ model_name=model_name,+ temperature=temperature,+ **kwargs+ )\ No newline at end of filediff --git a/src/local_deep_research/utilties/llm_utils.py b/src/local_deep_research/utilties/llm_utils.pynew file mode 100644index 0000000000..397c7c02cd--- /dev/null+++ b/src/local_deep_research/utilties/llm_utils.py@@ -0,0 +1,116 @@+# utilties/llm_utils.py+"""+LLM utilities for Local Deep Research.++This module provides utility functions for working with language models+when the user's llm_config.py is missing or incomplete.+"""++import os+import logging+from typing import Dict, Any, Optional++# Setup logging+logger = logging.getLogger(__name__)++def get_model(+ model_name: Optional[str] = None,+ model_type: Optional[str] = None,+ temperature: Optional[float] = None,+ **kwargs+) -> Any:+ """+ Get a language model instance as fallback when llm_config.get_llm is not available.++ Args:+ model_name: Name of the model to use+ model_type: Type of the model provider+ temperature: Model temperature+ **kwargs: Additional parameters++ Returns:+ LangChain language model instance+ """+ # Get default values from kwargs or use reasonable defaults+ model_name = model_name or kwargs.get('DEFAULT_MODEL', 'mistral')+ model_type = model_type or kwargs.get('DEFAULT_MODEL_TYPE', 'ollama')+ temperature = temperature or kwargs.get('DEFAULT_TEMPERATURE', 0.7)+ max_tokens = kwargs.get('max_tokens', kwargs.get('MAX_TOKENS', 30000))++ # Common parameters+ common_params = {+ "temperature": temperature,+ "max_tokens": max_tokens,+ }++ # Add additional kwargs+ for key, value in kwargs.items():+ if key not in ['DEFAULT_MODEL', 'DEFAULT_MODEL_TYPE', 'DEFAULT_TEMPERATURE', 'MAX_TOKENS']:+ common_params[key] = value++ # Try to load the model based on type+ if model_type == "ollama":+ try:+ from langchain_ollama import ChatOllama+ return ChatOllama(model=model_name, **common_params)+ except ImportError:+ try:+ from langchain_community.llms import Ollama+ return Ollama(model=model_name, **common_params)+ except ImportError:+ logger.error("Neither langchain_ollama nor langchain_community.llms.Ollama available")+ raise++ elif model_type == "openai":+ try:+ from langchain_openai import ChatOpenAI+ api_key = os.getenv("OPENAI_API_KEY")+ if not api_key:+ raise ValueError("OPENAI_API_KEY environment variable not set")+ return ChatOpenAI(model=model_name, api_key=api_key, **common_params)+ except ImportError:+ logger.error("langchain_openai not available")+ raise++ elif model_type == "anthropic":+ try:+ from langchain_anthropic import ChatAnthropic+ api_key = os.getenv("ANTHROPIC_API_KEY")+ if not api_key:+ raise ValueError("ANTHROPIC_API_KEY environment variable not set")+ return ChatAnthropic(model=model_name, anthropic_api_key=api_key, **common_params)+ except ImportError:+ logger.error("langchain_anthropic not available")+ raise++ elif model_type == "openai_endpoint":+ try:+ from langchain_openai import ChatOpenAI+ api_key = os.getenv("OPENAI_ENDPOINT_API_KEY")+ if not api_key:+ raise ValueError("OPENAI_ENDPOINT_API_KEY environment variable not set")++ endpoint_url = kwargs.get("OPENAI_ENDPOINT_URL", "https://openrouter.ai/api/v1")++ if model_name is None and not kwargs.get("OPENAI_ENDPOINT_REQUIRES_MODEL", True):+ return ChatOpenAI(api_key=api_key, openai_api_base=endpoint_url, **common_params)+ else:+ return ChatOpenAI(model=model_name, api_key=api_key, openai_api_base=endpoint_url, **common_params)+ except ImportError:+ logger.error("langchain_openai not available")+ raise++ # Default fallback+ try:+ from langchain_ollama import ChatOllama+ logger.warning(f"Unknown model type '{model_type}', defaulting to Ollama")+ return ChatOllama(model=model_name, **common_params)+ except (ImportError, Exception) as e:+ logger.error(f"Failed to load any model: {e}")++ # Last resort: create a dummy model+ try:+ from langchain_community.llms.fake import FakeListLLM+ return FakeListLLM(responses=["No language models are available. Please install Ollama or set up API keys."])+ except ImportError:+ raise ValueError("No language models available and could not create dummy model")\ No newline at end of filediff --git a/src/local_deep_research/utilties/setup_utils.py b/src/local_deep_research/utilties/setup_utils.pynew file mode 100644index 0000000000..377a748cc8--- /dev/null+++ b/src/local_deep_research/utilties/setup_utils.py@@ -0,0 +1,210 @@+# utilties/setup_utils.py+"""+Setup utilities for Local Deep Research.++This module handles initial setup of configuration and directories.+"""++import os+import logging+import shutil+from pathlib import Path+import toml++logger = logging.getLogger(__name__)+++def setup_user_directories():+ """Create the necessary directories and configuration files."""+ import os+ import logging+ from pathlib import Path++ logger = logging.getLogger(__name__)+ logger.info("Setting up user directories and configuration...")++ # Import configuration paths+ from ..config_manager import CONFIG_DIR, MAIN_CONFIG_FILE, LOCAL_COLLECTIONS_FILE, LLM_CONFIG_FILE+ from ..config_manager import get_data_dir, get_cache_dir++ # Print paths for debugging+ logger.info(f"Config directory: {CONFIG_DIR}")+ logger.info(f"Main config file: {MAIN_CONFIG_FILE}")+ logger.info(f"Local collections file: {LOCAL_COLLECTIONS_FILE}")+ logger.info(f"LLM config file: {LLM_CONFIG_FILE}")++ # Create config directory+ logger.info(f"Creating directory: {CONFIG_DIR}")+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)++ # Create config files+ _create_default_config_files(MAIN_CONFIG_FILE, LOCAL_COLLECTIONS_FILE, LLM_CONFIG_FILE)++ # Create data directories+ data_dir = get_data_dir()+ logger.info(f"Creating data directory: {data_dir}")+ data_dir.mkdir(parents=True, exist_ok=True)++ # Create document directories+ docs_dir = data_dir / "documents"+ docs_dir.mkdir(parents=True, exist_ok=True)+ (docs_dir / "project_documents").mkdir(exist_ok=True)+ (docs_dir / "research_papers").mkdir(exist_ok=True)+ (docs_dir / "personal_notes").mkdir(exist_ok=True)++ # Create output directory+ (data_dir / "research_outputs").mkdir(parents=True, exist_ok=True)++ # Create cache directories+ cache_dir = get_cache_dir()+ cache_dir.mkdir(parents=True, exist_ok=True)+ (cache_dir / "local_search").mkdir(exist_ok=True)++ logger.info("User directories and configuration files created successfully")++def _create_default_config_files(main_config_file, collections_file, llm_config_file):+ """+ Create default configuration files from package resources.++ Args:+ main_config_file: Path to main configuration file+ collections_file: Path to collections configuration file+ llm_config_file: Path to LLM configuration file+ """+ try:+ # Import from package resources+ import importlib.resources++ # Create main.toml if it doesn't exist+ if not main_config_file.exists():+ try:+ with importlib.resources.path('local_deep_research.defaults', 'main.toml') as default_main:+ shutil.copy(default_main, main_config_file)+ logger.info(f"Created default main configuration at {main_config_file}")+ except (ImportError, FileNotFoundError) as e:+ logger.warning(f"Could not copy default main config: {e}")+ _create_simple_main_config(main_config_file)++ # Create local_collections.toml if it doesn't exist+ if not collections_file.exists():+ try:+ with importlib.resources.path('local_deep_research.defaults', 'local_collections.toml') as default_collections:+ shutil.copy(default_collections, collections_file)+ logger.info(f"Created default collections configuration at {collections_file}")+ except (ImportError, FileNotFoundError) as e:+ logger.warning(f"Could not copy default collections config: {e}")+ _create_simple_collections_config(collections_file)++ # Create llm_config.py if it doesn't exist+ if not llm_config_file.exists():+ try:+ with importlib.resources.path('local_deep_research.defaults', 'llm_config.py') as default_llm:+ shutil.copy(default_llm, llm_config_file)+ logger.info(f"Created default LLM configuration at {llm_config_file}")+ except (ImportError, FileNotFoundError) as e:+ logger.warning(f"Could not copy default LLM config: {e}")+ _create_simple_llm_config(llm_config_file)++ except Exception as e:+ logger.error(f"Error creating default configuration files: {e}")++def _create_simple_main_config(config_file):+ """Create a simple main configuration file."""+ from ..config_manager import DEFAULT_MAIN_CONFIG++ try:+ with open(config_file, 'w') as f:+ toml.dump(DEFAULT_MAIN_CONFIG, f)+ logger.info(f"Created simple main configuration at {config_file}")+ except Exception as e:+ logger.error(f"Error creating simple main config: {e}")++def _create_simple_collections_config(config_file):+ """Create a simple collections configuration file."""+ from ..config_manager import DEFAULT_LOCAL_COLLECTIONS, get_data_dir, get_cache_dir++ # Update paths+ collections = DEFAULT_LOCAL_COLLECTIONS.copy()+ for collection_name, collection in collections.items():+ # Set paths to default locations+ collection["paths"] = [str(get_data_dir() / "documents" / collection_name.replace("_", "-"))]++ # Set cache dir+ collection["cache_dir"] = str(get_cache_dir() / "local_search" / collection_name)++ try:+ with open(config_file, 'w') as f:+ toml.dump(collections, f)+ logger.info(f"Created simple collections configuration at {config_file}")+ except Exception as e:+ logger.error(f"Error creating simple collections config: {e}")++def _create_simple_llm_config(config_file):+ """Create a simple LLM configuration file."""+ default_content = """# Default LLM configuration+DEFAULT_MODEL = "mistral"+DEFAULT_MODEL_TYPE = "ollama"+DEFAULT_TEMPERATURE = 0.7+MAX_TOKENS = 30000++# OpenAI Endpoint configuration+USE_OPENAI_ENDPOINT = True+OPENAI_ENDPOINT_URL = "https://openrouter.ai/api/v1"+OPENAI_ENDPOINT_REQUIRES_MODEL = True++from langchain_anthropic import ChatAnthropic+from langchain_openai import ChatOpenAI+from langchain_ollama import ChatOllama+from langchain_community.llms import VLLM, Ollama+import os+import logging++logger = logging.getLogger(__name__)++def get_llm(model_name=None, model_type=None, temperature=None, **kwargs):+ '''Get LLM instance based on model name and type.'''+ # Use defaults if not specified+ if model_name is None:+ model_name = DEFAULT_MODEL+ if model_type is None:+ model_type = DEFAULT_MODEL_TYPE+ if temperature is None:+ temperature = DEFAULT_TEMPERATURE++ # Common parameters+ common_params = {+ "temperature": temperature,+ "max_tokens": kwargs.get("max_tokens", MAX_TOKENS),+ }+ common_params.update(kwargs)++ # Simple pattern matching for model types+ if model_type == "ollama":+ try:+ return ChatOllama(model=model_name, **common_params)+ except (ImportError, Exception):+ from langchain_community.llms import Ollama+ return Ollama(model=model_name, **common_params)+ elif model_type == "openai":+ api_key = os.getenv("OPENAI_API_KEY")+ if not api_key:+ logger.warning("OPENAI_API_KEY not found. Falling back to default model.")+ return get_llm(DEFAULT_MODEL, DEFAULT_MODEL_TYPE, temperature, **kwargs)+ return ChatOpenAI(model=model_name, api_key=api_key, **common_params)+ elif model_type == "anthropic":+ api_key = os.getenv("ANTHROPIC_API_KEY")+ if not api_key:+ logger.warning("ANTHROPIC_API_KEY not found. Falling back to default model.")+ return get_llm(DEFAULT_MODEL, DEFAULT_MODEL_TYPE, temperature, **kwargs)+ return ChatAnthropic(model=model_name, anthropic_api_key=api_key, **common_params)+ else:+ # Default to Ollama+ return ChatOllama(model=model_name, **common_params)+"""++ try:+ with open(config_file, 'w') as f:+ f.write(default_content)+ logger.info(f"Created simple LLM configuration at {config_file}")+ except Exception as e:+ logger.error(f"Error creating simple LLM config: {e}")\ No newline at end of filediff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.pyindex d140a2c2fa..53804abaa5 100644--- a/src/local_deep_research/web/app.py+++ b/src/local_deep_research/web/app.py@@ -17,11 +17,37 @@ OPENAI_AVAILABLE = False# Initialize Flask apptry:++ import os+ import logging+ from .utilties.setup_utils import setup_user_directories++ # Configure logging+ logging.basicConfig(level=logging.INFO)+ logger = logging.getLogger(__name__)++ # Explicitly run setup+ logger.info("Initializing configuration...")+ setup_user_directories()+++# Get directories based on package installationPACKAGE_DIR = pkg_resources.resource_filename('local_deep_research', 'web')STATIC_DIR = os.path.join(PACKAGE_DIR, 'static')TEMPLATE_DIR = os.path.join(PACKAGE_DIR, 'templates')+ import sys+ import logging+ from .utils.setup_utils import setup_user_directories+++ # Setup logging+ logging.basicConfig(level=logging.INFO)++ # Create directories and default configs if needed+ setup_user_directories()+# Initialize Flask app with package directoriesapp = Flask(__name__,static_folder=STATIC_DIR,