~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
Add custom context window size setting (Fix #241)
LearningCircuita29fd6220a68
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.pyindex e00fb38541..a18a880f17 100644--- a/src/local_deep_research/config/llm_config.py+++ b/src/local_deep_research/config/llm_config.py@@ -74,8 +74,16 @@ def get_llm(model_name=None, temperature=None, provider=None, openai_endpoint_urcommon_params = {"temperature": temperature,}++ # Get context window size from settings+ context_window_size = get_db_setting("llm.context_window_size", 32000)+if get_db_setting("llm.supports_max_tokens", True):- common_params["max_tokens"] = get_db_setting("llm.max_tokens", 30000)+ # Use 80% of context window to leave room for prompts+ max_tokens = min(+ get_db_setting("llm.max_tokens", 30000), int(context_window_size * 0.8)+ )+ common_params["max_tokens"] = max_tokens# Handle different providersif provider == "anthropic":@@ -212,7 +220,7 @@ def get_llm(model_name=None, temperature=None, provider=None, openai_endpoint_urapi_key="lm-studio", # LM Studio doesn't require a real API keybase_url=f"{lmstudio_url}/v1", # Use the configured URL with /v1 endpointtemperature=temperature,- max_tokens=get_db_setting("llm.max_tokens", 30000),+ max_tokens=max_tokens, # Use calculated max_tokens based on context size)return wrap_llm_without_think_tags(llm)@@ -254,10 +262,11 @@ def get_llm(model_name=None, temperature=None, provider=None, openai_endpoint_urllm = LlamaCpp(model_path=model_path,temperature=temperature,- max_tokens=get_db_setting("llm.max_tokens", 30000),+ max_tokens=max_tokens, # Use calculated max_tokensn_gpu_layers=n_gpu_layers,n_batch=n_batch,f16_kv=f16_kv,+ n_ctx=context_window_size, # Set context window size directlyverbose=True,)diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.jsonindex a8907523e5..94ac886871 100644--- a/src/local_deep_research/defaults/default_settings.json+++ b/src/local_deep_research/defaults/default_settings.json@@ -194,6 +194,20 @@"value": 30000,"visible": true},+ "llm.context_window_size": {+ "category": "llm_parameters",+ "description": "Maximum context window size in tokens for the LLM",+ "editable": true,+ "max_value": 128000.0,+ "min_value": 512.0,+ "name": "Context Window Size",+ "options": null,+ "step": null,+ "type": "LLM",+ "ui_element": "number",+ "value": 32000,+ "visible": true+ },"llm.supports_max_tokens": {"category": "llm_parameters","description": "Whether the LLM API supports the 'max_tokens' option.",diff --git a/tests/feature_tests/IMPLEMENTATION_GUIDE_241.md b/tests/feature_tests/IMPLEMENTATION_GUIDE_241.mdnew file mode 100644index 0000000000..3579452600--- /dev/null+++ b/tests/feature_tests/IMPLEMENTATION_GUIDE_241.md@@ -0,0 +1,114 @@+# Implementation Guide for Custom Context Window Size++This document outlines the steps to implement the custom context window size feature requested in issue #241.++## Background++Users have reported issues with models that have smaller context windows (like some Llama.cpp and LM Studio models) failing because the default token limit (30,000) exceeds their capabilities.++Issue: [Custom context size #241](https://github.com/LearningCircuit/local-deep-research/issues/241)++## Implementation Steps++### 1. Add New Setting++Add a new setting in the default settings JSON file:++```json+"llm.context_window_size": {+ "category": "llm_parameters",+ "description": "Maximum context window size in tokens for the LLM",+ "editable": true,+ "max_value": 128000.0,+ "min_value": 512.0,+ "name": "Context Window Size",+ "options": null,+ "step": null,+ "type": "LLM",+ "ui_element": "number",+ "value": 32000,+ "visible": true+}+```++### 2. Modify the LLM Configuration++Update the `get_llm` function in `src/local_deep_research/config/llm_config.py`:++1. Add context window size to common parameters:++```python+# Common parameters for all models+common_params = {+ "temperature": temperature,+}++# Get context window size from settings+context_window_size = get_db_setting("llm.context_window_size", 32000)++# Ensure max_tokens doesn't exceed context window size+if get_db_setting("llm.supports_max_tokens", True):+ # Use 80% of context window to leave room for prompts+ max_tokens = min(get_db_setting("llm.max_tokens", 30000), int(context_window_size * 0.8))+ common_params["max_tokens"] = max_tokens+```++2. Add specific handling for models that need context window size parameter:++For example, in the LlamaCpp section:++```python+# For LlamaCpp, also set context size directly if supported+if hasattr(LlamaCpp, "n_ctx"): # Check if the parameter exists+ llm = LlamaCpp(+ model_path=model_path,+ temperature=temperature,+ max_tokens=max_tokens,+ n_gpu_layers=n_gpu_layers,+ n_batch=n_batch,+ f16_kv=f16_kv,+ n_ctx=context_window_size, # Set context window size+ verbose=True,+ )+```++### 3. Update UI to Make Context Size Visible++The UI should already display the setting once it's added to the default settings JSON.++### 4. Update Documentation++Add documentation explaining:++1. What the context window size setting does+2. How it affects different model providers+3. Recommended values for common models++## Testing Approach++1. Test with different providers (especially Llama.cpp and LM Studio)+2. Verify models with smaller context windows work correctly+3. Ensure max_tokens is calculated correctly based on context window size+4. Check for any regressions in models that worked previously++## Impact Assessment++This change:+- Allows users to customize context window size for their specific models+- Helps prevent errors when using models with smaller context windows+- Makes the software more adaptable to different LLM capabilities+- Is backwards compatible with existing configurations++## Example Usage++Example user workflow:+1. User sets up a Llama.cpp model with 4K context window size+2. User changes the context window size setting to 4096+3. System automatically adjusts max_tokens to 3277 (80% of 4096)+4. Model works properly without "context too long" errors++## Potential Future Enhancements++1. Auto-detection of model context window size+2. Provider-specific context window settings+3. Dynamic adjustment based on model characteristicsdiff --git a/tests/feature_tests/README.md b/tests/feature_tests/README.mdnew file mode 100644index 0000000000..7672c6749d--- /dev/null+++ b/tests/feature_tests/README.md@@ -0,0 +1,26 @@+# Feature Tests++This directory contains test scripts for potential features and improvements before they are fully implemented.++## Available Tests++### test_custom_context.py++Tests the implementation of a custom context window size setting for LLMs (issue #241).++**Purpose:**+- Verify that we can correctly apply a custom context window size to various LLM providers+- Test the calculation of appropriate max_tokens values based on context window size+- Identify any potential issues with implementation++**How to run:**+```bash+cd local-deep-research+source ../venv/bin/activate # Or your virtual environment path+python tests/feature_tests/test_custom_context.py+```++**What it demonstrates:**+This test simulates adding a `llm.context_window_size` setting that would allow users to specify the context window size of their model. This is especially useful for custom models like Llama.cpp and LM Studio where the default 30000 tokens might exceed the model's capabilities.++The test patches the settings system to include the new setting, then demonstrates how max_tokens would be calculated based on the specified context window size.diff --git a/tests/feature_tests/__init__.py b/tests/feature_tests/__init__.pynew file mode 100644index 0000000000..897f1f4826--- /dev/null+++ b/tests/feature_tests/__init__.py@@ -0,0 +1,5 @@+"""Feature tests package for local-deep-research.++This package contains tests for potential features and improvements+before they are fully implemented.+"""diff --git a/tests/feature_tests/test_custom_context.py b/tests/feature_tests/test_custom_context.pynew file mode 100644index 0000000000..eed5d1691b--- /dev/null+++ b/tests/feature_tests/test_custom_context.py@@ -0,0 +1,139 @@+"""+Test script to validate custom context window size setting.++This script tests if we can set a custom context window size for different model providers.+It simulates the fix for issue #241: https://github.com/LearningCircuit/local-deep-research/issues/241+"""++import logging+import sys+from pathlib import Path+from typing import Any, Dict, Optional++# Configure logging+logging.basicConfig(level=logging.INFO)+logger = logging.getLogger(__name__)++# Add the src directory to the path before importing project modules+src_path = str(Path(__file__).parent.parent.parent / "src")+if src_path not in sys.path:+ sys.path.insert(0, src_path)+++def patch_db_setting():+ """+ Patch the get_db_setting function to override certain settings.+ This simulates what would happen if we added a context_window_size setting.+ """+ # Import here to avoid module level import issues+ from local_deep_research.utilities.db_utils import get_db_setting++ original_get_db_setting = get_db_setting+ settings_override = {+ "llm.context_window_size": 8192, # Custom context window size setting+ }++ def patched_get_db_setting(key: str, default_value: Any = None) -> Any:+ """Override specific settings for testing"""+ if key in settings_override:+ return settings_override[key]+ return original_get_db_setting(key, default_value)++ # Apply the patch+ import local_deep_research.utilities.db_utils++ local_deep_research.utilities.db_utils.get_db_setting = patched_get_db_setting++ # Also patch the llm_config module+ import local_deep_research.config.llm_config++ local_deep_research.config.llm_config.get_db_setting = patched_get_db_setting++ return patched_get_db_setting+++def modify_llm_creation(provider: str, model_name: Optional[str] = None) -> Dict:+ """+ Simulate creating an LLM with a custom context window size setting.++ Args:+ provider: The LLM provider to use+ model_name: Optional model name to use++ Returns:+ Dict containing configuration used+ """+ # Import here to avoid module level import issues+ from local_deep_research.utilities.db_utils import get_db_setting++ # Get context window size from settings+ context_window_size = get_db_setting("llm.context_window_size", 32000)++ # Get current max_tokens setting+ max_tokens = get_db_setting("llm.max_tokens", 30000)++ logger.info(f"Provider: {provider}")+ logger.info(f"Context window size from settings: {context_window_size}")+ logger.info(f"Current max_tokens setting: {max_tokens}")++ # Calculate new max_tokens based on context window size+ # In a real implementation, this would ensure max_tokens doesn't exceed the model's context window+ new_max_tokens = min(max_tokens, int(context_window_size * 0.8))+ logger.info(f"Adjusted max_tokens would be: {new_max_tokens}")++ # For certain providers, this is especially important+ if provider in ["llamacpp", "lmstudio", "ollama"]:+ logger.info(+ f"Provider {provider} would particularly benefit from custom context size"+ )++ # This would actually create the LLM with adjusted max_tokens in the real implementation+ # from local_deep_research.config.llm_config import get_llm+ # llm = get_llm(provider=provider, model_name=model_name)++ return {+ "provider": provider,+ "model_name": model_name,+ "context_window_size": context_window_size,+ "original_max_tokens": max_tokens,+ "adjusted_max_tokens": new_max_tokens,+ }+++def test_custom_context_size():+ """+ Test custom context window size for different providers.+ """+ # Import here to avoid module level import issues+ from local_deep_research.config.llm_config import get_available_providers++ # Apply the patch to simulate new setting+ patch_db_setting()++ # Get available providers+ providers = get_available_providers()+ logger.info(f"Available providers: {list(providers.keys())}")++ # Test each provider+ results = {}+ for provider in providers:+ logger.info(f"\nTesting provider: {provider}")+ try:+ result = modify_llm_creation(provider)+ results[provider] = result+ except Exception as e:+ logger.error(f"Error testing provider {provider}: {str(e)}")+ results[provider] = {"error": str(e)}++ # Show summary+ logger.info("\n\n=== TEST RESULTS ===")+ for provider, result in results.items():+ status = "✓" if "error" not in result else "✗"+ logger.info(f"{status} {provider}: {result}")++ return results+++if __name__ == "__main__":+ logger.info("Testing custom context window size functionality")+ test_custom_context_size()