~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
feat: Add adaptive rate limiting for LLM API calls
LearningCircuitf47617192518
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.pyindex f9eac9cbfd..1c7ec7ac06 100644--- a/src/local_deep_research/config/llm_config.py+++ b/src/local_deep_research/config/llm_config.py@@ -589,6 +589,16 @@ def wrap_llm_without_think_tags():"""Create a wrapper class that processes LLM outputs with remove_think_tags and token counting"""+ # First apply rate limiting if enabled+ from ..web_search_engines.rate_limiting.llm import (+ create_rate_limited_llm_wrapper,+ )+ from ..utilities.db_utils import get_db_setting++ # Check if LLM rate limiting is enabled (independent of search rate limiting)+ if get_db_setting("rate_limiting.llm_enabled", False):+ llm = create_rate_limited_llm_wrapper(llm, provider)+# Import token counting functionality if research_id is providedcallbacks = []if research_id is not None:diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.jsonindex a80382baa3..c151b43d38 100644--- a/src/local_deep_research/defaults/default_settings.json+++ b/src/local_deep_research/defaults/default_settings.json@@ -4502,6 +4502,20 @@"value": 0.95,"visible": true},+ "rate_limiting.llm_enabled": {+ "category": "rate_limiting",+ "description": "Enable adaptive rate limiting for LLM API calls (e.g., for free tier APIs with request limits)",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Enable LLM Rate Limiting",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": false,+ "visible": true+ },"benchmark.evaluation.provider": {"category": "benchmark","description": "Provider for benchmark evaluation model",diff --git a/src/local_deep_research/error_handling/error_reporter.py b/src/local_deep_research/error_handling/error_reporter.pyindex 8fa4061648..061c1d9d4c 100644--- a/src/local_deep_research/error_handling/error_reporter.py+++ b/src/local_deep_research/error_handling/error_reporter.py@@ -16,6 +16,7 @@ class ErrorCategory(Enum):SEARCH_ERROR = "search_error"SYNTHESIS_ERROR = "synthesis_error"FILE_ERROR = "file_error"+ RATE_LIMIT_ERROR = "rate_limit_error"UNKNOWN_ERROR = "unknown_error"@@ -52,11 +53,24 @@ class ErrorReporter:r"No auth credentials found",r"401.*API key",],+ ErrorCategory.RATE_LIMIT_ERROR: [+ r"429.*resource.*exhausted",+ r"429.*too many requests",+ r"rate limit",+ r"rate_limit",+ r"ratelimit",+ r"quota.*exceeded",+ r"resource.*exhausted.*quota",+ r"threshold.*requests",+ r"LLM rate limit",+ r"API rate limit",+ r"maximum.*requests.*minute",+ r"maximum.*requests.*hour",+ ],ErrorCategory.SEARCH_ERROR: [r"Search.*failed",r"No search results",r"Search engine.*error",- r"Rate limit.*exceeded",r"The search is longer than 256 characters",r"Failed to create search engine",r"could not be found",@@ -120,6 +134,7 @@ class ErrorReporter:ErrorCategory.SEARCH_ERROR: "Search Service Error",ErrorCategory.SYNTHESIS_ERROR: "Report Generation Error",ErrorCategory.FILE_ERROR: "File System Error",+ ErrorCategory.RATE_LIMIT_ERROR: "API Rate Limit Exceeded",ErrorCategory.UNKNOWN_ERROR: "Unexpected Error",}return titles.get(category, "Error")@@ -167,6 +182,13 @@ class ErrorReporter:"Try changing the output directory","Restart the application",],+ ErrorCategory.RATE_LIMIT_ERROR: [+ "The API has reached its rate limit",+ "Enable LLM Rate Limiting in Settings → Rate Limiting → Enable LLM Rate Limiting",+ "Once enabled, the system will automatically learn and adapt to API limits",+ "Consider upgrading to a paid API plan for higher limits",+ "Try using a different model temporarily",+ ],ErrorCategory.UNKNOWN_ERROR: ["Check the detailed logs below for more information","Try running the research again",@@ -219,6 +241,7 @@ class ErrorReporter:ErrorCategory.SEARCH_ERROR: "medium",ErrorCategory.SYNTHESIS_ERROR: "low", # Can often show partial resultsErrorCategory.FILE_ERROR: "medium",+ ErrorCategory.RATE_LIMIT_ERROR: "medium", # Can be resolved with settingsErrorCategory.UNKNOWN_ERROR: "high",}return severity_map.get(category, "medium")@@ -231,6 +254,7 @@ class ErrorReporter:ErrorCategory.SEARCH_ERROR: True,ErrorCategory.SYNTHESIS_ERROR: True,ErrorCategory.FILE_ERROR: True,+ ErrorCategory.RATE_LIMIT_ERROR: True, # Can enable rate limitingErrorCategory.UNKNOWN_ERROR: False,}return recoverable.get(category, False)diff --git a/src/local_deep_research/web_search_engines/rate_limiting/llm/__init__.py b/src/local_deep_research/web_search_engines/rate_limiting/llm/__init__.pynew file mode 100644index 0000000000..503ec28035--- /dev/null+++ b/src/local_deep_research/web_search_engines/rate_limiting/llm/__init__.py@@ -0,0 +1,11 @@+"""+LLM-specific rate limiting module.+"""++from .wrapper import create_rate_limited_llm_wrapper+from .detection import is_llm_rate_limit_error++__all__ = [+ "create_rate_limited_llm_wrapper",+ "is_llm_rate_limit_error",+]diff --git a/src/local_deep_research/web_search_engines/rate_limiting/llm/detection.py b/src/local_deep_research/web_search_engines/rate_limiting/llm/detection.pynew file mode 100644index 0000000000..a0f53e3ca0--- /dev/null+++ b/src/local_deep_research/web_search_engines/rate_limiting/llm/detection.py@@ -0,0 +1,112 @@+"""+LLM-specific rate limit error detection.+"""++import logging++logger = logging.getLogger(__name__)+++def is_llm_rate_limit_error(error: Exception) -> bool:+ """+ Detect if an error is a rate limit error from an LLM provider.++ Args:+ error: The exception to check++ Returns:+ True if this is a rate limit error, False otherwise+ """+ error_str = str(error).lower()+ error_type = type(error).__name__.lower()++ # Check for explicit HTTP 429 status codes+ if hasattr(error, "response") and hasattr(error.response, "status_code"):+ if error.response.status_code == 429:+ logger.debug(f"Detected HTTP 429 rate limit error: {error}")+ return True++ # Check for common rate limit error messages+ rate_limit_indicators = [+ "rate limit",+ "rate_limit",+ "ratelimit",+ "too many requests",+ "quota exceeded",+ "quota has been exhausted",+ "resource has been exhausted",+ "429",+ "threshold",+ "try again later",+ "slow down",+ ]++ if any(indicator in error_str for indicator in rate_limit_indicators):+ logger.debug(f"Detected rate limit error from message: {error}")+ return True++ # Check for specific provider error types+ if "ratelimiterror" in error_type or "quotaexceeded" in error_type:+ logger.debug(f"Detected rate limit error from type: {type(error)}")+ return True++ # Check for OpenAI specific rate limit errors+ if hasattr(error, "__class__") and error.__class__.__module__ == "openai":+ if error_type in ["ratelimiterror", "apierror"] and "429" in error_str:+ logger.debug(f"Detected OpenAI rate limit error: {error}")+ return True++ # Check for Anthropic specific rate limit errors+ if (+ hasattr(error, "__class__")+ and "anthropic" in error.__class__.__module__+ ):+ if any(x in error_str for x in ["rate_limit", "429", "too many"]):+ logger.debug(f"Detected Anthropic rate limit error: {error}")+ return True++ return False+++def extract_retry_after(error: Exception) -> float:+ """+ Extract retry-after time from rate limit error if available.++ Args:+ error: The rate limit error++ Returns:+ Retry after time in seconds, or 0 if not found+ """+ # Check for Retry-After header in response+ if hasattr(error, "response") and hasattr(error.response, "headers"):+ retry_after = error.response.headers.get("Retry-After")+ if retry_after:+ try:+ return float(retry_after)+ except ValueError:+ logger.debug(+ f"Could not parse Retry-After header: {retry_after}"+ )++ # Try to extract from error message+ error_str = str(error)++ # Look for patterns like "try again in X seconds"+ import re++ patterns = [+ r"try again in (\d+(?:\.\d+)?)\s*seconds?",+ r"retry after (\d+(?:\.\d+)?)\s*seconds?",+ r"wait (\d+(?:\.\d+)?)\s*seconds?",+ ]++ for pattern in patterns:+ match = re.search(pattern, error_str, re.IGNORECASE)+ if match:+ try:+ return float(match.group(1))+ except ValueError:+ pass++ return 0diff --git a/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py b/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.pynew file mode 100644index 0000000000..a84649076d--- /dev/null+++ b/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py@@ -0,0 +1,207 @@+"""+Rate-limited wrapper for LLM calls.+"""++import logging+from typing import Optional+from urllib.parse import urlparse++from tenacity import (+ retry,+ stop_after_attempt,+ retry_if_exception,+)+from tenacity.wait import wait_base++from ..tracker import get_tracker+from ..exceptions import RateLimitError+from .detection import is_llm_rate_limit_error, extract_retry_after+from ....utilities.db_utils import get_db_setting++logger = logging.getLogger(__name__)+++class AdaptiveLLMWait(wait_base):+ """Adaptive wait strategy for LLM rate limiting."""++ def __init__(self, tracker, engine_type: str):+ self.tracker = tracker+ self.engine_type = engine_type+ self.last_error = None++ def __call__(self, retry_state) -> float:+ # Store the error for potential retry-after extraction+ if retry_state.outcome and retry_state.outcome.failed:+ self.last_error = retry_state.outcome.exception()++ # Get adaptive wait time from tracker+ wait_time = self.tracker.get_wait_time(self.engine_type)++ # If we have a retry-after from the error, use it+ if self.last_error:+ retry_after = extract_retry_after(self.last_error)+ if retry_after > 0:+ wait_time = max(wait_time, retry_after)++ logger.info(+ f"LLM rate limit wait for {self.engine_type}: {wait_time:.2f}s"+ )+ return wait_time+++def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):+ """+ Create a rate-limited wrapper around an LLM instance.++ Args:+ base_llm: The base LLM instance to wrap+ provider: Optional provider name (e.g., 'openai', 'anthropic')++ Returns:+ A wrapped LLM instance with rate limiting capabilities+ """++ class RateLimitedLLMWrapper:+ """Wrapper that adds rate limiting to LLM calls."""++ def __init__(self, llm, provider_name: Optional[str] = None):+ self.base_llm = llm+ self.provider = provider_name+ self.rate_limiter = None++ # Only setup rate limiting if enabled+ if self._should_rate_limit():+ self.rate_limiter = get_tracker()+ logger.info(+ f"Rate limiting enabled for LLM provider: {self._get_rate_limit_key()}"+ )++ def _should_rate_limit(self) -> bool:+ """Check if rate limiting should be applied to this LLM."""+ # Check LLM-specific switch (disabled by default, independent of search rate limiting)+ if not get_db_setting("rate_limiting.llm_enabled", False):+ return False++ # Don't rate limit local models+ local_providers = [+ "ollama",+ "lmstudio",+ "llamacpp",+ "vllm",+ "local",+ "none",+ ]+ if self.provider and self.provider.lower() in local_providers:+ logger.debug(+ f"Skipping rate limiting for local provider: {self.provider}"+ )+ return False++ # Check if base URL indicates local model+ if hasattr(self.base_llm, "base_url"):+ base_url = str(self.base_llm.base_url)+ if any(+ local in base_url+ for local in ["localhost", "127.0.0.1", "0.0.0.0"]+ ):+ logger.debug(+ f"Skipping rate limiting for local URL: {base_url}"+ )+ return False++ return True++ def _get_rate_limit_key(self) -> str:+ """Build composite key: provider-url-model"""+ provider = self.provider or "unknown"++ # Extract URL+ url = "unknown"+ if hasattr(self.base_llm, "base_url"):+ url = str(self.base_llm.base_url)+ elif hasattr(self.base_llm, "_client") and hasattr(+ self.base_llm._client, "base_url"+ ):+ url = str(self.base_llm._client.base_url)++ # Clean URL: remove protocol and trailing slashes+ if url != "unknown":+ parsed = urlparse(url)+ url = parsed.netloc or parsed.path+ url = url.rstrip("/")++ # Extract model+ model = "unknown"+ if hasattr(self.base_llm, "model_name"):+ model = str(self.base_llm.model_name)+ elif hasattr(self.base_llm, "model"):+ model = str(self.base_llm.model)++ # Clean model name+ model = model.replace("/", "-").replace(":", "-")++ key = f"{provider}-{url}-{model}"+ return key++ def invoke(self, *args, **kwargs):+ """Invoke the LLM with rate limiting if enabled."""+ if self.rate_limiter:+ rate_limit_key = self._get_rate_limit_key()++ # Define retry logic+ @retry(+ wait=AdaptiveLLMWait(self.rate_limiter, rate_limit_key),+ stop=stop_after_attempt(3),+ retry=retry_if_exception(is_llm_rate_limit_error),+ )+ def _invoke_with_retry():+ return self._do_invoke(*args, **kwargs)++ try:+ result = _invoke_with_retry()++ # Record successful attempt+ self.rate_limiter.record_outcome(+ engine_type=rate_limit_key,+ wait_time=0, # First attempt had no wait+ success=True,+ retry_count=0,+ )++ return result++ except Exception:+ # Record failed attempt+ self.rate_limiter.record_outcome(+ engine_type=rate_limit_key,+ wait_time=0,+ success=False,+ retry_count=0,+ )+ raise+ else:+ # No rate limiting, just invoke directly+ return self._do_invoke(*args, **kwargs)++ def _do_invoke(self, *args, **kwargs):+ """Actually invoke the LLM."""+ try:+ return self.base_llm.invoke(*args, **kwargs)+ except Exception as e:+ # Check if it's a rate limit error and wrap it+ if is_llm_rate_limit_error(e):+ logger.warning(f"LLM rate limit error detected: {e}")+ raise RateLimitError(f"LLM rate limit: {str(e)}")+ raise++ # Pass through any other attributes to the base LLM+ def __getattr__(self, name):+ return getattr(self.base_llm, name)++ def __str__(self):+ return f"RateLimited({str(self.base_llm)})"++ def __repr__(self):+ return f"RateLimitedLLMWrapper({repr(self.base_llm)})"++ return RateLimitedLLMWrapper(base_llm, provider)diff --git a/tests/test_llm_rate_limiting.py b/tests/test_llm_rate_limiting.pynew file mode 100644index 0000000000..4e20ad7108--- /dev/null+++ b/tests/test_llm_rate_limiting.py@@ -0,0 +1,248 @@+"""+Tests for LLM rate limiting functionality.+"""++import pytest+from unittest.mock import Mock, patch+from langchain_core.messages import AIMessage++from tests.test_utils import add_src_to_path++# Add src to path+add_src_to_path()++from local_deep_research.web_search_engines.rate_limiting.llm import ( # noqa: E402+ create_rate_limited_llm_wrapper,+ is_llm_rate_limit_error,+)+from tenacity import RetryError # noqa: E402+++class TestLLMRateLimitDetection:+ """Test rate limit error detection for various LLM providers."""++ def test_detects_429_status_code(self):+ """Test detection of HTTP 429 status code."""+ error = Mock()+ error.response = Mock()+ error.response.status_code = 429++ assert is_llm_rate_limit_error(error) is True++ def test_detects_rate_limit_messages(self):+ """Test detection of common rate limit error messages."""+ test_messages = [+ "Error: 429 Resource has been exhausted (e.g. check quota).",+ "Rate limit exceeded. Please try again later.",+ "Too many requests. Quota exceeded.",+ "API rate limit: maximum requests per minute exceeded",+ "Threshold for requests has been reached",+ ]++ for message in test_messages:+ error = Exception(message)+ assert is_llm_rate_limit_error(error) is True, (+ f"Failed to detect: {message}"+ )++ def test_does_not_detect_non_rate_limit_errors(self):+ """Test that non-rate limit errors are not detected."""+ test_messages = [+ "Model not found",+ "Invalid API key",+ "Connection refused",+ "Internal server error",+ ]++ for message in test_messages:+ error = Exception(message)+ assert is_llm_rate_limit_error(error) is False, (+ f"Incorrectly detected: {message}"+ )+++class TestRateLimitedLLMWrapper:+ """Test the rate limited LLM wrapper functionality."""++ @pytest.fixture+ def mock_llm(self):+ """Create a mock LLM for testing."""+ llm = Mock()+ llm.model_name = "test-model"+ llm.base_url = "https://api.example.com"+ llm.invoke = Mock(return_value=AIMessage(content="Test response"))+ return llm++ @pytest.fixture+ def mock_db_settings(self):+ """Mock database settings."""+ settings = {+ "rate_limiting.llm_enabled": True,+ "rate_limiting.enabled": True,+ "rate_limiting.exploration_rate": 0.1,+ "rate_limiting.learning_rate": 0.3,+ }++ with patch(+ "local_deep_research.web_search_engines.rate_limiting.llm.wrapper.get_db_setting"+ ) as mock:+ mock.side_effect = lambda key, default=None: settings.get(+ key, default+ )+ yield mock++ def test_wrapper_creation_with_rate_limiting_enabled(+ self, mock_llm, mock_db_settings+ ):+ """Test wrapper creation when rate limiting is enabled."""+ wrapper = create_rate_limited_llm_wrapper(mock_llm, provider="openai")++ assert wrapper is not None+ assert hasattr(wrapper, "invoke")+ assert wrapper.base_llm == mock_llm+ assert wrapper.provider == "openai"+ assert wrapper.rate_limiter is not None++ def test_wrapper_creation_with_rate_limiting_disabled(self, mock_llm):+ """Test wrapper creation when rate limiting is disabled."""+ with patch(+ "local_deep_research.web_search_engines.rate_limiting.llm.wrapper.get_db_setting"+ ) as mock:+ mock.return_value = False # Rate limiting disabled++ wrapper = create_rate_limited_llm_wrapper(+ mock_llm, provider="openai"+ )++ assert wrapper.rate_limiter is None++ def test_local_providers_skip_rate_limiting(+ self, mock_llm, mock_db_settings+ ):+ """Test that local providers skip rate limiting even when enabled."""+ local_providers = ["ollama", "lmstudio", "llamacpp", "vllm"]++ for provider in local_providers:+ wrapper = create_rate_limited_llm_wrapper(+ mock_llm, provider=provider+ )+ assert wrapper.rate_limiter is None, (+ f"Rate limiting should be skipped for {provider}"+ )++ def test_rate_limit_key_generation(self, mock_llm, mock_db_settings):+ """Test the generation of rate limit keys."""+ wrapper = create_rate_limited_llm_wrapper(mock_llm, provider="openai")++ key = wrapper._get_rate_limit_key()+ assert key == "openai-api.example.com-test-model"++ def test_invoke_without_rate_limiting(self, mock_llm):+ """Test invoke when rate limiting is disabled."""+ with patch(+ "local_deep_research.web_search_engines.rate_limiting.llm.wrapper.get_db_setting"+ ) as mock:+ mock.return_value = False # Rate limiting disabled++ wrapper = create_rate_limited_llm_wrapper(+ mock_llm, provider="openai"+ )+ response = wrapper.invoke("Test prompt")++ assert response.content == "Test response"+ mock_llm.invoke.assert_called_once_with("Test prompt")++ def test_invoke_with_rate_limit_error(self, mock_llm, mock_db_settings):+ """Test handling of rate limit errors during invoke."""+ # Make the LLM always raise a rate limit error (no success after retries)+ mock_llm.invoke.side_effect = Exception(+ "Error: 429 Resource has been exhausted"+ )++ wrapper = create_rate_limited_llm_wrapper(mock_llm, provider="openai")++ # Mock the tracker to avoid actual waits+ with patch.object(+ wrapper.rate_limiter, "get_wait_time", return_value=0.01+ ):+ with patch.object(wrapper.rate_limiter, "record_outcome"):+ # The retry logic will try 3 times then raise RetryError+ with pytest.raises(RetryError):+ wrapper.invoke("Test prompt")++ # Verify it tried 3 times+ assert mock_llm.invoke.call_count == 3++ def test_successful_retry_after_rate_limit(+ self, mock_llm, mock_db_settings+ ):+ """Test successful retry after rate limit error."""+ # First call fails with rate limit, second succeeds+ mock_llm.invoke.side_effect = [+ Exception("Error: 429 Too many requests"),+ AIMessage(content="Success after retry"),+ ]++ wrapper = create_rate_limited_llm_wrapper(mock_llm, provider="openai")++ # Mock the tracker to avoid actual waits+ with patch.object(+ wrapper.rate_limiter, "get_wait_time", return_value=0.01+ ):+ with patch.object(wrapper.rate_limiter, "record_outcome"):+ response = wrapper.invoke("Test prompt")++ assert response.content == "Success after retry"+ assert mock_llm.invoke.call_count == 2++ def test_attribute_passthrough(self, mock_llm, mock_db_settings):+ """Test that attributes are passed through to the base LLM."""+ mock_llm.custom_attribute = "test_value"++ wrapper = create_rate_limited_llm_wrapper(mock_llm, provider="openai")++ assert wrapper.custom_attribute == "test_value"+ assert wrapper.model_name == "test-model"+++class TestIntegrationWithTracker:+ """Test integration with the adaptive rate limit tracker."""++ @patch(+ "local_deep_research.web_search_engines.rate_limiting.llm.wrapper.get_tracker"+ )+ @patch(+ "local_deep_research.web_search_engines.rate_limiting.llm.wrapper.get_db_setting"+ )+ def test_tracker_records_successful_attempt(+ self, mock_db_setting, mock_get_tracker+ ):+ """Test that successful attempts are recorded in the tracker."""+ mock_db_setting.side_effect = lambda key, default=None: {+ "rate_limiting.llm_enabled": True,+ }.get(key, default)++ mock_tracker = Mock()+ mock_tracker.get_wait_time.return_value = 0+ mock_get_tracker.return_value = mock_tracker++ mock_llm = Mock()+ mock_llm.model_name = "test-model"+ mock_llm.base_url = "https://api.example.com"+ mock_llm.invoke.return_value = AIMessage(content="Success")++ wrapper = create_rate_limited_llm_wrapper(mock_llm, provider="openai")+ wrapper.invoke("Test prompt")++ # Verify the tracker recorded the attempt+ mock_tracker.record_outcome.assert_called_once()+ call_args = mock_tracker.record_outcome.call_args+ assert (+ call_args.kwargs["engine_type"]+ == "openai-api.example.com-test-model"+ )+ assert call_args.kwargs["success"] is True+++if __name__ == "__main__":+ pytest.main([__file__, "-v"])