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.

fix: resolve critical security vulnerabilities (RCE, SSRF, session cookies, CSP)

LearningCircuit615a8ff2f0f9
diff --git a/src/local_deep_research/advanced_search_system/tools/base_tool.py b/src/local_deep_research/advanced_search_system/tools/base_tool.py
index 2f71d1a5d4..075e159bd1 100644
--- a/src/local_deep_research/advanced_search_system/tools/base_tool.py
+++ b/src/local_deep_research/advanced_search_system/tools/base_tool.py
@@ -8,6 +8,19 @@ from abc import ABC, abstractmethod
from typing import Any, Dict
+# Safe type mapping for parameter validation (prevents eval() RCE)
+TYPE_MAP = {
+ "str": str,
+ "int": int,
+ "float": float,
+ "bool": bool,
+ "list": list,
+ "dict": dict,
+ "tuple": tuple,
+ "set": set,
+}
+
+
class BaseTool(ABC):
"""Abstract base class for all agent-compatible tools."""
@@ -69,9 +82,15 @@ class BaseTool(ABC):
param_value = kwargs[param_name]
param_type = param_schema.get("type")
- if param_type and not isinstance(param_value, eval(param_type)):
- logger.error(f"Invalid type for parameter {param_name}")
- return False
+ # Use safe type mapping instead of eval() to prevent RCE
+ if param_type:
+ expected_type = TYPE_MAP.get(param_type)
+ if expected_type and not isinstance(param_value, expected_type):
+ logger.error(
+ f"Invalid type for parameter {param_name}: "
+ f"expected {param_type}, got {type(param_value).__name__}"
+ )
+ return False
if (
"enum" in param_schema
diff --git a/src/local_deep_research/utils/__init__.py b/src/local_deep_research/utils/__init__.py
new file mode 100644
index 0000000000..070d36d103
--- /dev/null
+++ b/src/local_deep_research/utils/__init__.py
@@ -0,0 +1,13 @@
+"""Utility modules for Local Deep Research."""
+
+from .url_validator import validate_url, get_safe_url, is_ip_blocked
+from .safe_requests import safe_get, safe_post, SafeSession
+
+__all__ = [
+ "validate_url",
+ "get_safe_url",
+ "is_ip_blocked",
+ "safe_get",
+ "safe_post",
+ "SafeSession",
+]
diff --git a/src/local_deep_research/utils/safe_requests.py b/src/local_deep_research/utils/safe_requests.py
new file mode 100644
index 0000000000..20a67e540c
--- /dev/null
+++ b/src/local_deep_research/utils/safe_requests.py
@@ -0,0 +1,159 @@
+"""
+Safe HTTP Requests Wrapper
+
+Wraps requests library to add SSRF protection and security best practices.
+"""
+
+import requests
+from typing import Any, Optional
+from loguru import logger
+
+from .url_validator import validate_url
+
+
+# Default timeout for all HTTP requests (prevents hanging)
+DEFAULT_TIMEOUT = 30 # seconds
+
+# Maximum response size to prevent memory exhaustion (10MB)
+MAX_RESPONSE_SIZE = 10 * 1024 * 1024
+
+
+def safe_get(
+ url: str,
+ params: Optional[dict] = None,
+ timeout: int = DEFAULT_TIMEOUT,
+ **kwargs,
+) -> requests.Response:
+ """
+ Make a safe HTTP GET request with SSRF protection.
+
+ Args:
+ url: URL to request
+ params: URL parameters
+ timeout: Request timeout in seconds
+ **kwargs: Additional arguments to pass to requests.get()
+
+ Returns:
+ Response object
+
+ Raises:
+ ValueError: If URL fails SSRF validation
+ requests.RequestException: If request fails
+ """
+ # Validate URL to prevent SSRF
+ if not validate_url(url):
+ raise ValueError(
+ f"URL failed security validation (possible SSRF): {url}"
+ )
+
+ # Ensure timeout is set
+ if "timeout" not in kwargs:
+ kwargs["timeout"] = timeout
+
+ # Prevent following redirects to internal IPs by default
+ if "allow_redirects" not in kwargs:
+ kwargs["allow_redirects"] = False
+
+ try:
+ response = requests.get(url, params=params, **kwargs)
+
+ # Check response size
+ content_length = response.headers.get("Content-Length")
+ if content_length and int(content_length) > MAX_RESPONSE_SIZE:
+ raise ValueError(
+ f"Response too large: {content_length} bytes "
+ f"(max {MAX_RESPONSE_SIZE})"
+ )
+
+ return response
+
+ except requests.Timeout:
+ logger.warning(f"Request timeout after {timeout}s: {url}")
+ raise
+ except requests.RequestException as e:
+ logger.warning(f"Request failed for {url}: {e}")
+ raise
+
+
+def safe_post(
+ url: str,
+ data: Optional[Any] = None,
+ json: Optional[dict] = None,
+ timeout: int = DEFAULT_TIMEOUT,
+ **kwargs,
+) -> requests.Response:
+ """
+ Make a safe HTTP POST request with SSRF protection.
+
+ Args:
+ url: URL to request
+ data: Data to send in request body
+ json: JSON data to send in request body
+ timeout: Request timeout in seconds
+ **kwargs: Additional arguments to pass to requests.post()
+
+ Returns:
+ Response object
+
+ Raises:
+ ValueError: If URL fails SSRF validation
+ requests.RequestException: If request fails
+ """
+ # Validate URL to prevent SSRF
+ if not validate_url(url):
+ raise ValueError(
+ f"URL failed security validation (possible SSRF): {url}"
+ )
+
+ # Ensure timeout is set
+ if "timeout" not in kwargs:
+ kwargs["timeout"] = timeout
+
+ # Prevent following redirects to internal IPs by default
+ if "allow_redirects" not in kwargs:
+ kwargs["allow_redirects"] = False
+
+ try:
+ response = requests.post(url, data=data, json=json, **kwargs)
+
+ # Check response size
+ content_length = response.headers.get("Content-Length")
+ if content_length and int(content_length) > MAX_RESPONSE_SIZE:
+ raise ValueError(
+ f"Response too large: {content_length} bytes "
+ f"(max {MAX_RESPONSE_SIZE})"
+ )
+
+ return response
+
+ except requests.Timeout:
+ logger.warning(f"Request timeout after {timeout}s: {url}")
+ raise
+ except requests.RequestException as e:
+ logger.warning(f"Request failed for {url}: {e}")
+ raise
+
+
+# Create a safe session class
+class SafeSession(requests.Session):
+ """
+ Session with built-in SSRF protection.
+
+ Usage:
+ with SafeSession() as session:
+ response = session.get(url)
+ """
+
+ def request(self, method: str, url: str, **kwargs) -> requests.Response:
+ """Override request method to add SSRF validation."""
+ # Validate URL
+ if not validate_url(url):
+ raise ValueError(
+ f"URL failed security validation (possible SSRF): {url}"
+ )
+
+ # Ensure timeout is set
+ if "timeout" not in kwargs:
+ kwargs["timeout"] = DEFAULT_TIMEOUT
+
+ return super().request(method, url, **kwargs)
diff --git a/src/local_deep_research/utils/url_validator.py b/src/local_deep_research/utils/url_validator.py
new file mode 100644
index 0000000000..7416b5577f
--- /dev/null
+++ b/src/local_deep_research/utils/url_validator.py
@@ -0,0 +1,160 @@
+"""
+URL Validator for SSRF Prevention
+
+Validates URLs to prevent Server-Side Request Forgery (SSRF) attacks
+by blocking requests to internal/private networks and enforcing safe schemes.
+"""
+
+import ipaddress
+import socket
+from urllib.parse import urlparse
+from typing import Optional
+from loguru import logger
+
+
+# Blocked IP ranges (RFC1918 private networks, localhost, link-local, etc.)
+BLOCKED_IP_RANGES = [
+ ipaddress.ip_network("127.0.0.0/8"), # Loopback
+ ipaddress.ip_network("::1/128"), # IPv6 loopback
+ ipaddress.ip_network("10.0.0.0/8"), # Private network
+ ipaddress.ip_network("172.16.0.0/12"), # Private network
+ ipaddress.ip_network("192.168.0.0/16"), # Private network
+ ipaddress.ip_network("169.254.0.0/16"), # Link-local
+ ipaddress.ip_network("fe80::/10"), # IPv6 link-local
+ ipaddress.ip_network("fc00::/7"), # IPv6 unique local
+ ipaddress.ip_network("0.0.0.0/8"), # "This" network
+ ipaddress.ip_network("100.64.0.0/10"), # Shared address space
+]
+
+# AWS metadata endpoint (commonly targeted in SSRF attacks)
+AWS_METADATA_IP = "169.254.169.254"
+
+# Allowed URL schemes
+ALLOWED_SCHEMES = {"http", "https"}
+
+
+def is_ip_blocked(ip_str: str) -> bool:
+ """
+ Check if an IP address is in a blocked range.
+
+ Args:
+ ip_str: IP address as string
+
+ Returns:
+ True if IP is blocked, False otherwise
+ """
+ try:
+ ip = ipaddress.ip_address(ip_str)
+
+ # Check if IP is in any blocked range
+ for blocked_range in BLOCKED_IP_RANGES:
+ if ip in blocked_range:
+ return True
+
+ # Specifically block AWS metadata endpoint
+ if str(ip) == AWS_METADATA_IP:
+ return True
+
+ return False
+
+ except ValueError:
+ # Invalid IP address
+ return False
+
+
+def validate_url(url: str, allow_redirects: bool = True) -> bool:
+ """
+ Validate URL to prevent SSRF attacks.
+
+ Checks:
+ 1. URL scheme is allowed (http/https only)
+ 2. Hostname is not an internal/private IP address
+ 3. Hostname does not resolve to an internal/private IP
+
+ Args:
+ url: URL to validate
+ allow_redirects: Whether to allow redirects (future use)
+
+ Returns:
+ True if URL is safe, False otherwise
+ """
+ try:
+ parsed = urlparse(url)
+
+ # Check scheme
+ if parsed.scheme.lower() not in ALLOWED_SCHEMES:
+ logger.warning(
+ f"Blocked URL with invalid scheme: {parsed.scheme} - {url}"
+ )
+ return False
+
+ hostname = parsed.hostname
+ if not hostname:
+ logger.warning(f"Blocked URL with no hostname: {url}")
+ return False
+
+ # Check if hostname is an IP address
+ try:
+ ip = ipaddress.ip_address(hostname)
+ if is_ip_blocked(str(ip)):
+ logger.warning(
+ f"Blocked URL with internal/private IP: {hostname} - {url}"
+ )
+ return False
+ except ValueError:
+ # Not an IP address, it's a hostname - need to resolve it
+ pass
+
+ # Resolve hostname to IP and check
+ try:
+ # Get all IP addresses for hostname
+ addr_info = socket.getaddrinfo(
+ hostname, None, socket.AF_UNSPEC, socket.SOCK_STREAM
+ )
+
+ for info in addr_info:
+ ip_str = info[4][0] # Extract IP address from addr_info tuple
+
+ if is_ip_blocked(ip_str):
+ logger.warning(
+ f"Blocked URL - hostname {hostname} resolves to "
+ f"internal/private IP: {ip_str} - {url}"
+ )
+ return False
+
+ except socket.gaierror as e:
+ logger.warning(f"Failed to resolve hostname {hostname}: {e}")
+ return False
+ except Exception:
+ logger.exception("Error during hostname resolution")
+ return False
+
+ # URL passes all checks
+ return True
+
+ except Exception:
+ logger.exception(f"Error validating URL {url}")
+ return False
+
+
+def get_safe_url(
+ url: Optional[str], default: Optional[str] = None
+) -> Optional[str]:
+ """
+ Get URL if it's safe, otherwise return default.
+
+ Args:
+ url: URL to validate
+ default: Default value if URL is unsafe
+
+ Returns:
+ URL if safe, default otherwise
+ """
+ if not url:
+ return default
+
+ if validate_url(url):
+ return url
+
+ logger.warning(f"Unsafe URL rejected: {url}")
+ return default
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index e08d656835..a46fc1b41b 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -87,9 +87,13 @@ def create_app():
except Exception as e:
logger.warning(f"Could not save secret key file: {e}")
app.config["SECRET_KEY"] = new_key
- app.config["SESSION_COOKIE_SECURE"] = False # Allow HTTP for local testing
- app.config["SESSION_COOKIE_HTTPONLY"] = True
- app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
+ # Session cookie security settings
+ # SECURE: Only send cookies over HTTPS in production (not in debug mode)
+ app.config["SESSION_COOKIE_SECURE"] = not app.debug
+ app.config["SESSION_COOKIE_HTTPONLY"] = (
+ True # Prevent JavaScript access (XSS mitigation)
+ )
+ app.config["SESSION_COOKIE_SAMESITE"] = "Lax" # CSRF protection
app.config["PERMANENT_SESSION_LIFETIME"] = 7200 # 2 hours in seconds
app.config["PREFERRED_URL_SCHEME"] = "https"
@@ -317,17 +321,33 @@ def apply_middleware(app):
# Add Content Security Policy headers to allow Socket.IO to function
@app.after_request
def add_security_headers(response):
- # Define a permissive CSP for development that allows Socket.IO to function
- csp = (
- "default-src 'self'; "
- "connect-src 'self' ws: wss: http: https:; "
- "script-src 'self' 'unsafe-inline' 'unsafe-eval'; "
- "style-src 'self' 'unsafe-inline'; "
- "font-src 'self' data:; "
- "img-src 'self' data:; "
- "worker-src blob:; "
- "frame-src 'self';"
- )
+ # Use strict CSP in production, permissive in development
+ # In production: Remove unsafe-inline/unsafe-eval to prevent XSS attacks
+ # In development: Allow unsafe directives for compatibility
+ if app.debug:
+ # Development: Permissive CSP for easier debugging
+ csp = (
+ "default-src 'self'; "
+ "connect-src 'self' ws: wss: http: https:; "
+ "script-src 'self' 'unsafe-inline' 'unsafe-eval'; "
+ "style-src 'self' 'unsafe-inline'; "
+ "font-src 'self' data:; "
+ "img-src 'self' data:; "
+ "worker-src blob:; "
+ "frame-src 'self';"
+ )
+ else:
+ # Production: Strict CSP without unsafe-inline/unsafe-eval
+ csp = (
+ "default-src 'self'; "
+ "connect-src 'self' ws: wss: https:; "
+ "script-src 'self'; "
+ "style-src 'self'; "
+ "font-src 'self' data:; "
+ "img-src 'self' data:; "
+ "worker-src blob:; "
+ "frame-src 'self';"
+ )
response.headers["Content-Security-Policy"] = csp
response.headers["X-Content-Security-Policy"] = csp
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_github.py b/src/local_deep_research/web_search_engines/engines/search_engine_github.py
index f4f53404fb..446447ea4d 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_github.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_github.py
@@ -3,11 +3,11 @@ import json
import time
from typing import Any, Dict, List, Optional
-import requests
from langchain_core.language_models import BaseLLM
from loguru import logger
from ...config import llm_config, search_config
+from ...utils.safe_requests import safe_get
from ..search_engine_base import BaseSearchEngine
@@ -200,7 +200,7 @@ class GitHubSearchEngine(BaseSearchEngine):
)
# Execute the API request
- response = requests.get(
+ response = safe_get(
self.search_endpoint, headers=self.headers, params=params
)
@@ -263,7 +263,7 @@ class GitHubSearchEngine(BaseSearchEngine):
self.engine_type
)
- response = requests.get(
+ response = safe_get(
f"{self.api_base}/repos/{repo_full_name}/readme",
headers=self.headers,
)
@@ -313,7 +313,7 @@ class GitHubSearchEngine(BaseSearchEngine):
self.engine_type
)
- response = requests.get(
+ response = safe_get(
f"{self.api_base}/repos/{repo_full_name}/issues",
headers=self.headers,
params={
@@ -359,7 +359,7 @@ class GitHubSearchEngine(BaseSearchEngine):
)
# Get file content
- response = requests.get(file_url, headers=self.headers)
+ response = safe_get(file_url, headers=self.headers)
# Check for rate limiting
self._handle_rate_limits(response)
@@ -682,7 +682,7 @@ class GitHubSearchEngine(BaseSearchEngine):
self.engine_type
)
- response = requests.get(
+ response = safe_get(
f"{self.api_base}/repos/{repo_full_name}", headers=self.headers
)
@@ -806,7 +806,7 @@ class GitHubSearchEngine(BaseSearchEngine):
}
# Perform search
- response = requests.get(
+ response = safe_get(
self.search_endpoint, headers=self.headers, params=params
)
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py b/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py
index 4122757ea3..faca02fb16 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py
@@ -3,10 +3,10 @@ import random
import time
from typing import Any, Dict, List, Optional
-import requests
from langchain_core.language_models import BaseLLM
from requests.exceptions import RequestException
+from ...utils.safe_requests import safe_get
from ..rate_limiting import RateLimitError
from ..search_engine_base import BaseSearchEngine
@@ -232,7 +232,7 @@ class GooglePSESearchEngine(BaseSearchEngine):
self.engine_type
)
- response = requests.get(url, params=params, timeout=10)
+ response = safe_get(url, params=params, timeout=10)
# Check for HTTP errors
response.raise_for_status()
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py b/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py
index 1d30619140..3267aae24b 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py
@@ -1,13 +1,13 @@
from datetime import datetime, timedelta, UTC
from typing import Any, Dict, List, Optional, Tuple
-import requests
from langchain_core.language_models import BaseLLM
from loguru import logger
from ...config import search_config
from ...config.search_config import get_setting_from_snapshot
from ...utilities.search_utilities import remove_think_tags
+from ...utils.safe_requests import safe_get
from ..search_engine_base import BaseSearchEngine
@@ -367,7 +367,7 @@ ONE WORD ONLY:"""
)
# Execute the API request
- response = requests.get(self.api_url, params=params)
+ response = safe_get(self.api_url, params=params)
response.raise_for_status()
data = response.json()
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py b/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py
index 425141f605..2104ca566d 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py
@@ -2,13 +2,13 @@
from typing import Any, Dict, List, Optional
-import requests
from langchain_core.language_models import BaseLLM
from loguru import logger
from ...advanced_search_system.filters.journal_reputation_filter import (
JournalReputationFilter,
)
+from ...utils.safe_requests import safe_get
from ..rate_limiting import RateLimitError
from ..search_engine_base import BaseSearchEngine
@@ -179,7 +179,7 @@ class NasaAdsSearchEngine(BaseSearchEngine):
logger.info(
f"Making NASA ADS API request with query: {params['q'][:100]}..."
)
- response = requests.get(
+ response = safe_get(
f"{self.api_base}/search/query",
params=params,
headers=self.headers,
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py b/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py
index e09e599ba5..9d94d0cced 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py
@@ -2,13 +2,13 @@
from typing import Any, Dict, List, Optional
-import requests
from langchain_core.language_models import BaseLLM
from loguru import logger
from ...advanced_search_system.filters.journal_reputation_filter import (
JournalReputationFilter,
)
+from ...utils.safe_requests import safe_get
from ..rate_limiting import RateLimitError
from ..search_engine_base import BaseSearchEngine
@@ -165,7 +165,7 @@ class OpenAlexSearchEngine(BaseSearchEngine):
# Make the API request
logger.info(f"Making OpenAlex API request with params: {params}")
- response = requests.get(
+ response = safe_get(
f"{self.api_base}/works",
params=params,
headers=self.headers,
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py
index 56126a3b55..a0b0925c00 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py
@@ -2,11 +2,11 @@ import re
import xml.etree.ElementTree as ET
from typing import Any, Dict, List, Optional, Tuple
-import requests
from langchain_core.language_models import BaseLLM
from loguru import logger
from ...config import search_config
+from ...utils.safe_requests import safe_get
from ..rate_limiting import RateLimitError
from ..search_engine_base import BaseSearchEngine
@@ -127,7 +127,7 @@ class PubMedSearchEngine(BaseSearchEngine):
)
# Execute search request
- response = requests.get(self.search_url, params=params)
+ response = safe_get(self.search_url, params=params)
response.raise_for_status()
# Parse response
@@ -619,7 +619,7 @@ The default assumption should be that medical and scientific queries want RECENT
# Execute search request
logger.debug(f"Sending request to PubMed API: {self.search_url}")
- response = requests.get(self.search_url, params=params)
+ response = safe_get(self.search_url, params=params)
response.raise_for_status()
logger.debug(f"PubMed API response status: {response.status_code}")
@@ -679,7 +679,7 @@ The default assumption should be that medical and scientific queries want RECENT
# Execute request
logger.debug(f"Requesting summaries from: {self.summary_url}")
- response = requests.get(self.summary_url, params=params)
+ response = safe_get(self.summary_url, params=params)
response.raise_for_status()
logger.debug(f"Summary API response status: {response.status_code}")
@@ -802,7 +802,7 @@ The default assumption should be that medical and scientific queries want RECENT
# Execute request
logger.debug(f"Requesting abstracts from: {self.fetch_url}")
- response = requests.get(self.fetch_url, params=params)
+ response = safe_get(self.fetch_url, params=params)
response.raise_for_status()
logger.debug(
f"Abstract fetch response status: {response.status_code}, size: {len(response.text)} bytes"
@@ -908,7 +908,7 @@ The default assumption should be that medical and scientific queries want RECENT
)
# Execute request
- response = requests.get(self.fetch_url, params=params)
+ response = safe_get(self.fetch_url, params=params)
response.raise_for_status()
# Parse XML response
@@ -1142,7 +1142,7 @@ The default assumption should be that medical and scientific queries want RECENT
)
# Execute request
- response = requests.get(self.link_url, params=params)
+ response = safe_get(self.link_url, params=params)
response.raise_for_status()
# Parse response
@@ -1200,7 +1200,7 @@ The default assumption should be that medical and scientific queries want RECENT
)
# Execute request
- response = requests.get(self.fetch_url, params=params)
+ response = safe_get(self.fetch_url, params=params)
response.raise_for_status()
# Parse XML response
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py
index bd8dac8d42..731809b7a7 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py
@@ -7,6 +7,7 @@ from langchain_core.language_models import BaseLLM
from loguru import logger
from ...config import search_config
+from ...utils.safe_requests import safe_get
from ..search_engine_base import BaseSearchEngine
from .full_search import FullSearchResults
@@ -76,7 +77,7 @@ class SearXNGSearchEngine(BaseSearchEngine):
)
try:
# Make sure it's accessible.
- response = requests.get(self.instance_url, timeout=5)
+ response = safe_get(self.instance_url, timeout=5)
if response.status_code == 200:
logger.info("SearXNG instance is accessible.")
self.is_available = True
@@ -182,7 +183,7 @@ class SearXNGSearchEngine(BaseSearchEngine):
}
try:
- initial_response = requests.get(
+ initial_response = safe_get(
self.instance_url, headers=initial_headers, timeout=10
)
cookies = initial_response.cookies
@@ -219,7 +220,7 @@ class SearXNGSearchEngine(BaseSearchEngine):
logger.info(
f"Sending request to SearXNG instance at {self.instance_url}"
)
- response = requests.get(
+ response = safe_get(
self.search_url,
params=params,
headers=headers,
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py b/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py
index b6c28ce781..944446affd 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py
@@ -5,6 +5,7 @@ from langchain_core.language_models import BaseLLM
from loguru import logger
from ...config import search_config
+from ...utils.safe_requests import safe_post
from ..rate_limiting import RateLimitError
from ..search_engine_base import BaseSearchEngine
@@ -145,7 +146,7 @@ class TavilySearchEngine(BaseSearchEngine):
)
# Make the API request
- response = requests.post(
+ response = safe_post(
f"{self.base_url}/search",
json=payload,
headers={"Content-Type": "application/json"},
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py b/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py
index 304998aba5..8e1997d534 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py
@@ -2,11 +2,11 @@ import re
from typing import Any, Dict, List, Optional, Tuple
import justext
-import requests
from langchain_core.language_models import BaseLLM
from loguru import logger
from ...config import search_config
+from ...utils.safe_requests import safe_get
from ..search_engine_base import BaseSearchEngine
@@ -144,7 +144,7 @@ class WaybackSearchEngine(BaseSearchEngine):
try:
if self.closest_only:
# Get only the closest snapshot
- response = requests.get(self.available_api, params={"url": url})
+ response = safe_get(self.available_api, params={"url": url})
data = response.json()
if (
@@ -167,7 +167,7 @@ class WaybackSearchEngine(BaseSearchEngine):
)
else:
# Get multiple snapshots using CDX API
- response = requests.get(
+ response = safe_get(
self.cdx_api,
params={
"url": url,
@@ -297,7 +297,7 @@ class WaybackSearchEngine(BaseSearchEngine):
headers = {
"User-Agent": "Mozilla/5.0 (Local Deep Research Bot; research project)"
}
- response = requests.get(url, headers=headers, timeout=10)
+ response = safe_get(url, headers=headers, timeout=10)
raw_html = response.text
# Clean the HTML
@@ -415,7 +415,7 @@ class WaybackSearchEngine(BaseSearchEngine):
"""
try:
# Use CDX API with date range
- response = requests.get(
+ response = safe_get(
self.cdx_api,
params={
"url": url,
@@ -479,7 +479,7 @@ class WaybackSearchEngine(BaseSearchEngine):
Dictionary with snapshot information or None if not found
"""
try:
- response = requests.get(self.available_api, params={"url": url})
+ response = safe_get(self.available_api, params={"url": url})
data = response.json()
if (