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: close remaining LLM and Elasticsearch FD leaks (#2712)

LearningCircuit43a651280f2b
diff --git a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
index 96a776003b..4a7fb2ecd5 100644
--- a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
+++ b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
@@ -11,6 +11,7 @@ from ...config.llm_config import get_llm
from ...database.models import Journal
from ...database.session_context import get_user_db_session
from ...search_system import AdvancedSearchSystem
+from ...utilities.llm_utils import close_llm
from ...utilities.thread_context import get_search_context
from ...web_search_engines.search_engine_factory import create_search_engine
from .base_filter import BaseFilter
@@ -56,6 +57,7 @@ class JournalReputationFilter(BaseFilter):
"""
super().__init__(model)
+ self._owns_llm = self.model is None
if self.model is None:
self.model = get_llm()
@@ -119,6 +121,19 @@ class JournalReputationFilter(BaseFilter):
"SearXNG initialization failed or not available."
)
+ def close(self) -> None:
+ """Close the SearXNG engine and LLM client."""
+ if (
+ hasattr(self, "_JournalReputationFilter__engine")
+ and self.__engine is not None
+ ):
+ try:
+ self.__engine.close()
+ except Exception:
+ pass
+ if self._owns_llm and self.model is not None:
+ close_llm(self.model)
+
@classmethod
def create_default(
cls,
diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.py
index d305098a82..4ffe2356c5 100644
--- a/src/local_deep_research/api/research_functions.py
+++ b/src/local_deep_research/api/research_functions.py
@@ -15,37 +15,12 @@ from ..config.thread_settings import get_setting_from_snapshot
from ..report_generator import IntegratedReportGenerator
from ..search_system import AdvancedSearchSystem
from ..utilities.db_utils import no_db_settings
+from ..utilities.llm_utils import close_llm as _close_llm
from ..utilities.thread_context import clear_search_context, set_search_context
from ..utilities.search_utilities import remove_think_tags
from .settings_utils import create_settings_snapshot
-def _close_llm(llm):
- """Close underlying HTTP clients held by LLM instances.
-
- Only ChatOllama creates per-instance httpx.Client objects that need
- explicit close(). ChatAnthropic uses @lru_cache'd shared httpx
- clients that must NOT be closed.
- """
- try:
- # Unwrap ProcessingLLMWrapper
- base = getattr(llm, "base_llm", llm)
- # ChatOllama path: base._client is ollama.Client,
- # base._client._client is httpx.Client
- ollama_client = getattr(base, "_client", None)
- if ollama_client is not None:
- # Only close Ollama clients — Anthropic's are @lru_cache'd and shared.
- # This relies on ollama's module structure; if the ollama package
- # reorganises its internals this guard may need updating.
- if not type(ollama_client).__module__.startswith("ollama"):
- return
- httpx_client = getattr(ollama_client, "_client", None)
- if httpx_client is not None and hasattr(httpx_client, "close"):
- httpx_client.close()
- except Exception:
- pass
-
-
def _close_system(system):
"""Close an AdvancedSearchSystem and its associated resources."""
try:
diff --git a/src/local_deep_research/benchmarks/graders.py b/src/local_deep_research/benchmarks/graders.py
index c9043efc28..427e0c15a0 100644
--- a/src/local_deep_research/benchmarks/graders.py
+++ b/src/local_deep_research/benchmarks/graders.py
@@ -13,6 +13,7 @@ from typing import Any, Callable, Dict, List, Optional
from langchain_core.messages.human import HumanMessage
from ..config.llm_config import get_llm
+from ..utilities.llm_utils import close_llm
from .templates import BROWSECOMP_GRADER_TEMPLATE, SIMPLEQA_GRADER_TEMPLATE
@@ -158,25 +159,25 @@ def grade_single_result(
# Get evaluation LLM
evaluation_llm = get_evaluation_llm(evaluation_config, settings_snapshot)
- # Select appropriate template
- template = (
- BROWSECOMP_GRADER_TEMPLATE
- if dataset_type.lower() == "browsecomp"
- else SIMPLEQA_GRADER_TEMPLATE
- )
+ try:
+ # Select appropriate template
+ template = (
+ BROWSECOMP_GRADER_TEMPLATE
+ if dataset_type.lower() == "browsecomp"
+ else SIMPLEQA_GRADER_TEMPLATE
+ )
- question = result_data.get("problem", "")
- correct_answer = result_data.get("correct_answer", "")
- response = result_data.get("response", "")
+ question = result_data.get("problem", "")
+ correct_answer = result_data.get("correct_answer", "")
+ response = result_data.get("response", "")
- logger.info(f"Grading single result: {question[:50]}...")
+ logger.info(f"Grading single result: {question[:50]}...")
- # Format grading prompt
- grading_prompt = template.format(
- question=question, correct_answer=correct_answer, response=response
- )
+ # Format grading prompt
+ grading_prompt = template.format(
+ question=question, correct_answer=correct_answer, response=response
+ )
- try:
import time
eval_llm_start = time.time()
@@ -273,7 +274,7 @@ def grade_single_result(
confidence = "100" # SimpleQA doesn't have confidence
# Format graded result
- graded_result = {
+ return {
"extracted_by_grader": extracted_answer,
"reasoning": reasoning,
"is_correct": is_correct,
@@ -281,8 +282,6 @@ def grade_single_result(
"grader_response": grading_response,
}
- return graded_result
-
except Exception as e:
logger.exception("Error grading single result")
return {
@@ -291,6 +290,8 @@ def grade_single_result(
"graded_confidence": "0",
"grader_response": f"Grading failed: {e!s}",
}
+ finally:
+ close_llm(evaluation_llm)
def grade_results(
@@ -316,6 +317,26 @@ def grade_results(
# Get evaluation LLM
evaluation_llm = get_evaluation_llm(evaluation_config)
+ try:
+ return _grade_results_inner(
+ evaluation_llm,
+ results_file,
+ output_file,
+ dataset_type,
+ progress_callback,
+ )
+ finally:
+ close_llm(evaluation_llm)
+
+
+def _grade_results_inner(
+ evaluation_llm,
+ results_file: str,
+ output_file: str,
+ dataset_type: str,
+ progress_callback: Optional[Callable[[int, int, Dict], None]],
+) -> List[Dict[str, Any]]:
+ """Inner implementation of grade_results, separated for cleanup."""
# Select appropriate template
template = (
BROWSECOMP_GRADER_TEMPLATE
diff --git a/src/local_deep_research/domain_classifier/classifier.py b/src/local_deep_research/domain_classifier/classifier.py
index ee380acaa1..4ef29f33c4 100644
--- a/src/local_deep_research/domain_classifier/classifier.py
+++ b/src/local_deep_research/domain_classifier/classifier.py
@@ -10,6 +10,7 @@ from ..config.llm_config import get_llm
from ..database.models import ResearchResource
from ..database.session_context import get_user_db_session
from ..utilities.json_utils import extract_json, get_llm_response_text
+from ..utilities.llm_utils import close_llm
from .models import DomainClassification
@@ -101,6 +102,11 @@ class DomainClassifier:
self.llm = get_llm(settings_snapshot=self.settings_snapshot)
return self.llm
+ def close(self) -> None:
+ """Close the LLM client if one was created."""
+ if self.llm is not None:
+ close_llm(self.llm)
+
def _get_domain_samples(
self, domain: str, session: Session, limit: int = 5
) -> List[Dict]:
diff --git a/src/local_deep_research/news/core/news_analyzer.py b/src/local_deep_research/news/core/news_analyzer.py
index a44c77f14d..12637bc5ce 100644
--- a/src/local_deep_research/news/core/news_analyzer.py
+++ b/src/local_deep_research/news/core/news_analyzer.py
@@ -11,6 +11,7 @@ from .utils import generate_card_id
from ..utils.topic_generator import generate_topics
from ...config.llm_config import get_llm
from ...utilities.json_utils import extract_json, get_llm_response_text
+from ...utilities.llm_utils import close_llm
class NewsAnalyzer:
@@ -35,8 +36,14 @@ class NewsAnalyzer:
Args:
llm_client: LLM client for analysis
"""
+ self._owns_llm = llm_client is None
self.llm_client = llm_client or get_llm()
+ def close(self) -> None:
+ """Close the LLM client if this instance created it."""
+ if self._owns_llm and self.llm_client is not None:
+ close_llm(self.llm_client)
+
def analyze_news(
self, search_results: List[Dict[str, Any]]
) -> Dict[str, Any]:
diff --git a/src/local_deep_research/news/utils/headline_generator.py b/src/local_deep_research/news/utils/headline_generator.py
index 6f95bbee37..e61be499bf 100644
--- a/src/local_deep_research/news/utils/headline_generator.py
+++ b/src/local_deep_research/news/utils/headline_generator.py
@@ -36,22 +36,24 @@ def _generate_with_llm(
"""Generate headline using LLM."""
try:
from ...config.llm_config import get_llm
+ from ...utilities.llm_utils import close_llm
# Use the configured model for headline generation
llm = get_llm(temperature=0.3)
- # Focus only on the findings/report content, not the query
- if not findings:
- logger.debug("No findings provided for headline generation")
- return None
+ try:
+ # Focus only on the findings/report content, not the query
+ if not findings:
+ logger.debug("No findings provided for headline generation")
+ return None
- # Use the COMPLETE findings - no character limit
- findings_preview = findings
- logger.debug(
- f"Generating headline with {len(findings)} chars of findings"
- )
+ # Use the COMPLETE findings - no character limit
+ findings_preview = findings
+ logger.debug(
+ f"Generating headline with {len(findings)} chars of findings"
+ )
- prompt = f"""Generate a comprehensive news headline that captures the key events from the research report below.
+ prompt = f"""Generate a comprehensive news headline that captures the key events from the research report below.
Research Findings:
{findings_preview}
@@ -68,16 +70,18 @@ Requirements:
Generate only the headline text, nothing else."""
- response = llm.invoke(prompt)
- headline = response.content.strip()
+ response = llm.invoke(prompt)
+ headline = response.content.strip()
- # Clean up the generated headline
- headline = headline.strip("\"'.,!?")
+ # Clean up the generated headline
+ headline = headline.strip("\"'.,!?")
- # Validate the headline
- if headline:
- logger.debug(f"Generated headline: {headline}")
- return headline
+ # Validate the headline
+ if headline:
+ logger.debug(f"Generated headline: {headline}")
+ return headline
+ finally:
+ close_llm(llm)
except Exception as e:
logger.debug(f"LLM headline generation failed: {e}")
diff --git a/src/local_deep_research/news/utils/topic_generator.py b/src/local_deep_research/news/utils/topic_generator.py
index df1b1b61b4..608bbf67c8 100644
--- a/src/local_deep_research/news/utils/topic_generator.py
+++ b/src/local_deep_research/news/utils/topic_generator.py
@@ -41,6 +41,7 @@ def _generate_with_llm(
"""Generate topics using LLM."""
try:
from ...config.llm_config import get_llm
+ from ...utilities.llm_utils import close_llm
logger.debug(
f"Topic generation - findings length: {len(findings) if findings else 0}, category: {category}"
@@ -49,13 +50,16 @@ def _generate_with_llm(
# Use the configured model for topic generation
llm = get_llm(temperature=0.5)
- # Prepare context
- query_preview = query[:500] if len(query) > 500 else query
- findings_preview = (
- findings[:1000] if findings and len(findings) > 1000 else findings
- )
+ try:
+ # Prepare context
+ query_preview = query[:500] if len(query) > 500 else query
+ findings_preview = (
+ findings[:1000]
+ if findings and len(findings) > 1000
+ else findings
+ )
- prompt = f"""Extract relevant topics/tags from this news content.
+ prompt = f"""Extract relevant topics/tags from this news content.
Query: {query_preview}
{f"Content: {findings_preview}" if findings_preview else ""}
@@ -73,29 +77,31 @@ Requirements:
Return ONLY a JSON array of topic strings, like: ["Topic 1", "Topic 2", "Topic 3"]"""
- response = llm.invoke(prompt)
- content = get_llm_response_text(response)
-
- # Try to parse the JSON response
- topics = extract_json(content, expected_type=list)
-
- if topics is not None:
- # Clean and validate each topic
- cleaned_topics = []
- for topic in topics:
- if isinstance(topic, str):
- cleaned = topic.strip()
- if cleaned and len(cleaned) <= 30: # Max topic length
- cleaned_topics.append(cleaned)
-
- logger.debug(f"Generated topics: {cleaned_topics}")
- return cleaned_topics[:max_topics]
-
- # Try to extract topics from plain text response
- logger.debug(f"Failed to parse LLM topics as JSON: {content}")
- if "," in content:
- topics = [t.strip().strip("\"'") for t in content.split(",")]
- return [t for t in topics if t and len(t) <= 30][:max_topics]
+ response = llm.invoke(prompt)
+ content = get_llm_response_text(response)
+
+ # Try to parse the JSON response
+ topics = extract_json(content, expected_type=list)
+
+ if topics is not None:
+ # Clean and validate each topic
+ cleaned_topics = []
+ for topic in topics:
+ if isinstance(topic, str):
+ cleaned = topic.strip()
+ if cleaned and len(cleaned) <= 30: # Max topic length
+ cleaned_topics.append(cleaned)
+
+ logger.debug(f"Generated topics: {cleaned_topics}")
+ return cleaned_topics[:max_topics]
+
+ # Try to extract topics from plain text response
+ logger.debug(f"Failed to parse LLM topics as JSON: {content}")
+ if "," in content:
+ topics = [t.strip().strip("\"'") for t in content.split(",")]
+ return [t for t in topics if t and len(t) <= 30][:max_topics]
+ finally:
+ close_llm(llm)
except Exception as e:
logger.debug(f"LLM topic generation failed: {e}")
diff --git a/src/local_deep_research/report_generator.py b/src/local_deep_research/report_generator.py
index 9590a60097..f2bd7ac117 100644
--- a/src/local_deep_research/report_generator.py
+++ b/src/local_deep_research/report_generator.py
@@ -10,6 +10,7 @@ from .config.llm_config import get_llm
from .config.thread_settings import get_setting_from_snapshot
from .search_system import AdvancedSearchSystem
from .utilities import search_utilities
+from .utilities.llm_utils import close_llm
# Default constants for context accumulation to avoid repetition
# These are used as fallbacks when settings are not available
@@ -49,6 +50,7 @@ class IntegratedReportGenerator:
"""
# If search_system is provided, use its LLM; otherwise use the provided LLM
+ self._owns_llm = False
if search_system:
self.search_system = search_system
self.model = llm or search_system.model
@@ -57,6 +59,7 @@ class IntegratedReportGenerator:
self.search_system = AdvancedSearchSystem(llm=self.model)
else:
# Fallback for backwards compatibility - will only work with auth
+ self._owns_llm = True
self.model = get_llm()
self.search_system = AdvancedSearchSystem(llm=self.model)
@@ -76,6 +79,11 @@ class IntegratedReportGenerator:
settings_snapshot=settings_snapshot,
)
+ def close(self) -> None:
+ """Close the LLM client if this instance created it."""
+ if self._owns_llm and self.model is not None:
+ close_llm(self.model)
+
def generate_report(
self,
initial_findings: Dict,
diff --git a/src/local_deep_research/utilities/es_utils.py b/src/local_deep_research/utilities/es_utils.py
index f4ed7d8030..b6c673548a 100644
--- a/src/local_deep_research/utilities/es_utils.py
+++ b/src/local_deep_research/utilities/es_utils.py
@@ -67,6 +67,13 @@ class ElasticsearchManager:
logger.exception("Failed to connect to Elasticsearch")
raise ConnectionError(f"Could not connect to Elasticsearch: {e!s}")
+ def close(self) -> None:
+ """Close the Elasticsearch client and its connection pool."""
+ try:
+ self.client.close()
+ except Exception:
+ pass
+
def create_index(
self,
index_name: str,
diff --git a/src/local_deep_research/utilities/llm_utils.py b/src/local_deep_research/utilities/llm_utils.py
index e8a400b84a..5b3a3252de 100644
--- a/src/local_deep_research/utilities/llm_utils.py
+++ b/src/local_deep_research/utilities/llm_utils.py
@@ -12,6 +12,32 @@ from typing import Any, Optional, Dict
from ..config.thread_settings import get_setting_from_snapshot
+def close_llm(llm):
+ """Close underlying HTTP clients held by LLM instances.
+
+ Only ChatOllama creates per-instance httpx.Client objects that need
+ explicit close(). ChatAnthropic uses @lru_cache'd shared httpx
+ clients that must NOT be closed.
+ """
+ try:
+ # Unwrap ProcessingLLMWrapper
+ base = getattr(llm, "base_llm", llm)
+ # ChatOllama path: base._client is ollama.Client,
+ # base._client._client is httpx.Client
+ ollama_client = getattr(base, "_client", None)
+ if ollama_client is not None:
+ # Only close Ollama clients — Anthropic's are @lru_cache'd and shared.
+ # This relies on ollama's module structure; if the ollama package
+ # reorganises its internals this guard may need updating.
+ if not type(ollama_client).__module__.startswith("ollama"):
+ return
+ httpx_client = getattr(ollama_client, "_client", None)
+ if httpx_client is not None and hasattr(httpx_client, "close"):
+ httpx_client.close()
+ except Exception:
+ pass
+
+
def get_ollama_base_url(
settings_snapshot: Optional[Dict[str, Any]] = None,
) -> str:
diff --git a/src/local_deep_research/web/routes/metrics_routes.py b/src/local_deep_research/web/routes/metrics_routes.py
index 8fcb7c3a66..befa290c03 100644
--- a/src/local_deep_research/web/routes/metrics_routes.py
+++ b/src/local_deep_research/web/routes/metrics_routes.py
@@ -2052,6 +2052,7 @@ def api_link_analytics():
@login_required
def api_get_domain_classifications():
"""Get all domain classifications."""
+ classifier = None
try:
username = flask_session["username"]
@@ -2071,12 +2072,16 @@ def api_get_domain_classifications():
return jsonify(
{"status": "error", "message": "Failed to retrieve classifications"}
), 500
+ finally:
+ if classifier is not None:
+ classifier.close()
@metrics_bp.route("/api/domain-classifications/summary", methods=["GET"])
@login_required
def api_get_classifications_summary():
"""Get summary of domain classifications by category."""
+ classifier = None
try:
username = flask_session["username"]
@@ -2090,12 +2095,16 @@ def api_get_classifications_summary():
return jsonify(
{"status": "error", "message": "Failed to retrieve summary"}
), 500
+ finally:
+ if classifier is not None:
+ classifier.close()
@metrics_bp.route("/api/domain-classifications/classify", methods=["POST"])
@login_required
def api_classify_domains():
"""Trigger classification of a specific domain or batch classification."""
+ classifier = None
try:
username = flask_session["username"]
@@ -2154,6 +2163,9 @@ def api_classify_domains():
return jsonify(
{"status": "error", "message": "Failed to classify domains"}
), 500
+ finally:
+ if classifier is not None:
+ classifier.close()
@metrics_bp.route("/api/domain-classifications/progress", methods=["GET"])
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index ccac402336..f941d2092a 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -9,6 +9,7 @@ from loguru import logger
from ...exceptions import ResearchTerminatedException
from ...config.llm_config import get_llm
+from ...utilities.llm_utils import close_llm
# Output directory for research results
from ...config.paths import get_research_outputs_directory
@@ -908,20 +909,9 @@ def run_research_process(research_id, query, mode, **kwargs):
"Generating enhanced error report using ErrorReportGenerator"
)
- # Get LLM for error explanation if available
- try:
- llm = get_llm(
- research_id=research_id,
- research_context=shared_research_context,
- )
- except Exception:
- llm = None
- logger.warning(
- "Could not get LLM for error explanation"
- )
-
# Generate comprehensive error report
- error_generator = ErrorReportGenerator(llm)
+ # ErrorReportGenerator does not use LLM (kept for compat)
+ error_generator = ErrorReportGenerator()
clean_markdown = error_generator.generate_error_report(
error_message=raw_formatted_findings,
query=query,
@@ -1485,18 +1475,6 @@ def run_research_process(research_id, query, mode, **kwargs):
# Generate enhanced error report for failed research
enhanced_report_content = None
try:
- # Get LLM for error explanation if available
- try:
- llm = get_llm(
- research_id=research_id,
- research_context=shared_research_context,
- )
- except Exception:
- llm = None
- logger.warning(
- "Could not get LLM for error explanation in failure handler"
- )
-
# Get partial results if they exist
partial_results = results if "results" in locals() else None
search_iterations = (
@@ -1504,7 +1482,8 @@ def run_research_process(research_id, query, mode, **kwargs):
)
# Generate comprehensive error report
- error_generator = ErrorReportGenerator(llm)
+ # ErrorReportGenerator does not use LLM (kept for compat)
+ error_generator = ErrorReportGenerator()
enhanced_report_content = error_generator.generate_error_report(
error_message=f"Research failed: {e!s}",
query=query,
@@ -1677,6 +1656,14 @@ def run_research_process(research_id, query, mode, **kwargs):
system.close()
except Exception:
pass
+ # Close the LLM instance created for model/provider overrides.
+ # system.close() does NOT close the LLM passed to it via system.model,
+ # so we must close it explicitly here.
+ if "use_llm" in locals() and use_llm is not None:
+ try:
+ close_llm(use_llm)
+ except Exception:
+ pass
def cleanup_research_resources(research_id, username=None):
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py b/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py
index 46060f0e4c..21460b6112 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py
@@ -96,6 +96,14 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
logger.exception("Failed to connect to Elasticsearch")
raise ConnectionError(f"Could not connect to Elasticsearch: {e!s}")
+ def close(self) -> None:
+ """Close the Elasticsearch client and its connection pool."""
+ try:
+ self.client.close()
+ except Exception:
+ pass
+ super().close()
+
def _get_previews(self, query: str) -> List[Dict[str, Any]]:
"""
Get preview information for Elasticsearch documents.
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 4a68f62ffd..47a4558dc6 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
@@ -9,6 +9,7 @@ from loguru import logger
from ...config import llm_config, search_config
from ...security.safe_requests import safe_get
from ...utilities.json_utils import extract_json, get_llm_response_text
+from ...utilities.llm_utils import close_llm
from ..search_engine_base import BaseSearchEngine
@@ -53,6 +54,8 @@ class GitHubSearchEngine(BaseSearchEngine):
self.include_readme = include_readme
self.include_issues = include_issues
+ self._owns_llm = False
+
# API endpoints
self.api_base = "https://api.github.com"
self.search_endpoint = f"{self.api_base}/search/{search_type}"
@@ -72,6 +75,12 @@ class GitHubSearchEngine(BaseSearchEngine):
"No GitHub API key provided. Rate limits will be restricted."
)
+ def close(self) -> None:
+ """Close the lazily-loaded LLM client if this engine created it."""
+ if self._owns_llm and self.llm is not None:
+ close_llm(self.llm)
+ super().close()
+
def _handle_rate_limits(self, response):
"""Handle GitHub API rate limits by logging warnings and sleeping if necessary"""
remaining = int(response.headers.get("X-RateLimit-Remaining", 60))
@@ -104,6 +113,7 @@ class GitHubSearchEngine(BaseSearchEngine):
if not self.llm:
try:
self.llm = llm_config.get_llm()
+ self._owns_llm = True
if not self.llm:
logger.warning("No LLM available for query optimization")
return query
diff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.py
index 7d884d9fb5..0c316e2d77 100644
--- a/src/local_deep_research/web_search_engines/search_engine_base.py
+++ b/src/local_deep_research/web_search_engines/search_engine_base.py
@@ -1023,13 +1023,21 @@ Respond with ONLY the JSON array, no other text."""
Close any resources held by this search engine.
Subclasses with HTTP sessions or other resources should override this.
- The base implementation safely closes any 'session' attribute if present.
+ The base implementation safely closes any 'session' attribute if present
+ and closes content filters that hold resources.
"""
if hasattr(self, "session") and self.session is not None:
try:
self.session.close()
except Exception:
pass # Safe cleanup - don't raise on close
+ if hasattr(self, "_content_filters"):
+ for content_filter in self._content_filters:
+ if hasattr(content_filter, "close"):
+ try:
+ content_filter.close()
+ except Exception:
+ pass
def __enter__(self):
"""Support context manager usage."""