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.

refactor: add close() to LLM wrappers and fix 3 remaining FD leaks

LearningCircuited724b8d6142
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 4a7fb2ecd5..564a5eea46 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,7 +11,6 @@ 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
@@ -132,7 +131,7 @@ class JournalReputationFilter(BaseFilter):
except Exception:
pass
if self._owns_llm and self.model is not None:
- close_llm(self.model)
+ self.model.close()
@classmethod
def create_default(
@@ -225,12 +224,19 @@ class JournalReputationFilter(BaseFilter):
logger.info(f"Analyzing reputation of journal '{journal_name}'...")
# Perform a search for information about this journal.
- journal_info = self.__make_search_system().analyze_topic(
- f'Assess the reputability and reliability of the journal "'
- f'{journal_name}", with a particular focus on its quartile '
- f"ranking and peer review status. Be sure to specify the journal "
- f"name in any generated questions."
- )
+ search_system = self.__make_search_system()
+ try:
+ journal_info = search_system.analyze_topic(
+ f'Assess the reputability and reliability of the journal "'
+ f'{journal_name}", with a particular focus on its quartile '
+ f"ranking and peer review status. Be sure to specify the journal "
+ f"name in any generated questions."
+ )
+ finally:
+ try:
+ search_system.close()
+ except Exception:
+ pass
journal_info = "\n".join(
[f["content"] for f in journal_info["findings"]]
)
diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.py
index 4ffe2356c5..b83640f02e 100644
--- a/src/local_deep_research/api/research_functions.py
+++ b/src/local_deep_research/api/research_functions.py
@@ -15,7 +15,6 @@ 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
@@ -33,7 +32,7 @@ def _close_system(system):
except Exception:
pass
if hasattr(system, "model"):
- _close_llm(system.model)
+ system.model.close()
def _init_search_system(
@@ -152,7 +151,7 @@ def _init_search_system(
search_original_query=search_original_query,
)
except Exception:
- _close_llm(llm)
+ llm.close()
raise
# Override default settings with user-provided values
@@ -602,7 +601,7 @@ def analyze_documents(
search = get_search(collection_name, llm_instance=llm)
if not search:
- _close_llm(llm)
+ llm.close()
llm = None
return {
"summary": f"Error: Collection '{collection_name}' not found or not properly configured.",
@@ -697,4 +696,4 @@ def analyze_documents(
except Exception:
pass
if llm is not None:
- _close_llm(llm)
+ llm.close()
diff --git a/src/local_deep_research/benchmarks/cli.py b/src/local_deep_research/benchmarks/cli.py
index d1d501845d..c6e5732ae6 100644
--- a/src/local_deep_research/benchmarks/cli.py
+++ b/src/local_deep_research/benchmarks/cli.py
@@ -246,6 +246,9 @@ def run_profiling(args):
speed_profiler.start()
resource_monitor.start()
+ llm = None
+ search = None
+ system = None
try:
# Initialize system
with speed_profiler.timer("initialization"):
@@ -351,6 +354,22 @@ def run_profiling(args):
logger.exception("Error during profiling")
return 1
+ finally:
+ if system is not None:
+ try:
+ system.close()
+ except Exception:
+ pass
+ if search is not None:
+ try:
+ search.close()
+ except Exception:
+ pass
+ if llm is not None:
+ try:
+ llm.close()
+ except Exception:
+ pass
def main():
diff --git a/src/local_deep_research/benchmarks/comparison/evaluator.py b/src/local_deep_research/benchmarks/comparison/evaluator.py
index 7d3485368d..a0dd8fc314 100644
--- a/src/local_deep_research/benchmarks/comparison/evaluator.py
+++ b/src/local_deep_research/benchmarks/comparison/evaluator.py
@@ -253,6 +253,9 @@ def _evaluate_single_configuration(
speed_profiler.start()
resource_monitor.start()
+ llm = None
+ search = None
+ system = None
try:
# Get LLM
with speed_profiler.timer("llm_initialization"):
@@ -346,6 +349,22 @@ def _evaluate_single_configuration(
"timing_details": speed_profiler.get_timings(),
"resource_details": resource_monitor.get_combined_stats(),
}
+ finally:
+ if system is not None:
+ try:
+ system.close()
+ except Exception:
+ pass
+ if search is not None:
+ try:
+ search.close()
+ except Exception:
+ pass
+ if llm is not None:
+ try:
+ llm.close()
+ except Exception:
+ pass
def _calculate_average_metrics(results: List[Dict[str, Any]]) -> Dict[str, Any]:
diff --git a/src/local_deep_research/benchmarks/graders.py b/src/local_deep_research/benchmarks/graders.py
index 427e0c15a0..0d320a51bc 100644
--- a/src/local_deep_research/benchmarks/graders.py
+++ b/src/local_deep_research/benchmarks/graders.py
@@ -13,7 +13,6 @@ 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
@@ -291,7 +290,7 @@ def grade_single_result(
"grader_response": f"Grading failed: {e!s}",
}
finally:
- close_llm(evaluation_llm)
+ evaluation_llm.close()
def grade_results(
@@ -326,7 +325,7 @@ def grade_results(
progress_callback,
)
finally:
- close_llm(evaluation_llm)
+ evaluation_llm.close()
def _grade_results_inner(
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.py
index 529b813c86..282b7efc6e 100644
--- a/src/local_deep_research/config/llm_config.py
+++ b/src/local_deep_research/config/llm_config.py
@@ -1031,4 +1031,13 @@ def wrap_llm_without_think_tags(
def __getattr__(self, name):
return getattr(self.base_llm, name)
+ def close(self):
+ """Close underlying HTTP clients held by this LLM. Idempotent."""
+ try:
+ from ..utilities.llm_utils import close_llm
+
+ close_llm(self.base_llm)
+ except Exception:
+ pass
+
return ProcessingLLMWrapper(llm)
diff --git a/src/local_deep_research/domain_classifier/classifier.py b/src/local_deep_research/domain_classifier/classifier.py
index 4ef29f33c4..23bc7e8f3c 100644
--- a/src/local_deep_research/domain_classifier/classifier.py
+++ b/src/local_deep_research/domain_classifier/classifier.py
@@ -10,7 +10,6 @@ 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
@@ -105,7 +104,7 @@ class DomainClassifier:
def close(self) -> None:
"""Close the LLM client if one was created."""
if self.llm is not None:
- close_llm(self.llm)
+ self.llm.close()
def _get_domain_samples(
self, domain: str, session: Session, limit: int = 5
diff --git a/src/local_deep_research/news/core/news_analyzer.py b/src/local_deep_research/news/core/news_analyzer.py
index 12637bc5ce..e7f95e3040 100644
--- a/src/local_deep_research/news/core/news_analyzer.py
+++ b/src/local_deep_research/news/core/news_analyzer.py
@@ -11,7 +11,6 @@ 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:
@@ -42,7 +41,7 @@ class NewsAnalyzer:
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)
+ self.llm_client.close()
def analyze_news(
self, search_results: List[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 e61be499bf..39adccb02b 100644
--- a/src/local_deep_research/news/utils/headline_generator.py
+++ b/src/local_deep_research/news/utils/headline_generator.py
@@ -36,7 +36,6 @@ 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)
@@ -81,7 +80,7 @@ Generate only the headline text, nothing else."""
logger.debug(f"Generated headline: {headline}")
return headline
finally:
- close_llm(llm)
+ llm.close()
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 608bbf67c8..9c3ad7bd22 100644
--- a/src/local_deep_research/news/utils/topic_generator.py
+++ b/src/local_deep_research/news/utils/topic_generator.py
@@ -41,7 +41,6 @@ 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}"
@@ -101,7 +100,7 @@ Return ONLY a JSON array of topic strings, like: ["Topic 1", "Topic 2", "Topic 3
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)
+ llm.close()
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 f2bd7ac117..ed14e47256 100644
--- a/src/local_deep_research/report_generator.py
+++ b/src/local_deep_research/report_generator.py
@@ -10,7 +10,6 @@ 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
@@ -82,7 +81,7 @@ class IntegratedReportGenerator:
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)
+ self.model.close()
def generate_report(
self,
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index f941d2092a..1cd791139f 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -9,7 +9,6 @@ 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
@@ -1661,7 +1660,7 @@ def run_research_process(research_id, query, mode, **kwargs):
# so we must close it explicitly here.
if "use_llm" in locals() and use_llm is not None:
try:
- close_llm(use_llm)
+ use_llm.close()
except Exception:
pass
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 47a4558dc6..885571ff6a 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,7 +9,6 @@ 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
@@ -78,7 +77,7 @@ class GitHubSearchEngine(BaseSearchEngine):
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)
+ self.llm.close()
super().close()
def _handle_rate_limits(self, response):
diff --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.py
index 60c4306c5e..a1d879599f 100644
--- 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.py
@@ -198,6 +198,15 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):
def __getattr__(self, name):
return getattr(self.base_llm, name)
+ def close(self):
+ """Close underlying HTTP clients held by this LLM. Idempotent."""
+ try:
+ from local_deep_research.utilities.llm_utils import close_llm
+
+ close_llm(self.base_llm)
+ except Exception:
+ pass
+
def __str__(self):
return f"RateLimited({str(self.base_llm)})"