Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

first working version with all features

LearningCircuit4efb4296e0fe
diff --git a/src/local_deep_research/__init__.py b/src/local_deep_research/__init__.py
index 4cc0f43cd7..9ce5fb0d01 100644
--- a/src/local_deep_research/__init__.py
+++ b/src/local_deep_research/__init__.py
@@ -9,16 +9,13 @@ __version__ = "0.1.0"
# Initialize configuration on module import
from .utilties.setup_utils import setup_user_directories
-setup_user_directories()
+
# Import main components
from .search_system import AdvancedSearchSystem
from .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
# Export it
__all__ = [
diff --git a/src/local_deep_research/citation_handler.py b/src/local_deep_research/citation_handler.py
index ee3758a861..cb3eb5c1a8 100644
--- a/src/local_deep_research/citation_handler.py
+++ b/src/local_deep_research/citation_handler.py
@@ -4,7 +4,7 @@ from langchain_core.documents import Document
from typing import Dict, List, Union, Any
import re
from .utilties.search_utilities import remove_think_tags
-from local_deep_research import config
+from .config import settings
class CitationHandler:
def __init__(self, llm):
@@ -90,7 +90,7 @@ Provide a detailed analysis with citations and always keep URLS. Never make up s
{formatted_sources}
Return any inconsistencies or conflicts found."""
- if config.ENABLE_FACT_CHECKING:
+ if settings.GENERAL.ENABLE_FACT_CHECKING:
fact_check_response = remove_think_tags(self.llm.invoke(fact_check_prompt).content)
else:
fact_check_response = ""
diff --git a/src/local_deep_research/config.py b/src/local_deep_research/config.py
index 7947a25516..5462d7ea48 100644
--- a/src/local_deep_research/config.py
+++ b/src/local_deep_research/config.py
@@ -1,66 +1,158 @@
+# local_deep_research/config.py
+from dynaconf import Dynaconf
+from pathlib import Path
+import logging
+from platformdirs import user_documents_dir
+import os
+# Setup logging
+logger = logging.getLogger(__name__)
-"""
-Legacy configuration module for backward compatibility.
+# Get config directory
+def get_config_dir():
+ from platformdirs import user_config_dir
+ config_dir = Path(user_config_dir("local_deep_research", "LearningCircuit"))
+ print(f"Looking for config in: {config_dir}")
+ return config_dir
-This module forwards imports to the new config_manager module.
-It will be deprecated in a future version.
-"""
+# Define config paths
+CONFIG_DIR = get_config_dir() / "config"
+CONFIG_DIR.mkdir(parents=True, exist_ok=True)
+SETTINGS_FILE = CONFIG_DIR / "settings.toml"
+SECRETS_FILE = CONFIG_DIR / ".secrets.toml"
+LLM_CONFIG_FILE = CONFIG_DIR / "llm_config.py"
+LOCAL_COLLECTIONS_FILE = CONFIG_DIR / "local_collections.toml"
+print("CONFIGDIR:", CONFIG_DIR)
+print("SECRETS_FILE:", SECRETS_FILE)
+print("SETTINGS_FILE:", SETTINGS_FILE)
-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
-)
+# Set environment variable for Dynaconf to use
+docs_base = Path(user_documents_dir()) / "local_deep_research"
+os.environ["DOCS_DIR"] = str(docs_base)
+
+
+
+
+
+
+
+
+# Expose get_llm function
+def get_llm(*args, **kwargs):
+ """
+ Helper function to get LLM from llm_config.py
+ """
+ # Import here to avoid circular imports
+ import importlib.util
+ import sys
+
+ llm_config_path = CONFIG_DIR / "llm_config.py"
+
+ # If llm_config.py exists, use it
+ if llm_config_path.exists():
+ if str(CONFIG_DIR) not in sys.path:
+ sys.path.insert(0, str(CONFIG_DIR))
+
+ spec = importlib.util.spec_from_file_location("llm_config", llm_config_path)
+ llm_config = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(llm_config)
+
+ if hasattr(llm_config, "get_llm"):
+ return llm_config.get_llm(*args, **kwargs)
+
+ # Fallback to utility function
+ from .utilties.llm_utils import get_model
+ return get_model(*args, **kwargs)
+
+# Expose get_search function
+def get_search(search_tool=None):
+ """
+ Helper function to get search engine
+ """
+ # Use specified tool or default from settings
+ tool = search_tool or settings.search.tool
+
+ # Import here to avoid circular imports
+ from .web_search_engines.search_engine_factory import get_search as factory_get_search
+
+ # Get search parameters
+ params = {
+ "search_tool": tool,
+ "llm_instance": get_llm(),
+ "max_results": settings.get("max_results"),
+ "region": settings.get("region"),
+ "time_period": settings.get("time_period"),
+ "safe_search": settings.get("safe_search"),
+ "search_snippets_only": settings.get("snippets_only"),
+ "search_language": settings.get("search_language"),
+ "max_filtered_results": settings.get("max_filtered_results")
+ }
+
+ # Create and return search engine
+ return factory_get_search(**params)
+
+def init_config_files():
+ """Initialize config files if they don't exist"""
+ import shutil
+ from importlib.resources import files
+
+ # Get default files path
+ try:
+ defaults_dir = files('local_deep_research.defaults')
+ except ImportError:
+ # Fallback for older Python versions
+ from pkg_resources import resource_filename
+ defaults_dir = Path(resource_filename('local_deep_research', 'defaults'))
+
+ # Create settings.toml if it doesn't exist
+ settings_file = CONFIG_DIR / "settings.toml"
+ if not settings_file.exists():
+ shutil.copy(defaults_dir / "main.toml", settings_file)
+ logger.info(f"Created settings.toml at {settings_file}")
+
+
+
+ # Create llm_config.py if it doesn't exist
+ llm_config_file = CONFIG_DIR / "llm_config.py"
+ if not llm_config_file.exists():
+ shutil.copy(defaults_dir / "llm_config.py", llm_config_file)
+ logger.info(f"Created llm_config.py at {llm_config_file}")
+
+ # Create local_collections.toml if it doesn't exist
+ collections_file = CONFIG_DIR / "local_collections.toml"
+ if not collections_file.exists():
+ shutil.copy(defaults_dir / "local_collections.toml", collections_file)
+ logger.info(f"Created local_collections.toml at {collections_file}")
+
+ secrets_file = CONFIG_DIR / ".secrets.toml"
+ if not secrets_file.exists():
+ with open(secrets_file, "w") as f:
+ f.write("""
+# ANTHROPIC_API_KEY = "your-api-key-here"
+# OPENAI_API_KEY = "your-openai-key-here"
+# GOOGLE_API_KEY = "your-google-key-here"
+# SERP_API_KEY = "your-api-key-here"
+# GUARDIAN_API_KEY = "your-api-key-here"
+# GOOGLE_PSE_API_KEY = "your-google-api-key-here"
+# GOOGLE_PSE_ENGINE_ID = "your-programmable-search-engine-id-here"
+""")
+
+# Initialize config files on import
+init_config_files()
+
+# Use an absolute path to your .secrets.toml for testing
+secrets_file = Path(SECRETS_FILE)
-# 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 approach
-from .utilties.enums import KnowledgeAccumulationApproach
-KNOWLEDGE_ACCUMULATION = getattr(
- KnowledgeAccumulationApproach,
- general_config["knowledge_accumulation"],
- KnowledgeAccumulationApproach.ITERATION
+settings = Dynaconf(
+ settings_files=[
+ str(SETTINGS_FILE),
+ str(LOCAL_COLLECTIONS_FILE), # Add this line
+
+ ],
+ secrets=str(SECRETS_FILE),
+ env_prefix="LDR",
+ load_dotenv=True,
+ envvar_prefix="LDR",
+ env_file=str(CONFIG_DIR / ".env"), # Add this line
)
-# 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 file
diff --git a/src/local_deep_research/config.py__old b/src/local_deep_research/config.py__old
deleted file mode 100644
index 10eda52b44..0000000000
--- a/src/local_deep_research/config.py__old
+++ /dev/null
@@ -1,291 +0,0 @@
-"""
-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 file
diff --git a/src/local_deep_research/config_manager.py b/src/local_deep_research/config_manager.py
deleted file mode 100644
index e0392330fb..0000000000
--- a/src/local_deep_research/config_manager.py
+++ /dev/null
@@ -1,369 +0,0 @@
-# src/local_deep_research/config_manager.py
-
-"""
-Configuration manager for Local Deep Research.
-
-This module uses Dynaconf to handle configuration management
-while using template files from the defaults directory.
-"""
-
-import os
-import sys
-import importlib.util
-import logging
-import shutil
-from pathlib import Path
-from typing import Dict, Any, Optional
-
-# Import Dynaconf - required dependency
-from dynaconf import Dynaconf, loaders
-
-# 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."""
- from platformdirs import user_config_dir
- return Path(user_config_dir(APP_NAME, APP_AUTHOR))
-
-def get_data_dir() -> Path:
- """Get the data directory based on platform standards."""
- from platformdirs import user_data_dir
- data_dir_path = Path(user_data_dir(APP_NAME, APP_AUTHOR))
- logger.info(f"Data Dir: {data_dir_path}")
- return data_dir_path
-
-def get_cache_dir() -> Path:
- """Get the cache directory based on platform standards."""
- from platformdirs import user_cache_dir
- return Path(user_cache_dir(APP_NAME, APP_AUTHOR))
-
-# Define 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"
-
-# Dynaconf settings object - initialized once
-settings = None
-
-# LLM config cache
-_llm_config_cache = None
-
-def ensure_config_files_exist():
- """
- Ensure all configuration files exist by copying from templates.
- Raises a clear error if templates are not found.
- """
- # Create config directory
- CONFIG_DIR.mkdir(parents=True, exist_ok=True)
-
- # Try to find the default templates in the package
- package_dir = Path(__file__).parent
- defaults_dir = package_dir / "defaults"
-
- # Log what we find for debugging
- logger.info(f"Looking for default templates in: {defaults_dir}")
- if not defaults_dir.exists():
- raise FileNotFoundError(
- f"Default templates directory not found at {defaults_dir}. "
- f"Make sure the 'defaults' directory exists in the package."
- )
-
- # Check for required default files
- required_files = ["main.toml", "local_collections.toml", "llm_config.py"]
- missing_files = []
- for file in required_files:
- if not (defaults_dir / file).exists():
- missing_files.append(file)
-
- if missing_files:
- raise FileNotFoundError(
- f"Missing required default templates: {', '.join(missing_files)}. "
- f"Make sure all required templates exist in {defaults_dir}."
- )
-
- # Create directories first
- data_dir = get_data_dir()
- docs_dir = data_dir / "documents"
- docs_dir.mkdir(parents=True, exist_ok=True)
- cache_dir = get_cache_dir()
- cache_dir.mkdir(parents=True, exist_ok=True)
-
- # Create subdirectories
- (docs_dir / "project_documents").mkdir(exist_ok=True)
- (docs_dir / "research_papers").mkdir(exist_ok=True)
- (docs_dir / "personal_notes").mkdir(exist_ok=True)
- (cache_dir / "local_search").mkdir(exist_ok=True)
- (data_dir / "research_outputs").mkdir(parents=True, exist_ok=True)
-
- # Copy main.toml if needed
- print(MAIN_CONFIG_FILE)
- logger.info(f"Main config file exists? {MAIN_CONFIG_FILE.exists()}")
-
- if not False:
- default_main = defaults_dir / "main.toml"
- logger.info(f"Copying main.toml from {default_main} to {MAIN_CONFIG_FILE}")
- shutil.copy(default_main, MAIN_CONFIG_FILE)
- # After copying the file
- if os.path.exists(MAIN_CONFIG_FILE):
- absolute_path = os.path.abspath(MAIN_CONFIG_FILE)
- logger.info(f"File exists at absolute path: {absolute_path}")
- else:
- logger.error(f"File does not exist after copy: {MAIN_CONFIG_FILE}")
- # Process and copy local_collections.toml if needed
- if not LOCAL_COLLECTIONS_FILE.exists():
- default_collections = defaults_dir / "local_collections.toml"
- logger.info(f"Processing local_collections.toml from {default_collections}")
-
- # Read the template file
- with open(default_collections, 'r') as f:
- template_content = f.read()
-
- # Replace placeholders with actual paths
- template_content = template_content.replace("__DATA_DIR__", str(data_dir))
- template_content = template_content.replace("__CACHE_DIR__", str(cache_dir))
-
- # Write the processed file
- with open(LOCAL_COLLECTIONS_FILE, 'w') as f:
- f.write(template_content)
-
- logger.info(f"Created collections configuration at {LOCAL_COLLECTIONS_FILE}")
-
- # Copy llm_config.py if needed
- if not LLM_CONFIG_FILE.exists():
- default_llm = defaults_dir / "llm_config.py"
- logger.info(f"Copying llm_config.py from {default_llm} to {LLM_CONFIG_FILE}")
- shutil.copy(default_llm, LLM_CONFIG_FILE)
-
- logger.info("Configuration files successfully set up")
-
-def get_settings(reload=False):
- """Get Dynaconf settings object."""
- global settings
-
- if settings is not None and not reload:
- return settings
-
- # Ensure config files exist
- ensure_config_files_exist()
-
- # Initialize Dynaconf with our config files
- settings = Dynaconf(
- settings_files=[
- MAIN_CONFIG_FILE,
- LOCAL_COLLECTIONS_FILE
- ],
- environments=True,
- env_prefix="LDR",
- includes=[], # Additional config files
- )
-
- return settings
-
-def load_main_config(reload=False):
- """Load main configuration using Dynaconf."""
- settings = get_settings(reload)
-
- # Convert Dynaconf settings to a dictionary structure
- # matching your existing expectations
- config = {
- "general": {
- "output_dir": settings.get('output_dir', 'research_outputs'),
- "knowledge_accumulation": settings.get('knowledge_accumulation', 'ITERATION'),
- "knowledge_accumulation_context_limit": settings.get('knowledge_accumulation_context_limit', 2000000),
- "enable_fact_checking": settings.get('enable_fact_checking', False),
- },
- "search": {
- "tool": settings.get('tool', 'auto'),
- "iterations": settings.get('iterations', 3),
- "questions_per_iteration": settings.get('questions_per_iteration', 3),
- "searches_per_section": settings.get('searches_per_section', 3),
- "max_results": settings.get('max_results', 50),
- "max_filtered_results": settings.get('max_filtered_results', 5),
- "region": settings.get('region', 'us'),
- "time_period": settings.get('time_period', 'y'),
- "safe_search": settings.get('safe_search', True),
- "search_language": settings.get('search_language', 'English'),
- "snippets_only": settings.get('snippets_only', False),
- "skip_relevance_filter": settings.get('skip_relevance_filter', False),
- "quality_check_urls": settings.get('quality_check_urls', True),
- }
- }
-
- return config
-
-def load_local_collections(reload=False):
- """Load local collections configuration using Dynaconf."""
- settings = get_settings(reload)
-
- # Get all local collections
- # This is a bit tricky as Dynaconf flattens the hierarchy
- collections = {}
-
- # Process each collection from settings
- # Note: You'll need to adjust this if your local_collections.toml has a different structure
- for collection_name in ["project_docs", "research_papers", "personal_notes"]:
- if hasattr(settings, collection_name):
- collection_data = getattr(settings, collection_name)
- collections[collection_name] = collection_data
-
- # Ensure directories exist
- for collection in collections.values():
- for path in collection.get("paths", []):
- Path(path).mkdir(parents=True, exist_ok=True)
-
- return collections
-
-def load_llm_config(reload=False):
- """Load LLM configuration by importing the Python module."""
- global _llm_config_cache
-
- if _llm_config_cache is not None and not reload:
- return _llm_config_cache
-
- # Ensure config files exist
- ensure_config_files_exist()
-
- # Add config directory to path if needed
- if str(CONFIG_DIR) not in sys.path:
- sys.path.insert(0, str(CONFIG_DIR))
-
- # 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
- _llm_config_cache = config
-
- return config
-
-def save_main_config(config):
- """Save main configuration to file."""
- # Ensure directory exists
- CONFIG_DIR.mkdir(parents=True, exist_ok=True)
-
- # Use Dynaconf's writer to save the config
- loaders.write(str(MAIN_CONFIG_FILE), config, env="default")
-
- # Reset settings to reload from file
- get_settings(reload=True)
-
- logger.info(f"Saved main configuration to {MAIN_CONFIG_FILE}")
-
-def save_local_collections(collections):
- """Save local collections configuration to file."""
- # Ensure directory exists
- CONFIG_DIR.mkdir(parents=True, exist_ok=True)
-
- # Use Dynaconf's writer to save the config
- loaders.write(str(LOCAL_COLLECTIONS_FILE), collections, env="default")
-
- # Reset settings to reload from file
- get_settings(reload=True)
-
- # 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}")
-
-def get_config():
- """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 .utilties.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.
-
- 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 at module load time
-ensure_config_files_exist()
-
-# API exports
-__all__ = [
- "get_config",
- "get_llm",
- "load_main_config",
- "load_local_collections",
- "load_llm_config",
- "save_main_config",
- "save_local_collections",
- "get_search",
- "get_data_dir",
- "get_cache_dir",
- "CONFIG_DIR",
- "MAIN_CONFIG_FILE",
- "LOCAL_COLLECTIONS_FILE",
- "LLM_CONFIG_FILE"
-]
\ No newline at end of file
diff --git a/src/local_deep_research/defaults/llm_config.py b/src/local_deep_research/defaults/llm_config.py
index 1fbc404e69..7f714e0c33 100644
--- a/src/local_deep_research/defaults/llm_config.py
+++ b/src/local_deep_research/defaults/llm_config.py
@@ -3,38 +3,197 @@ 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
+from langchain_community.llms import VLLM
+from local_deep_research.config import settings
import os
import logging
+from enum import Enum, auto
# Initialize environment
-load_dotenv()
logger = logging.getLogger(__name__)
-# Main LLM settings
+# Provider enum
+class ModelProvider(Enum):
+ OLLAMA = auto()
+ OPENAI = auto()
+ ANTHROPIC = auto()
+ VLLM = auto()
+ OPENAI_ENDPOINT = auto()
+ NONE = auto()
+
+# ================================
+# USER CONFIGURATION SECTION
+# ================================
+
+# Set your preferred model provider here
+DEFAULT_PROVIDER = ModelProvider.OPENAI_ENDPOINT # Change this to your preferred provider
+
+# Set your default model name here
DEFAULT_MODEL = "mistral" # Your default model
-DEFAULT_MODEL_TYPE = "ollama" # Type of the default model: "openai", "anthropic", "ollama", "openai_endpoint", "vllm"
+
+# Set default model parameters
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
+# Server URLs
+OPENAI_ENDPOINT_URL = "https://openrouter.ai/api/v1" # For OpenRouter or compatible services
+OLLAMA_BASE_URL = "http://localhost:11434" # URL for Ollama server
+
+
+
+
+# ================================
+# LLM FUNCTIONS
+# ================================
+
+
+
+
+
+def get_llm(model_name=None, temperature=None, provider=None):
+ """
+ Get LLM instance based on model name and provider.
+
+ Args:
+ model_name: Name of the model to use (if None, uses DEFAULT_MODEL)
+ temperature: Model temperature (if None, uses DEFAULT_TEMPERATURE)
+ provider: Provider to use (if None, uses DEFAULT_PROVIDER)
+
+ Returns:
+ A LangChain LLM instance
+ """
+ if model_name is None:
+ model_name = DEFAULT_MODEL
+
+ if temperature is None:
+ temperature = DEFAULT_TEMPERATURE
+
+ if provider is None:
+ provider = DEFAULT_PROVIDER
+
+ # Common parameters for all models
+ common_params = {
+ "temperature": temperature,
+ "max_tokens": MAX_TOKENS,
+ }
+
+ # Handle different providers
+ if provider == ModelProvider.ANTHROPIC:
+ api_key = settings.get('ANTHROPIC_API_KEY', '')
+ if not api_key:
+ logger.warning("ANTHROPIC_API_KEY not found. Falling back to default model.")
+ return get_fallback_model(temperature)
+
+ return ChatAnthropic(
+ model=model_name, anthropic_api_key=api_key, **common_params
+ )
+
+ elif provider == ModelProvider.OPENAI:
+ api_key = settings.get('OPENAI_API_KEY', '')
+ if not api_key:
+ logger.warning("OPENAI_API_KEY not found. Falling back to default model.")
+ return get_fallback_model(temperature)
+
+ return ChatOpenAI(model=model_name, api_key=api_key, **common_params)
+
+ elif provider == ModelProvider.OPENAI_ENDPOINT:
+ api_key = settings.OPENAI_ENDPOINT_API_KEY
+
+ if not api_key:
+ logger.warning("OPENAI_ENDPOINT_API_KEY not found. Falling back to default model.")
+ return get_fallback_model(temperature)
+
+ return ChatOpenAI(
+ model=model_name,
+ api_key=api_key,
+ openai_api_base=OPENAI_ENDPOINT_URL,
+ **common_params
+ )
+
+ elif provider == ModelProvider.VLLM:
+ try:
+ return VLLM(
+ model=model_name,
+ trust_remote_code=True,
+ max_new_tokens=128,
+ top_k=10,
+ top_p=0.95,
+ temperature=temperature,
+ )
+ except Exception as e:
+ logger.error(f"Error loading VLLM model: {e}")
+ logger.warning("Falling back.")
+ return get_fallback_model(temperature)
+
+ elif provider == ModelProvider.OLLAMA:
+ try:
+ # Use the configurable Ollama base URL
+ base_url = settings.get('OLLAMA_BASE_URL', OLLAMA_BASE_URL)
+ return ChatOllama(model=model_name, base_url=base_url, **common_params)
+ except Exception as e:
+ logger.error(f"Error loading Ollama model: {e}")
+ return get_fallback_model(temperature)
+
+ else:
+ return get_fallback_model(temperature)
+
+def get_fallback_model(temperature=DEFAULT_TEMPERATURE):
+ """Create a dummy model for when no providers are available"""
+ from langchain_community.llms.fake import FakeListLLM
+ return FakeListLLM(
+ responses=["No language models are available. Please install Ollama or set up API keys."]
+ )
+
+# ================================
+# COMPATIBILITY FUNCTIONS
+# ================================
+
+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
+
+
+
+
+# ================================
+# HELPER FUNCTIONS
+# ================================
def is_openai_available():
"""Check if OpenAI is available"""
try:
- api_key = os.environ.get("OPENAI_API_KEY")
+ api_key = settings.api_keys.get('OPENAI_API_KEY', '')
return bool(api_key)
except:
return False
@@ -42,16 +201,19 @@ def is_openai_available():
def is_anthropic_available():
"""Check if Anthropic is available"""
try:
- api_key = os.environ.get("ANTHROPIC_API_KEY")
+ api_key = settings.api_keys.get('ANTHROPIC_API_KEY', '')
return bool(api_key)
except:
return False
+
+
def is_openai_endpoint_available():
"""Check if OpenAI endpoint is available"""
+ print(os.getenv("OPENAI_ENDPOINT_API_KEY"))
try:
- api_key = os.environ.get("OPENAI_ENDPOINT_API_KEY")
- return bool(api_key) and USE_OPENAI_ENDPOINT
+ api_key = settings.OPENAI_ENDPOINT_API_KEY
+ return bool(api_key)
except:
return False
@@ -59,224 +221,49 @@ def is_ollama_available():
"""Check if Ollama is running"""
try:
import requests
- base_url = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")
+ base_url = settings.get('OLLAMA_BASE_URL', OLLAMA_BASE_URL)
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"""
+def is_vllm_available():
+ """Check if VLLM capability is available"""
+ try:
+ import torch
+ import transformers
+ return True
+ except ImportError:
+ return False
+
+def get_available_providers():
+ """Get dictionary of available providers"""
providers = {}
if is_ollama_available():
- providers["ollama"] = "Ollama (local models)"
+ providers[ModelProvider.OLLAMA] = "Ollama (local models)"
if is_openai_available():
- providers["openai"] = "OpenAI API"
+ providers[ModelProvider.OPENAI] = "OpenAI API"
if is_anthropic_available():
- providers["anthropic"] = "Anthropic API"
+ providers[ModelProvider.ANTHROPIC] = "Anthropic API"
if is_openai_endpoint_available():
- providers["openai_endpoint"] = "OpenAI-compatible Endpoint"
+ providers[ModelProvider.OPENAI_ENDPOINT] = "OpenAI-compatible Endpoint"
- # Check for VLLM capability
- try:
- import torch
- import transformers
- providers["vllm"] = "VLLM (local models)"
- except ImportError:
- pass
+ if is_vllm_available():
+ providers[ModelProvider.VLLM] = "VLLM (local models)"
- # Default fallback
if not providers:
- providers["none"] = "No model providers available"
+ providers[ModelProvider.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 file
+# Log which providers are available
+AVAILABLE_PROVIDERS = get_available_providers()
+logger.info(f"Available providers: {[p.name for p in AVAILABLE_PROVIDERS.keys()]}")
+
+# Check if selected provider is available
+if DEFAULT_PROVIDER not in AVAILABLE_PROVIDERS and DEFAULT_PROVIDER != ModelProvider.NONE:
+ logger.warning(f"Selected provider {DEFAULT_PROVIDER.name} is not available.")
\ No newline at end of file
diff --git a/src/local_deep_research/defaults/local_collections.toml b/src/local_deep_research/defaults/local_collections.toml
index 0e69b1939a..57333849c3 100644
--- a/src/local_deep_research/defaults/local_collections.toml
+++ b/src/local_deep_research/defaults/local_collections.toml
@@ -5,7 +5,7 @@
[project_docs]
name = "Project Documents"
description = "Project documentation and specifications"
-paths = ["__DATA_DIR__/documents/project_documents"]
+paths = ["@format ${DOCS_DIR}/project_documents"]
enabled = true
embedding_model = "all-MiniLM-L6-v2"
embedding_device = "cpu"
@@ -20,7 +20,7 @@ cache_dir = "__CACHE_DIR__/local_search/project_docs"
[research_papers]
name = "Research Papers"
description = "Academic research papers and articles"
-paths = ["__DATA_DIR__/documents/research_papers"]
+paths = ["@format ${DOCS_DIR}/research_papers"]
enabled = true
embedding_model = "all-MiniLM-L6-v2"
embedding_device = "cpu"
@@ -35,7 +35,7 @@ cache_dir = "__CACHE_DIR__/local_search/research_papers"
[personal_notes]
name = "Personal Notes"
description = "Personal notes and documents"
-paths = ["__DATA_DIR__/documents/personal_notes"]
+paths = ["@format ${DOCS_DIR}/personal_notes"]
enabled = true
embedding_model = "all-MiniLM-L6-v2"
embedding_device = "cpu"
diff --git a/src/local_deep_research/defaults/main.toml b/src/local_deep_research/defaults/main.toml
index 6b39b367ff..9fc749837c 100644
--- a/src/local_deep_research/defaults/main.toml
+++ b/src/local_deep_research/defaults/main.toml
@@ -54,4 +54,4 @@ snippets_only = false
skip_relevance_filter = false
# Check URL quality
-quality_check_urls = true
\ No newline at end of file
+quality_check_urls = true
diff --git a/src/local_deep_research/main.py b/src/local_deep_research/main.py
index 914eae92c5..c27c163c9b 100644
--- a/src/local_deep_research/main.py
+++ b/src/local_deep_research/main.py
@@ -1,6 +1,6 @@
from .search_system import AdvancedSearchSystem
from typing import Dict
-
+from .config import settings
def print_report(report: Dict):
"""Print and save the report in a readable format"""
@@ -32,6 +32,7 @@ from .report_generator import IntegratedReportGenerator
report_generator = IntegratedReportGenerator()
+
def main():
import os
import logging
@@ -40,13 +41,13 @@ def main():
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
-
+ logger.info(f"Starting with settings: iterations={settings.search.iterations}, "
+ f"questions_per_iteration={settings.search.questions_per_iteration}")
+
# Explicitly run setup
logger.info("Initializing configuration...")
setup_user_directories()
-
-
system = AdvancedSearchSystem()
print("Welcome to the Advanced Research System")
@@ -73,6 +74,9 @@ def main():
if query.lower() == "quit":
break
+ # System will automatically use updated configuration
+ # through the automatic reloading in get_llm() and get_search()
+
if choice == "1":
print("\nResearching... This may take a few minutes.\n")
else:
@@ -105,6 +109,5 @@ def main():
else:
print("Research failed. Please try again.")
-
if __name__ == "__main__":
main()
\ No newline at end of file
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index 00b78a1ca1..9e5a6ff230 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -3,24 +3,30 @@ from datetime import datetime
from .utilties.search_utilities import remove_think_tags, format_findings_to_text, print_search_results, format_links
import os
from .utilties.enums import KnowledgeAccumulationApproach
-from .config import get_llm, get_search, SEARCH_ITERATIONS, QUESTIONS_PER_ITERATION
-from local_deep_research import config
+from .config import settings, get_llm, get_search
from .citation_handler import CitationHandler
from datetime import datetime
from .utilties.search_utilities import extract_links_from_search_results
class AdvancedSearchSystem:
def __init__(self):
+
+
+ # Get fresh configuration
+
self.search = get_search()
self.model = get_llm()
- self.max_iterations = SEARCH_ITERATIONS
- self.questions_per_iteration = QUESTIONS_PER_ITERATION
- self.context_limit = config.KNOWLEDGE_ACCUMULATION_CONTEXT_LIMIT
+ self.max_iterations = settings.search.iterations
+ self.questions_per_iteration = settings.search.questions_per_iteration
+
+ self.context_limit = settings.general.knowledge_accumulation_context_limit
self.questions_by_iteration = {}
self.citation_handler = CitationHandler(self.model)
self.progress_callback = None
self.all_links_of_system = list()
+
+
def set_progress_callback(self, callback: Callable[[str, int, dict], None]) -> None:
"""Set a callback function to receive progress updates.
@@ -93,6 +99,10 @@ class AdvancedSearchSystem:
return response
def analyze_topic(self, query: str) -> Dict:
+
+
+
+
findings = []
current_knowledge = ""
iteration = 0
@@ -152,6 +162,7 @@ class AdvancedSearchSystem:
formatted_links = ""
if links:
formatted_links=format_links(links=links)
+ print(formatted_links)
results_with_links = str(result["content"]) #+ "\n" + str(formatted_links)
if result is not None:
findings.append(
@@ -166,11 +177,11 @@ class AdvancedSearchSystem:
- if config.KNOWLEDGE_ACCUMULATION != KnowledgeAccumulationApproach.NO_KNOWLEDGE:
+ if settings.general.knowledge_accumulation != KnowledgeAccumulationApproach.NO_KNOWLEDGE:
current_knowledge = current_knowledge + "\n\n\n New: \n" + results_with_links
print(current_knowledge)
- if config.KNOWLEDGE_ACCUMULATION == KnowledgeAccumulationApproach.QUESTION:
+ if settings.general.knowledge_accumulation == KnowledgeAccumulationApproach.QUESTION:
self._update_progress(f"Compress Knowledge for: {question}",
int(question_progress_base + 0),
{"phase": "analysis"})
@@ -185,7 +196,7 @@ class AdvancedSearchSystem:
self._update_progress(f"Compressing knowledge after iteration {iteration}",
int((iteration / total_iterations) * 100 - 5),
{"phase": "knowledge_compression"})
- if config.KNOWLEDGE_ACCUMULATION == KnowledgeAccumulationApproach.ITERATION:
+ if settings.general.knowledge_accumulation == KnowledgeAccumulationApproach.ITERATION:
current_knowledge = self._compress_knowledge(current_knowledge , query, section_links)
diff --git a/src/local_deep_research/utilties/setup_utils.py b/src/local_deep_research/utilties/setup_utils.py
index 056f2bd8ec..63f0dd32cc 100644
--- a/src/local_deep_research/utilties/setup_utils.py
+++ b/src/local_deep_research/utilties/setup_utils.py
@@ -1,6 +1,6 @@
"""Setup utilities (legacy wrapper)."""
def setup_user_directories():
- """Set up directories (delegated to config_manager)."""
- from ..config_manager import ensure_config_files_exist
- ensure_config_files_exist()
\ No newline at end of file
+ """Set up directories and ensure config files exist."""
+ from ..config import init_config_files
+ init_config_files()
\ No newline at end of file
diff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.py
index 53804abaa5..cb5806f73f 100644
--- a/src/local_deep_research/web/app.py
+++ b/src/local_deep_research/web/app.py
@@ -4,7 +4,7 @@ import time
import sqlite3
import threading
from datetime import datetime
-from flask import Flask, render_template, request, jsonify, send_from_directory, Response, make_response, current_app, Blueprint, redirect, url_for
+from flask import Flask, render_template, request, jsonify, send_from_directory, Response, make_response, current_app, Blueprint, redirect, url_for, flash
from flask_socketio import SocketIO, emit
from ..search_system import AdvancedSearchSystem
from ..report_generator import IntegratedReportGenerator
@@ -12,15 +12,24 @@ from ..report_generator import IntegratedReportGenerator
from dateutil import parser
import traceback
import pkg_resources
+# Import the new configuration manager
+from ..config import get_config_dir
+
+
+CONFIG_DIR = get_config_dir() / "config"
+MAIN_CONFIG_FILE = CONFIG_DIR / "settings.toml"
+LLM_CONFIG_FILE = CONFIG_DIR / "llm_config.py"
+LOCAL_COLLECTIONS_FILE = CONFIG_DIR / "local_collections.toml"
+import toml
+
# Set flag for tracking OpenAI availability - we'll check it only when needed
OPENAI_AVAILABLE = False
# Initialize Flask app
try:
-
import os
import logging
- from .utilties.setup_utils import setup_user_directories
+ from ..utilties.setup_utils import setup_user_directories
# Configure logging
logging.basicConfig(level=logging.INFO)
@@ -30,18 +39,11 @@ try:
logger.info("Initializing configuration...")
setup_user_directories()
-
-
# Get directories based on package installation
PACKAGE_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)
@@ -198,7 +200,6 @@ def calculate_duration(created_at_str):
return duration_seconds
# Initialize the database on startup
-# @app.before_first_request # This is deprecated in newer Flask versions
def initialize():
init_db()
@@ -871,85 +872,39 @@ def delete_research(research_id):
conn.close()
return jsonify({'status': 'success'})
-from flask import render_template, redirect, url_for
-from ..config import get_config, save_config
-@research_bp.route('/settings', methods=['GET', 'POST'])
+# Main settings page that links to specialized config pages
+@research_bp.route('/settings', methods=['GET'])
def settings_page():
- if request.method == 'POST':
- # Get current config
- current_config = get_config()
-
- # Process checkbox fields
- checkbox_fields = [
- 'ENABLE_FACT_CHECKING', 'SEARCH_SNIPPETS_ONLY', 'SKIP_RELEVANCE_FILTER',
- 'QUALITY_CHECK_DDG_URLS', 'SAFE_SEARCH', 'OPENAIENDPOINT'
- ]
-
- # First set all checkboxes to False
- for key in checkbox_fields:
- if key in current_config and isinstance(current_config[key], bool):
- current_config[key] = False
-
- # Update with form data
- for key, value in request.form.items():
- if key in current_config:
- # Convert value to the appropriate type
- if isinstance(current_config[key], bool) or key in checkbox_fields:
- current_config[key] = value.lower() in ('true', 'yes', '1', 'on', 'checked')
- elif isinstance(current_config[key], int):
- try:
- current_config[key] = int(value)
- except ValueError:
- pass
- elif isinstance(current_config[key], float):
- try:
- current_config[key] = float(value)
- except ValueError:
- pass
- else:
- current_config[key] = value
-
- # Handle special cases
- if 'search_tool' in request.form:
- current_config['search_tool'] = request.form['search_tool']
-
- if 'KNOWLEDGE_ACCUMULATION' in request.form:
- from .utilties.enums import KnowledgeAccumulationApproach
- value = request.form['KNOWLEDGE_ACCUMULATION']
- try:
- current_config['KNOWLEDGE_ACCUMULATION'] = getattr(KnowledgeAccumulationApproach, value)
- except AttributeError:
- pass
-
- # Save updated config
- save_config(current_config)
-
- flash('Settings saved successfully', 'success')
- return redirect(url_for('research.settings_page'))
+ """Main settings dashboard with links to specialized config pages"""
+ return render_template('settings_dashboard.html')
+
+@research_bp.route('/settings/main', methods=['GET'])
+def main_config_page():
+ """Edit main configuration with search parameters"""
+ return render_template('main_config.html', main_file_path=MAIN_CONFIG_FILE)
+
+@research_bp.route('/settings/llm', methods=['GET'])
+def llm_config_page():
+ """Edit LLM configuration using raw file editor"""
+ return render_template('llm_config.html', llm_file_path=LLM_CONFIG_FILE)
+
+@research_bp.route('/settings/collections', methods=['GET'])
+def collections_config_page():
+ """Edit local collections configuration using raw file editor"""
+ return render_template('collections_config.html', collections_file_path=LOCAL_COLLECTIONS_FILE)
+
+@research_bp.route('/settings/api_keys', methods=['GET'])
+def api_keys_config_page():
+ """Edit API keys configuration"""
+ # Get the secrets file path
+ secrets_file = CONFIG_DIR / ".secrets.toml"
- # Get the raw config file content
- try:
- import os
- module_path = os.path.join(os.path.dirname(__file__), "config.py")
- if os.path.exists(module_path):
- with open(module_path, "r") as f:
- raw_config = f.read()
- else:
- # Look for the config in the parent directory
- parent_module_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "config.py")
- if os.path.exists(parent_module_path):
- with open(parent_module_path, "r") as f:
- raw_config = f.read()
- else:
- raw_config = "Config file not found. Please check your installation."
- except Exception as e:
- raw_config = f"Error loading raw configuration: {str(e)}"
-
- # For GET request, display settings form
- return render_template('settings.html', config=get_config(), raw_config=raw_config)
-@research_bp.route('/save_raw_config', methods=['POST'])
-def save_raw_config():
+ return render_template('api_keys_config.html', secrets_file_path=secrets_file)
+
+# API endpoint to save raw LLM config
+@research_bp.route('/api/save_llm_config', methods=['POST'])
+def save_llm_config():
try:
data = request.get_json()
raw_config = data.get('raw_config', '')
@@ -960,31 +915,146 @@ def save_raw_config():
except SyntaxError as e:
return jsonify({'success': False, 'error': f'Syntax error: {str(e)}'})
- # Save to file
- import os
- module_path = os.path.join(os.path.dirname(__file__), "config.py")
- if os.path.exists(module_path):
- config_path = module_path
- else:
- # Look for the config in the parent directory
- parent_module_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "config.py")
- if os.path.exists(parent_module_path):
- config_path = parent_module_path
- else:
- return jsonify({'success': False, 'error': 'Config file not found'})
+ # Ensure directory exists
+ os.makedirs(os.path.dirname(LLM_CONFIG_FILE), exist_ok=True)
+
+ # Create a backup first
+ backup_path = f"{LLM_CONFIG_FILE}.bak"
+ if os.path.exists(LLM_CONFIG_FILE):
+ import shutil
+ shutil.copy2(LLM_CONFIG_FILE, backup_path)
+
+ # Write new config
+ with open(LLM_CONFIG_FILE, 'w') as f:
+ f.write(raw_config)
+
+ return jsonify({'success': True})
+ except Exception as e:
+ return jsonify({'success': False, 'error': str(e)})
+
+# API endpoint to save raw collections config
+@research_bp.route('/api/save_collections_config', methods=['POST'])
+def save_collections_config():
+ try:
+ data = request.get_json()
+ raw_config = data.get('raw_config', '')
+
+ # Validate TOML syntax
+ try:
+ toml.loads(raw_config)
+ except toml.TomlDecodeError as e:
+ return jsonify({'success': False, 'error': f'TOML syntax error: {str(e)}'})
+
+ # Ensure directory exists
+ os.makedirs(os.path.dirname(LOCAL_COLLECTIONS_FILE), exist_ok=True)
# Create a backup first
- import shutil
- backup_path = config_path + '.bak'
- shutil.copy2(config_path, backup_path)
+ backup_path = f"{LOCAL_COLLECTIONS_FILE}.bak"
+ if os.path.exists(LOCAL_COLLECTIONS_FILE):
+ import shutil
+ shutil.copy2(LOCAL_COLLECTIONS_FILE, backup_path)
# Write new config
- with open(config_path, 'w') as f:
+ with open(LOCAL_COLLECTIONS_FILE, 'w') as f:
f.write(raw_config)
+
+ # Also trigger a reload in the collections system
+ try:
+ load_local_collections(reload=True)
+ except Exception as reload_error:
+ return jsonify({'success': True, 'warning': f'Config saved, but error reloading: {str(reload_error)}'})
return jsonify({'success': True})
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
+
+# API endpoint to save raw main config
+@research_bp.route('/api/save_main_config', methods=['POST'])
+def save_raw_main_config():
+ try:
+ data = request.get_json()
+ raw_config = data.get('raw_config', '')
+
+ # Validate TOML syntax
+ try:
+ toml.loads(raw_config)
+ except toml.TomlDecodeError as e:
+ return jsonify({'success': False, 'error': f'TOML syntax error: {str(e)}'})
+
+ # Ensure directory exists
+ os.makedirs(os.path.dirname(MAIN_CONFIG_FILE), exist_ok=True)
+
+ # Create a backup first
+ backup_path = f"{MAIN_CONFIG_FILE}.bak"
+ if os.path.exists(MAIN_CONFIG_FILE):
+ import shutil
+ shutil.copy2(MAIN_CONFIG_FILE, backup_path)
+
+ # Write new config
+ with open(MAIN_CONFIG_FILE, 'w') as f:
+ f.write(raw_config)
+
+ return jsonify({'success': True})
+ except Exception as e:
+ return jsonify({'success': False, 'error': str(e)})
+@research_bp.route('/raw_config')
+def get_raw_config():
+ """Return the raw configuration file content"""
+ try:
+ # Determine which config file to load based on a query parameter
+ config_type = request.args.get('type', 'main')
+
+ if config_type == 'main':
+ config_path = os.path.join(app.config['CONFIG_DIR'], 'config.toml')
+ with open(config_path, 'r') as f:
+ return f.read()
+ elif config_type == 'llm':
+ config_path = os.path.join(app.config['CONFIG_DIR'], 'llm_config.py')
+ with open(config_path, 'r') as f:
+ return f.read()
+ elif config_type == 'collections':
+ config_path = os.path.join(app.config['CONFIG_DIR'], 'collections.toml')
+ with open(config_path, 'r') as f:
+ return f.read()
+ else:
+ return "Unknown configuration type", 400
+ except Exception as e:
+ return str(e), 500
+import os
+import subprocess
+import platform
+
+@research_bp.route('/open_file_location', methods=['POST'])
+def open_file_location():
+ file_path = request.form.get('file_path')
+
+ if not file_path:
+ flash('No file path provided', 'error')
+ return redirect(url_for('research.settings_page'))
+
+ # Get the directory containing the file
+ dir_path = os.path.dirname(os.path.abspath(file_path))
+
+ # Open the directory in the file explorer
+ try:
+ if platform.system() == "Windows":
+ subprocess.Popen(f'explorer "{dir_path}"')
+ elif platform.system() == "Darwin": # macOS
+ subprocess.Popen(["open", dir_path])
+ else: # Linux
+ subprocess.Popen(["xdg-open", dir_path])
+
+ flash(f'Opening folder: {dir_path}', 'success')
+ except Exception as e:
+ flash(f'Error opening folder: {str(e)}', 'error')
+
+ # Redirect back to the settings page
+ if 'llm' in file_path:
+ return redirect(url_for('research.llm_config_page'))
+ elif 'collections' in file_path:
+ return redirect(url_for('research.collections_config_page'))
+ else:
+ return redirect(url_for('research.main_config_page'))
# Register the blueprint
app.register_blueprint(research_bp)
@@ -998,7 +1068,11 @@ def app_serve_static(path):
def favicon():
return send_from_directory(app.static_folder, 'favicon.ico', mimetype='image/x-icon')
-if __name__ == '__main__':
+def main():
+ """
+ Entry point for the web application when run as a command.
+ This function is needed for the package's entry point to work properly.
+ """
# Check for OpenAI availability but don't import it unless necessary
try:
import os
@@ -1018,4 +1092,9 @@ if __name__ == '__main__':
print(f"Error checking OpenAI availability: {e}")
# Run with threading (more stable than eventlet with complex dependencies)
- socketio.run(app, debug=True, host='0.0.0.0', port=5000, allow_unsafe_werkzeug=False)
\ No newline at end of file
+ socketio.run(app, debug=True, host='0.0.0.0', port=5000, allow_unsafe_werkzeug=False)
+
+if __name__ == '__main__':
+ main()
+
+
diff --git a/src/local_deep_research/web/static/css/styles.css b/src/local_deep_research/web/static/css/styles.css
index 218f7898d3..500dceee67 100644
--- a/src/local_deep_research/web/static/css/styles.css
+++ b/src/local_deep_research/web/static/css/styles.css
@@ -980,4 +980,29 @@ textarea:focus, input[type="text"]:focus {
display: flex;
justify-content: center;
margin-top: 1rem;
+}
+
+.file-path {
+ background-color: #1a1a1a;
+ padding: 10px;
+ border-radius: 4px;
+ font-family: monospace;
+ margin: 15px 0;
+ word-break: break-all;
+ border: 1px solid #333;
+}
+
+.config-example {
+ background-color: #0a0a0a;
+ padding: 15px;
+ border-radius: 4px;
+ font-family: monospace;
+ margin: 15px 0;
+ overflow-x: auto;
+ border: 1px solid #333;
+ color: #e6e6e6;
+}
+
+.mt-4 {
+ margin-top: 20px;
}
\ No newline at end of file
diff --git a/src/local_deep_research/web/templates/api_keys_config.html b/src/local_deep_research/web/templates/api_keys_config.html
new file mode 100644
index 0000000000..24c5452746
--- /dev/null
+++ b/src/local_deep_research/web/templates/api_keys_config.html
@@ -0,0 +1,82 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Deep Research System - API Keys</title>
+ <link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/styles.css') }}">
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
+ <link rel="icon" type="image/png" href="{{ url_for('static', filename='favicon.ico') }}">
+</head>
+<body>
+ <div class="app-container">
+ <!-- Sidebar -->
+ <aside class="sidebar">
+ <!-- Sidebar content (keep as is) -->
+ </aside>
+
+ <!-- Main Content -->
+ <main class="main-content">
+ <div class="page active" id="api-keys-settings">
+ <div class="page-header">
+ <div class="results-header">
+ <h1>API Keys Configuration</h1>
+ <div class="results-actions">
+ <a href="{{ url_for('research.settings_page') }}" class="btn btn-outline">
+ <i class="fas fa-arrow-left"></i> Back to Settings
+ </a>
+ </div>
+ </div>
+ </div>
+
+ <div class="card">
+ <div class="card-content">
+ <h2>API Keys Configuration File</h2>
+ <p>To edit your API keys configuration, open this file with your preferred text editor. Note that files beginning with a dot or located in configuration directories may be hidden by default in your file explorer. You may need to enable "Show Hidden Files" in your file explorer settings to view it.</p>
+ <div class="file-path">{{ secrets_file_path }}</div>
+
+ <button onclick="openFileLocation('{{ secrets_file_path }}')" class="btn btn-primary">
+ <i class="fas fa-folder-open"></i> Open Containing Folder
+ </button>
+
+ <h3 class="mt-4">Configuration Example</h3>
+ <pre class="config-example">
+# API Keys for Deep Research System
+# This file contains sensitive information and should not be shared.
+
+# LLM Service API Keys
+ANTHROPIC_API_KEY = "your-anthropic-api-key-here"
+OPENAI_API_KEY = "your-openai-api-key-here"
+
+# Search Service API Keys
+GOOGLE_API_KEY = "your-google-api-key-here"
+SERP_API_KEY = "your-serp-api-key-here"
+GUARDIAN_API_KEY = "your-guardian-api-key-here"
+GOOGLE_PSE_API_KEY = "your-google-pse-api-key-here"
+GOOGLE_PSE_ENGINE_ID = "your-google-pse-engine-id-here"
+ </pre>
+ </div>
+ </div>
+ </div>
+ </main>
+ </div>
+
+ <script>
+ function openFileLocation(filePath) {
+ // Create a hidden form and submit it to a route that will open the file location
+ const form = document.createElement('form');
+ form.method = 'POST';
+ form.action = "{{ url_for('research.open_file_location') }}";
+
+ const input = document.createElement('input');
+ input.type = 'hidden';
+ input.name = 'file_path';
+ input.value = filePath;
+
+ form.appendChild(input);
+ document.body.appendChild(form);
+ form.submit();
+ }
+ </script>
+</body>
+</html>
\ No newline at end of file
diff --git a/src/local_deep_research/web/templates/collections_config.html b/src/local_deep_research/web/templates/collections_config.html
new file mode 100644
index 0000000000..1794b01ba4
--- /dev/null
+++ b/src/local_deep_research/web/templates/collections_config.html
@@ -0,0 +1,90 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Deep Research System - Local Collections</title>
+ <link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/styles.css') }}">
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
+ <link rel="icon" type="image/png" href="{{ url_for('static', filename='favicon.ico') }}">
+</head>
+<body>
+ <div class="app-container">
+ <!-- Sidebar -->
+ <aside class="sidebar">
+ <!-- Sidebar content (keep as is) -->
+ </aside>
+
+ <!-- Main Content -->
+ <main class="main-content">
+ <div class="page active" id="collections-settings">
+ <div class="page-header">
+ <div class="results-header">
+ <h1>Local Document Collections</h1>
+ <div class="results-actions">
+ <a href="{{ url_for('research.settings_page') }}" class="btn btn-outline">
+ <i class="fas fa-arrow-left"></i> Back to Settings
+ </a>
+ </div>
+ </div>
+ </div>
+
+ <div class="card">
+ <div class="card-content">
+ <h2>Local Collections Configuration File</h2>
+ <p>To edit your local collections configuration, open this file with your preferred text editor:</p>
+ <div class="file-path">{{ collections_file_path }}</div>
+
+ <button onclick="openFileLocation('{{ collections_file_path }}')" class="btn btn-primary">
+ <i class="fas fa-folder-open"></i> Open Containing Folder
+ </button>
+
+ <h3 class="mt-4">Default Configuration Example</h3>
+ <pre class="config-example">
+[project_docs]
+name = "Project Documents"
+description = "Project documentation and specifications"
+paths = ["/path/to/project_documents"]
+enabled = true
+embedding_model = "all-MiniLM-L6-v2"
+embedding_device = "cpu" # "cpu" or "cuda" for GPU
+embedding_model_type = "sentence_transformers"
+max_results = 20
+max_filtered_results = 5
+chunk_size = 1000
+chunk_overlap = 200
+cache_dir = ".cache/local_search/project_docs"
+
+# Default embedding settings for all collections
+[DEFAULT_EMBEDDING_SETTINGS]
+DEFAULT_EMBEDDING_MODEL = "all-MiniLM-L6-v2"
+DEFAULT_EMBEDDING_DEVICE = "cpu"
+DEFAULT_EMBEDDING_MODEL_TYPE = "sentence_transformers"
+FORCE_REINDEX = false
+CACHE_DIR = ".cache/local_search"
+ </pre>
+ </div>
+ </div>
+ </div>
+ </main>
+ </div>
+
+ <script>
+ function openFileLocation(filePath) {
+ // Create a hidden form and submit it to a route that will open the file location
+ const form = document.createElement('form');
+ form.method = 'POST';
+ form.action = "{{ url_for('research.open_file_location') }}";
+
+ const input = document.createElement('input');
+ input.type = 'hidden';
+ input.name = 'file_path';
+ input.value = filePath;
+
+ form.appendChild(input);
+ document.body.appendChild(form);
+ form.submit();
+ }
+ </script>
+</body>
+</html>
\ No newline at end of file
diff --git a/src/local_deep_research/web/templates/index.html b/src/local_deep_research/web/templates/index.html
index b98176995d..84acb18af0 100644
--- a/src/local_deep_research/web/templates/index.html
+++ b/src/local_deep_research/web/templates/index.html
@@ -25,7 +25,7 @@
</ul>
</nav>
<div class="sidebar-footer">
- <p>v0.0.1 | <i class="fas fa-brain"></i></p>
+ <p>v0.1.0 | <i class="fas fa-brain"></i></p>
</div>
</aside>
diff --git a/src/local_deep_research/web/templates/llm_config.html b/src/local_deep_research/web/templates/llm_config.html
new file mode 100644
index 0000000000..15da90a8c1
--- /dev/null
+++ b/src/local_deep_research/web/templates/llm_config.html
@@ -0,0 +1,120 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Deep Research System - LLM Settings</title>
+ <link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/styles.css') }}">
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
+ <link rel="icon" type="image/png" href="{{ url_for('static', filename='favicon.ico') }}">
+</head>
+<body>
+ <div class="app-container">
+ <!-- Sidebar -->
+ <aside class="sidebar">
+ <!-- Sidebar content (keep as is) -->
+ </aside>
+
+ <!-- Main Content -->
+ <main class="main-content">
+ <div class="page active" id="llm-settings">
+ <div class="page-header">
+ <div class="results-header">
+ <h1>Language Model Configuration</h1>
+ <div class="results-actions">
+ <a href="{{ url_for('research.settings_page') }}" class="btn btn-outline">
+ <i class="fas fa-arrow-left"></i> Back to Settings
+ </a>
+ </div>
+ </div>
+ </div>
+
+ <div class="card">
+ <div class="card-content">
+ <h2>LLM Configuration File</h2>
+ <p>To edit your LLM configuration, open this file with your preferred text editor:</p>
+ <div class="file-path">{{ llm_file_path }}</div>
+
+ <button onclick="openFileLocation('{{ llm_file_path }}')" class="btn btn-primary">
+ <i class="fas fa-folder-open"></i> Open Containing Folder
+ </button>
+
+ <h3 class="mt-4">Default Configuration Example</h3>
+ <pre class="config-example">
+"""
+LLM configuration for Local Deep Research.
+
+This file is loaded as a Python module, allowing for complex
+customization of LLM behavior.
+"""
+
+# Default model settings
+DEFAULT_MODEL = "mistral"
+DEFAULT_MODEL_TYPE = "ollama" # Options: ollama, openai, anthropic
+DEFAULT_TEMPERATURE = 0.7
+MAX_TOKENS = 30000
+
+# API keys and endpoints (consider using environment variables instead)
+USE_OPENAI_ENDPOINT = False
+OPENAI_ENDPOINT_URL = "https://openrouter.ai/api/v1"
+OPENAI_ENDPOINT_REQUIRES_MODEL = True
+
+# Custom model loading function
+def get_llm(model_name=None, model_type=None, temperature=None, **kwargs):
+ """
+ Get a language model instance.
+
+ Args:
+ model_name: Name of the model to use
+ model_type: Type of model provider
+ temperature: Model temperature
+ **kwargs: Additional parameters
+
+ Returns:
+ A LangChain language model instance
+ """
+ # Use defaults if not provided
+ model_name = model_name or DEFAULT_MODEL
+ model_type = model_type or DEFAULT_MODEL_TYPE
+ temperature = temperature or DEFAULT_TEMPERATURE
+
+ # If using Ollama
+ if model_type == "ollama":
+ from langchain_ollama import ChatOllama
+ return ChatOllama(
+ model=model_name,
+ temperature=temperature,
+ **kwargs
+ )
+
+ # Default fallback
+ from langchain_ollama import ChatOllama
+ return ChatOllama(
+ model="mistral",
+ temperature=0.7,
+ **kwargs
+ )
+ </pre>
+ </div>
+ </div>
+ </div>
+ </main>
+ </div>
+
+ <script>
+ function openFileLocation(path) {
+ fetch('/research/open_file_location', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
+ body: 'file_path=' + encodeURIComponent(path)
+ })
+ .then(response => {
+ // Handle response
+ })
+ .catch(error => console.error('Error:', error));
+ }
+ </script>
+</body>
+</html>
\ No newline at end of file
diff --git a/src/local_deep_research/web/templates/main_config.html b/src/local_deep_research/web/templates/main_config.html
new file mode 100644
index 0000000000..035b4cf651
--- /dev/null
+++ b/src/local_deep_research/web/templates/main_config.html
@@ -0,0 +1,89 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Deep Research System - Search Settings</title>
+ <link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/styles.css') }}">
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
+ <link rel="icon" type="image/png" href="{{ url_for('static', filename='favicon.ico') }}">
+</head>
+<body>
+ <div class="app-container">
+ <!-- Sidebar -->
+ <aside class="sidebar">
+ <!-- Sidebar content (keep as is) -->
+ </aside>
+
+ <!-- Main Content -->
+ <main class="main-content">
+ <div class="page active" id="settings">
+ <div class="page-header">
+ <div class="results-header">
+ <h1>Search Settings</h1>
+ <div class="results-actions">
+ <a href="{{ url_for('research.settings_page') }}" class="btn btn-outline">
+ <i class="fas fa-arrow-left"></i> Back to Settings
+ </a>
+ </div>
+ </div>
+ </div>
+
+ <div class="card">
+ <div class="card-content">
+ <h2>Main Configuration File</h2>
+ <p>To edit your main configuration, open this file with your preferred text editor:</p>
+ <div class="file-path">{{ main_file_path }}</div>
+
+ <button onclick="openFileLocation('{{ main_file_path }}')" class="btn btn-primary">
+ <i class="fas fa-folder-open"></i> Open Containing Folder
+ </button>
+
+ <h3 class="mt-4">Default Configuration Example</h3>
+ <pre class="config-example">
+[general]
+output_dir = "research_outputs"
+knowledge_accumulation = "ITERATION"
+knowledge_accumulation_context_limit = 500000
+enable_fact_checking = true
+
+[search]
+tool = "auto"
+iterations = 3
+questions_per_iteration = 3
+searches_per_section = 2
+max_results = 10
+max_filtered_results = 5
+region = "us"
+time_period = "a"
+search_language = "en"
+safe_search = true
+quality_check_urls = true
+snippets_only = false
+skip_relevance_filter = false
+ </pre>
+ </div>
+ </div>
+ </div>
+ </main>
+ </div>
+
+ <script>
+ function openFileLocation(filePath) {
+ // Create a hidden form and submit it to a route that will open the file location
+ const form = document.createElement('form');
+ form.method = 'POST';
+ form.action = "{{ url_for('research.open_file_location') }}";
+
+ const input = document.createElement('input');
+ input.type = 'hidden';
+ input.name = 'file_path';
+ input.value = filePath;
+
+ form.appendChild(input);
+ document.body.appendChild(form);
+ form.submit();
+ }
+ </script>
+</body>
+</html>
\ No newline at end of file
diff --git a/src/local_deep_research/web/templates/settings.html b/src/local_deep_research/web/templates/settings.html
index 34a32bc75f..e084103e45 100644
--- a/src/local_deep_research/web/templates/settings.html
+++ b/src/local_deep_research/web/templates/settings.html
@@ -78,6 +78,9 @@
font-size: 0.9rem;
color: #e6e6e6;
white-space: pre;
+ min-height: 200px;
+ max-height: 600px;
+ border: 1px solid #333;
}
.toggle-raw-config {
cursor: pointer;
@@ -85,20 +88,65 @@
align-items: center;
gap: 0.5rem;
margin-top: 2rem;
+ margin-bottom: 1rem;
color: #4a6cf7;
font-weight: 500;
+ padding: 0.5rem 1rem;
+ background-color: rgba(74, 108, 247, 0.1);
+ border-radius: 4px;
+ width: fit-content;
+ }
+ .toggle-raw-config:hover {
+ background-color: rgba(74, 108, 247, 0.2);
}
.config-raw-editor {
- background-color: #0a0a0a;
- color: #e6e6e6;
- font-family: monospace;
- font-size: 0.9rem;
- padding: 1rem;
- border: 1px solid #333;
- border-radius: 4px;
- width: 100%;
- resize: vertical;
- }
+ background-color: #0a0a0a;
+ color: #e6e6e6;
+ font-family: monospace;
+ font-size: 0.9rem;
+ padding: 1rem;
+ border: 1px solid #333;
+ border-radius: 4px;
+ width: 100%;
+ min-height: 400px;
+ resize: vertical;
+ display: block !important;
+ }
+ .alert {
+ padding: 0.75rem 1.25rem;
+ margin-bottom: 1rem;
+ border: 1px solid transparent;
+ border-radius: 0.25rem;
+ }
+ .alert-success {
+ color: #d4edda;
+ background-color: #1e462e;
+ border-color: #c3e6cb;
+ }
+ .alert-error {
+ color: #f8d7da;
+ background-color: #462c2e;
+ border-color: #f5c6cb;
+ }
+ .editor-header {
+ background-color: var(--bg-tertiary);
+ padding: 0.75rem 1rem;
+ border-bottom: 1px solid var(--border-color);
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ }
+ .editor-header h3 {
+ margin: 0;
+ font-size: 1rem;
+ color: var(--text-primary);
+ }
+ .editor-lang {
+ background-color: var(--accent-primary);
+ font-size: 0.8rem;
+ padding: 0.25rem 0.5rem;
+ border-radius: 4px;
+ }
</style>
</head>
<body>
@@ -126,6 +174,17 @@
<div class="page-header">
<h1>Settings</h1>
</div>
+
+ {% with messages = get_flashed_messages(with_categories=true) %}
+ {% if messages %}
+ {% for category, message in messages %}
+ <div class="alert alert-{{ category }}">
+ {{ message }}
+ </div>
+ {% endfor %}
+ {% endif %}
+ {% endwith %}
+
<div class="card">
<div class="card-content">
<form method="POST" action="{{ url_for('research.settings_page') }}">
@@ -257,7 +316,7 @@
<div class="form-group">
<label for="KNOWLEDGE_ACCUMULATION_CONTEXT_LIMIT">Knowledge Accumulation Context Limit</label>
- <input type="number" min="1000" max="10000000" step="10000" class="form-control" id="KNOWLEDGE_ACCUMULATION_CONTEXT_LIMIT" name="KNOWLEDGE_ACCUMULATION_CONTEXT_LIMIT" value="{{ config.KNOWLEDGE_ACCUMULATION_CONTEXT_LIMIT }}">
+ <input type="number" class="form-control" id="KNOWLEDGE_ACCUMULATION_CONTEXT_LIMIT" name="KNOWLEDGE_ACCUMULATION_CONTEXT_LIMIT" value="{{ config.KNOWLEDGE_ACCUMULATION_CONTEXT_LIMIT }}">
<span class="input-help">Maximum context size for knowledge accumulation</span>
</div>
@@ -272,7 +331,7 @@
<select id="TIME_PERIOD" name="TIME_PERIOD" class="form-control">
<option value="d" {% if config.TIME_PERIOD == "d" %}selected{% endif %}>Past day</option>
<option value="w" {% if config.TIME_PERIOD == "w" %}selected{% endif %}>Past week</option>
- <option value "m" {% if config.TIME_PERIOD == "m" %}selected{% endif %}>Past month</option>
+ <option value="m" {% if config.TIME_PERIOD == "m" %}selected{% endif %}>Past month</option>
<option value="y" {% if config.TIME_PERIOD == "y" %}selected{% endif %}>Past year</option>
<option value="a" {% if config.TIME_PERIOD == "a" %}selected{% endif %}>All time</option>
</select>
@@ -340,16 +399,19 @@
</div>
<div id="raw-config" class="config-raw" style="display: none;">
- {{ raw_config|safe }}
+ {{ raw_config|safe }}
</div>
+
<!-- Raw Configuration Editing -->
- <div class="settings-section">
- <h2><i class="fas fa-code"></i> Raw Configuration</h2>
- <div class="form-group">
- <textarea id="raw_config_editor" name="raw_config_editor" class="form-control config-raw-editor" rows="20">{{ raw_config|safe }}</textarea>
+ <div id="raw-config-editor-container" style="display: none; margin-top: 1rem;">
+ <div class="editor-header">
+ <h3>Edit Raw Configuration</h3>
+ <span class="editor-lang">TOML</span>
</div>
+ <textarea id="raw_config_editor" name="raw_config_editor" class="config-raw-editor" rows="20">{{ raw_config|safe }}</textarea>
<div class="form-actions">
<button type="button" class="btn btn-primary" onclick="saveRawConfig()"><i class="fas fa-save"></i> Save Raw Configuration</button>
+ <button type="button" class="btn btn-outline" onclick="cancelRawEdit()"><i class="fas fa-times"></i> Cancel</button>
</div>
</div>
</div>
@@ -404,37 +466,54 @@
// Toggle raw configuration display
function toggleRawConfig() {
const rawConfig = document.getElementById('raw-config');
+ const editorContainer = document.getElementById('raw-config-editor-container');
const toggleText = document.getElementById('toggle-text');
+
if (rawConfig.style.display === 'none') {
rawConfig.style.display = 'block';
+ editorContainer.style.display = 'block';
toggleText.textContent = 'Hide Raw Configuration';
} else {
rawConfig.style.display = 'none';
+ editorContainer.style.display = 'none';
toggleText.textContent = 'Show Raw Configuration';
}
}
+
+ function cancelRawEdit() {
+ const rawConfig = document.getElementById('raw-config');
+ const editorContainer = document.getElementById('raw-config-editor-container');
+ const toggleText = document.getElementById('toggle-text');
+
+ rawConfig.style.display = 'none';
+ editorContainer.style.display = 'none';
+ toggleText.textContent = 'Show Raw Configuration';
+ }
+
function saveRawConfig() {
- const rawConfig = document.getElementById('raw_config_editor').value;
-
- fetch('{{ url_for("research.save_raw_config") }}', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({ raw_config: rawConfig }),
- })
- .then(response => response.json())
- .then(data => {
- if (data.success) {
- alert('Configuration saved successfully. You may need to restart the application for changes to take effect.');
- } else {
- alert('Error saving configuration: ' + data.error);
+ const rawConfig = document.getElementById('raw_config_editor').value;
+
+ fetch('{{ url_for("research.save_raw_config") }}', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({ raw_config: rawConfig }),
+ })
+ .then(response => response.json())
+ .then(data => {
+ if (data.success) {
+ alert('Configuration saved successfully. You may need to restart the application for changes to take effect.');
+ // Reload the page to show updated values
+ window.location.reload();
+ } else {
+ alert('Error saving configuration: ' + data.error);
+ }
+ })
+ .catch(error => {
+ alert('Error saving configuration: ' + error);
+ });
}
- })
- .catch(error => {
- alert('Error saving configuration: ' + error);
- });
-}
</script>
</body>
</html>
\ No newline at end of file
diff --git a/src/local_deep_research/web/templates/settings_dashboard.html b/src/local_deep_research/web/templates/settings_dashboard.html
new file mode 100644
index 0000000000..7b2ece5576
--- /dev/null
+++ b/src/local_deep_research/web/templates/settings_dashboard.html
@@ -0,0 +1,191 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Deep Research System - Settings</title>
+ <link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/styles.css') }}">
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
+ <link rel="icon" type="image/png" href="{{ url_for('static', filename='favicon.ico') }}">
+ <style>
+ .settings-cards {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
+ gap: 1.5rem;
+ margin-top: 1.5rem;
+ }
+ .settings-card {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ }
+ .settings-card .card-content {
+ display: flex;
+ flex-direction: column;
+ flex: 1;
+ }
+ .settings-icon {
+ font-size: 2rem;
+ color: var(--accent-primary);
+ margin-bottom: 1rem;
+ text-align: center;
+ }
+ .settings-title {
+ font-size: 1.25rem;
+ font-weight: 600;
+ margin-bottom: 0.75rem;
+ color: var(--text-primary);
+ }
+ .settings-description {
+ color: var(--text-secondary);
+ margin-bottom: 1.5rem;
+ flex: 1;
+ }
+ .card-actions {
+ margin-top: auto;
+ text-align: center;
+ }
+ </style>
+</head>
+<body>
+ <div class="app-container">
+ <!-- Sidebar -->
+ <aside class="sidebar">
+ <div class="sidebar-header">
+ <h2 id="logo-link" style="cursor: pointer;"><i class="fas fa-atom"></i> Deep Research</h2>
+ </div>
+ <nav class="sidebar-nav">
+ <ul>
+ <li data-page="new-research"><i class="fas fa-search"></i> <a href="{{ url_for('research.index') }}">New Research</a></li>
+ <li data-page="history"><i class="fas fa-history"></i> <a href="{{ url_for('research.index') }}#history">History</a></li>
+ <li class="active" data-page="settings"><i class="fas fa-cog"></i> Settings</li>
+ </ul>
+ </nav>
+ <div class="sidebar-footer">
+ <p>v0.1.0 | <i class="fas fa-brain"></i></p>
+ </div>
+ </aside>
+
+ <!-- Main Content -->
+ <main class="main-content">
+ <div class="page active" id="settings">
+ <div class="page-header">
+ <h1>Settings</h1>
+ </div>
+
+ {% with messages = get_flashed_messages(with_categories=true) %}
+ {% if messages %}
+ {% for category, message in messages %}
+ <div class="alert alert-{{ category }}">
+ {{ message }}
+ </div>
+ {% endfor %}
+ {% endif %}
+ {% endwith %}
+
+ <div class="settings-cards">
+ <!-- Main Configuration Card -->
+ <div class="card settings-card">
+ <div class="card-content">
+ <div class="settings-icon">
+ <i class="fas fa-search"></i>
+ </div>
+ <h3 class="settings-title">Search Settings</h3>
+ <p class="settings-description">
+ Configure search parameters, results limits, general behavior, and output settings for the research system.
+ </p>
+ <div class="card-actions">
+ <a href="{{ url_for('research.main_config_page') }}" class="btn btn-primary">
+ <i class="fas fa-cog"></i> Configure
+ </a>
+ </div>
+ </div>
+ </div>
+
+ <!-- LLM Configuration Card -->
+ <div class="card settings-card">
+ <div class="card-content">
+ <div class="settings-icon">
+ <i class="fas fa-brain"></i>
+ </div>
+ <h3 class="settings-title">Language Model Settings</h3>
+ <p class="settings-description">
+ Set up the language models used for research, including model selection, parameters, and API settings.
+ </p>
+ <div class="card-actions">
+ <a href="{{ url_for('research.llm_config_page') }}" class="btn btn-primary">
+ <i class="fas fa-code"></i> Edit Configuration
+ </a>
+ </div>
+ </div>
+ </div>
+
+ <!-- Local Collections Card -->
+ <div class="card settings-card">
+ <div class="card-content">
+ <div class="settings-icon">
+ <i class="fas fa-folder"></i>
+ </div>
+ <h3 class="settings-title">Local Document Collections</h3>
+ <p class="settings-description">
+ Configure local document collections to search through your own files, papers, and research materials.
+ </p>
+ <div class="card-actions">
+ <a href="{{ url_for('research.collections_config_page') }}" class="btn btn-primary">
+ <i class="fas fa-code"></i> Edit Configuration
+ </a>
+ </div>
+ </div>
+ </div>
+
+ <div class="card settings-card">
+ <div class="card-content">
+ <div class="settings-icon">
+ <i class="fas fa-key"></i>
+ </div>
+ <h3 class="settings-title">API Keys</h3>
+ <p class="settings-description">
+ Configure API keys for external services like OpenAI, Anthropic, and search providers.
+ </p>
+ <div class="card-actions">
+ <a href="{{ url_for('research.api_keys_config_page') }}" class="btn btn-primary">
+ <i class="fas fa-cog"></i> Configure
+ </a>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </main>
+ </div>
+
+ <!-- Mobile Tab Bar -->
+ <nav class="mobile-tab-bar">
+ <ul>
+ <li data-page="new-research">
+ <a href="{{ url_for('research.index') }}">
+ <i class="fas fa-search"></i>
+ <span>Research</span>
+ </a>
+ </li>
+ <li data-page="history">
+ <a href="{{ url_for('research.index') }}#history">
+ <i class="fas fa-history"></i>
+ <span>History</span>
+ </a>
+ </li>
+ <li class="active" data-page="settings">
+ <i class="fas fa-cog"></i>
+ <span>Settings</span>
+ </li>
+ </ul>
+ </nav>
+
+ <script>
+ // Make the logo clickable to go back to home
+ document.getElementById('logo-link').addEventListener('click', function() {
+ window.location.href = "{{ url_for('research.index') }}";
+ });
+ </script>
+</body>
+</html>