~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
refactor: remove 5 dead functions from utilities and config (-229 lines) (#3186)
LearningCircuitf8e10776b75e
diff --git a/src/local_deep_research/config/search_config.py b/src/local_deep_research/config/search_config.pyindex 2bf3c301a3..bee191b569 100644--- a/src/local_deep_research/config/search_config.py+++ b/src/local_deep_research/config/search_config.py@@ -15,22 +15,6 @@ QUALITY_CHECK_DDG_URLS = True# get_setting_from_snapshot is now imported from thread_settings-def get_search_snippets_only_setting(username=None, settings_snapshot=None):- """- Lazily retrieve the 'search.snippets_only' setting.-- Args:- username: Optional username for thread context- settings_snapshot: Optional settings snapshot for thread safety- """- return get_setting_from_snapshot(- "search.snippets_only",- True,- username=username,- settings_snapshot=settings_snapshot,- )--# Expose get_search functiondef get_search(search_tool=None,diff --git a/src/local_deep_research/utilities/db_utils.py b/src/local_deep_research/utilities/db_utils.pyindex 986ca54dd7..bd60805062 100644--- a/src/local_deep_research/utilities/db_utils.py+++ b/src/local_deep_research/utilities/db_utils.py@@ -1,5 +1,5 @@import functools-from typing import Any, Callable, Dict+from typing import Any, Callablefrom cachetools import LRUCachefrom flask import (@@ -205,58 +205,3 @@ def no_db_settings(func: Callable[..., Any]) -> Callable[..., Any]:manager.db_session = db_sessionreturn wrapper---def get_setting_from_db_main_thread(- key: str, default_value: Any | None = None, username: str | None = None-) -> str | Dict[str, Any] | None:- """- Get a setting from the database with fallback to default value-- Args:- key: The setting key.- default_value: If the setting is not found, it will return this instead.- username: Optional username for thread context (e.g., background research threads).-- Returns:- The setting value.-- """- # CRITICAL: Detect if we're in a background thread and raise an error- import threading-- # Check if we're in a background thread- thread_name = threading.current_thread().name-- # Allow MainThread during startup, but not other threads- if not has_app_context() and thread_name != "MainThread":- thread_id = threading.get_ident()- raise RuntimeError(- f"get_db_setting('{key}') called from background thread '{thread_name}' (ID: {thread_id}). "- f"Database access from threads is not allowed. Use settings_snapshot or thread-local settings context."- )-- try:- # Use the new session context to ensure proper database access- from ..database.session_context import get_user_db_session-- try:- with get_user_db_session(username) as db_session:- if db_session:- # Use the unified settings manager- settings_manager = get_settings_manager(- db_session, username- )- return settings_manager.get_setting(- key, default=default_value- )- except Exception:- logger.debug(- "fall back to default if session unavailable", exc_info=True- )-- except Exception:- logger.exception(f"Error getting setting {key} from database")-- logger.warning(f"Could not read setting '{key}' from the database.")- return default_valuediff --git a/src/local_deep_research/utilities/llm_utils.py b/src/local_deep_research/utilities/llm_utils.pyindex 0ee2583d1f..6729c4b157 100644--- a/src/local_deep_research/utilities/llm_utils.py+++ b/src/local_deep_research/utilities/llm_utils.py@@ -18,7 +18,6 @@ __all__ = ["get_ollama_base_url","get_server_url","fetch_ollama_models",- "get_model",]@@ -116,7 +115,6 @@ def get_server_url(settings_snapshot: Optional[Dict[str, Any]] = None) -> str:Returns:Server URL with trailing slash"""- from loguru import loggerserver_url = None@@ -175,7 +173,6 @@ def fetch_ollama_models(List of model dicts with 'value' (model name) and 'label' (display name) keys.Returns empty list on error."""- from loguru import loggerfrom ..security import safe_getmodels = []@@ -212,144 +209,3 @@ def fetch_ollama_models(logger.exception("Error fetching Ollama models")return models---def get_model(- model_name: Optional[str] = None,- model_type: Optional[str] = None,- temperature: Optional[float] = None,- **kwargs,-) -> Any:- """- Get a language model instance as fallback when llm_config.get_llm is not available.-- Args:- model_name: Name of the model to use- model_type: Type of the model provider- temperature: Model temperature- **kwargs: Additional parameters-- Returns:- LangChain language model instance- """- # Get default values from kwargs or use reasonable defaults- model_name = model_name or kwargs.get("DEFAULT_MODEL", "mistral")- model_type = model_type or kwargs.get("DEFAULT_MODEL_TYPE", "ollama")- temperature = temperature or kwargs.get("DEFAULT_TEMPERATURE", 0.7)- max_tokens = kwargs.get("max_tokens", kwargs.get("MAX_TOKENS", 30000))-- # Common parameters- common_params = {- "temperature": temperature,- "max_tokens": max_tokens,- }-- # Add additional kwargs- common_params.update(- {- key: value- for key, value in kwargs.items()- if key- not in [- "DEFAULT_MODEL",- "DEFAULT_MODEL_TYPE",- "DEFAULT_TEMPERATURE",- "MAX_TOKENS",- ]- }- )-- # Try to load the model based on type- if model_type == "ollama":- try:- from langchain_ollama import ChatOllama-- return ChatOllama(model=model_name, **common_params)- except ImportError:- try:- from langchain_community.llms import Ollama-- return Ollama(model=model_name, **common_params)- except ImportError:- logger.exception(- "Neither langchain_ollama nor langchain_community.llms.Ollama available"- )- raise-- elif model_type == "openai":- try:- from langchain_openai import ChatOpenAI-- api_key = get_setting_from_snapshot("llm.openai.api_key")- if not api_key:- raise ValueError("OpenAI API key not found in settings")- return ChatOpenAI(- model=model_name, api_key=api_key, **common_params- )- except ImportError:- logger.exception("langchain_openai not available")- raise-- elif model_type == "anthropic":- try:- from langchain_anthropic import ChatAnthropic-- api_key = get_setting_from_snapshot("llm.anthropic.api_key")- if not api_key:- raise ValueError("Anthropic API key not found in settings")- return ChatAnthropic(- model=model_name, anthropic_api_key=api_key, **common_params- )- except ImportError:- logger.exception("langchain_anthropic not available")- raise-- elif model_type == "openai_endpoint":- try:- from langchain_openai import ChatOpenAI-- api_key = get_setting_from_snapshot("llm.openai_endpoint.api_key")- if not api_key:- raise ValueError(- "OpenAI endpoint API key not found in settings"- )-- endpoint_url = kwargs.get(- "OPENAI_ENDPOINT_URL",- get_setting_from_snapshot(- "llm.openai_endpoint.url", "https://openrouter.ai/api/v1"- ),- )-- if model_name is None and not kwargs.get(- "OPENAI_ENDPOINT_REQUIRES_MODEL", True- ):- return ChatOpenAI( # type: ignore[call-arg]- api_key=api_key,- openai_api_base=endpoint_url,- **common_params,- )- return ChatOpenAI( # type: ignore[call-arg]- model=model_name,- api_key=api_key,- openai_api_base=endpoint_url,- **common_params,- )- except ImportError:- logger.exception("langchain_openai not available")- raise-- # Default fallback- try:- from langchain_ollama import ChatOllama-- logger.warning(- f"Unknown model type '{model_type}', defaulting to Ollama"- )- return ChatOllama(model=model_name, **common_params)- except (ImportError, Exception):- logger.exception("Failed to load any model")-- raise ValueError(- "No language models available. Please install Ollama or set up API keys."- )diff --git a/src/local_deep_research/utilities/search_utilities.py b/src/local_deep_research/utilities/search_utilities.pyindex 0c7e7e88df..85ba6443f9 100644--- a/src/local_deep_research/utilities/search_utilities.py+++ b/src/local_deep_research/utilities/search_utilities.py@@ -418,11 +418,3 @@ def format_findings(logger.info("Finished format_findings utility.")return "".join(parts)---def print_search_results(search_results):- formatted_text = ""- links = extract_links_from_search_results(search_results)- if links:- formatted_text = format_links_to_markdown(links)- logger.info(formatted_text)diff --git a/tests/config/test_search_config.py b/tests/config/test_search_config.pyindex f4f11e8e00..2c27172223 100644--- a/tests/config/test_search_config.py+++ b/tests/config/test_search_config.py@@ -4,7 +4,6 @@ from unittest.mock import MagicMock, patchfrom local_deep_research.config.search_config import (- get_search_snippets_only_setting,get_search,QUALITY_CHECK_DDG_URLS,)@@ -18,33 +17,6 @@ class TestQualityCheckConstant:assert isinstance(QUALITY_CHECK_DDG_URLS, bool)-class TestGetSearchSnippetsOnlySetting:- """Tests for get_search_snippets_only_setting function."""-- def test_returns_value_from_snapshot(self):- """Should return value from settings snapshot."""- snapshot = {"search.snippets_only": False}- with patch(- "local_deep_research.config.search_config.get_setting_from_snapshot",- return_value=False,- ):- result = get_search_snippets_only_setting(- settings_snapshot=snapshot- )- assert result is False-- def test_uses_default_true(self):- """Should default to True."""- with patch(- "local_deep_research.config.search_config.get_setting_from_snapshot",- return_value=True,- ) as mock_get:- get_search_snippets_only_setting()- mock_get.assert_called_once()- call_args = mock_get.call_args- assert call_args[0][1] is True # default argument--class TestGetSearch:"""Tests for get_search function."""diff --git a/tests/performance/strategies/test_adaptive_strategy.py b/tests/performance/strategies/test_adaptive_strategy.pydeleted file mode 100644index c262be09f3..0000000000--- a/tests/performance/strategies/test_adaptive_strategy.py+++ /dev/null@@ -1,137 +0,0 @@-#!/usr/bin/env python3-"""-Test the adaptive decomposition strategy with a puzzle-like query.-"""--import pytest--from local_deep_research.advanced_search_system.strategies import (- AdaptiveDecompositionStrategy,- SmartDecompositionStrategy,-)-from local_deep_research.utilities.llm_utils import get_model-from local_deep_research.web_search_engines.search_engine_factory import (- create_search_engine,-)---def test_puzzle_query():- """Test the adaptive strategy with the hiking location puzzle."""-- # The puzzle query- query = """I am looking for a hike to a specific scenic location. I know these details about the location:- It was formed during the last ice age. Part of its name relates to a body part.- Someone fell from the viewpoint between 2000 and 2021.- In 2022, the Grand Canyon had 84.5x more Search and Rescue incidents than this hike had in 2014.- What is the name of this location?"""-- # Initialize components- model = get_model()- search = create_search_engine("meta_search")- all_links = []-- print("Testing Adaptive Decomposition Strategy")- print("=" * 50)- print(f"Query: {query[:100]}...")- print()-- # Test with adaptive strategy- adaptive_strategy = AdaptiveDecompositionStrategy(- model=model,- search=search,- all_links_of_system=all_links,- max_steps=10,- min_confidence=0.8,- source_search_iterations=2,- source_questions_per_iteration=15,- )-- # Set up progress callback for visibility- def progress_callback(message, progress, data):- print(f"[{progress}%] {message}")- if "step_type" in data:- print(f" - Step type: {data['step_type']}")-- adaptive_strategy.set_progress_callback(progress_callback)-- # Run analysis- print("\nRunning adaptive analysis...")- results = adaptive_strategy.analyze_topic(query)-- # Display results- print("\n" + "=" * 50)- print("RESULTS")- print("=" * 50)-- print(f"\nStrategy used: {results.get('strategy', 'unknown')}")- print(f"Total steps: {results.get('iterations', 0)}")-- if "working_knowledge" in results:- knowledge = results["working_knowledge"]- print("\nExtracted Constraints:")- for constraint in knowledge.get("constraints", []):- print(f" - {constraint}")-- print("\nCandidate Locations:")- for candidate in knowledge.get("candidates", []):- print(f" - {candidate}")-- print("\nVerified Facts:")- for fact in knowledge.get("verified_facts", []):- print(f" - {fact}")-- print(- f"\nFinal Answer:\n{results.get('current_knowledge', 'No answer found')}"- )-- # Also test with smart strategy to see classification- print("\n" + "=" * 50)- print("Testing Smart Decomposition Strategy")- print("=" * 50)-- smart_strategy = SmartDecompositionStrategy(- model=model, search=search, all_links_of_system=all_links- )-- smart_strategy.set_progress_callback(progress_callback)-- print("\nRunning smart analysis...")- smart_results = smart_strategy.analyze_topic(query)-- print(f"\nStrategy chosen: {smart_results.get('strategy', 'unknown')}")---def test_simpler_query():- """Test with a simpler query to see the difference."""-- query = "What is the capital of France?"-- model = get_model()- search = create_search_engine("meta_search")- all_links = []-- print("\n" + "=" * 50)- print("Testing with Simple Query")- print("=" * 50)- print(f"Query: {query}")-- smart_strategy = SmartDecompositionStrategy(- model=model, search=search, all_links_of_system=all_links- )-- def progress_callback(message, progress, data):- print(f"[{progress}%] {message}")-- smart_strategy.set_progress_callback(progress_callback)-- results = smart_strategy.analyze_topic(query)-- print(f"\nStrategy chosen: {results.get('strategy', 'unknown')}")- print(f"Answer: {results.get('current_knowledge', 'No answer')[:200]}...")---if __name__ == "__main__":- test_puzzle_query()- test_simpler_query()diff --git a/tests/performance/strategies/test_iterative_reasoning.py b/tests/performance/strategies/test_iterative_reasoning.pydeleted file mode 100755index a5e296096d..0000000000--- a/tests/performance/strategies/test_iterative_reasoning.py+++ /dev/null@@ -1,229 +0,0 @@-#!/usr/bin/env python3-"""-Test the iterative reasoning strategy with complex queries.-"""--import json--import pytest--from local_deep_research.advanced_search_system.strategies import (- IterativeReasoningStrategy,-)-from local_deep_research.utilities.llm_utils import get_model-from local_deep_research.web_search_engines.search_engine_factory import (- create_search_engine,-)---def test_puzzle_query():- """Test the iterative reasoning strategy with the hiking location puzzle."""-- # The puzzle query- query = """I am looking for a hike to a specific scenic location. I know these details about the location:- It was formed during the last ice age. Part of its name relates to a body part.- Someone fell from the viewpoint between 2000 and 2021.- In 2022, the Grand Canyon had 84.5x more Search and Rescue incidents than this hike had in 2014.- What is the name of this location?"""-- # Initialize components- model = get_model()- search = create_search_engine("meta_search")- all_links = []-- print("Testing Iterative Reasoning Strategy")- print("=" * 50)- print(f"Query: {query[:100]}...")- print()-- # Create strategy- strategy = IterativeReasoningStrategy(- model=model,- search=search,- all_links_of_system=all_links,- max_iterations=8,- confidence_threshold=0.85,- search_iterations_per_round=1,- questions_per_search=15,- )-- # Set up progress callback- def progress_callback(message, progress, data):- print(f"[{progress:3d}%] {message}")- if "iteration" in data:- print(- f" Iteration: {data['iteration']}, Confidence: {data.get('confidence', 0):.1%}"- )-- strategy.set_progress_callback(progress_callback)-- # Run analysis- print("\nRunning iterative reasoning analysis...")- results = strategy.analyze_topic(query)-- # Display results- print("\n" + "=" * 50)- print("RESULTS")- print("=" * 50)-- print(f"\nStrategy: {results.get('strategy', 'unknown')}")- print(f"Total iterations: {results.get('iterations', 0)}")-- if "knowledge_state" in results:- knowledge = results["knowledge_state"]-- print("\nKEY FACTS DISCOVERED:")- for i, fact in enumerate(knowledge.get("key_facts", []), 1):- print(f" {i}. {fact}")-- print("\nCANDIDATE ANSWERS:")- for candidate in knowledge.get("candidate_answers", []):- print(- f" - {candidate['answer']} (confidence: {candidate['confidence']:.1%})"- )-- print("\nREMAINING UNCERTAINTIES:")- for uncertainty in knowledge.get("uncertainties", []):- print(f" ? {uncertainty}")-- print("\nSEARCH HISTORY:")- for i, search in enumerate(knowledge.get("search_history", []), 1):- print(f" {i}. {search['query']}")-- print("\nFINAL ANSWER:")- print(results.get("current_knowledge", "No answer found"))-- print(- f"\nFinal Confidence: {results.get('knowledge_state', {}).get('confidence', 0):.1%}"- )-- # Save results for analysis- with open("iterative_reasoning_results.json", "w") as f:- json.dump(results, f, indent=2, default=str)- print("\nFull results saved to: iterative_reasoning_results.json")---def test_research_query():- """Test with a research-oriented query."""-- query = "What are the environmental impacts of lithium mining for electric vehicle batteries?"-- model = get_model()- search = create_search_engine("meta_search")- all_links = []-- print("\n" + "=" * 50)- print("Testing with Research Query")- print("=" * 50)- print(f"Query: {query}")-- strategy = IterativeReasoningStrategy(- model=model,- search=search,- all_links_of_system=all_links,- max_iterations=5,- confidence_threshold=0.8,- search_iterations_per_round=1,- questions_per_search=20,- )-- def progress_callback(message, progress, data):- print(f"[{progress:3d}%] {message}")-- strategy.set_progress_callback(progress_callback)-- results = strategy.analyze_topic(query)-- print(f"\nIterations used: {results.get('iterations', 0)}")- print(- f"Final confidence: {results.get('knowledge_state', {}).get('confidence', 0):.1%}"- )- print(f"\nAnswer preview: {results.get('current_knowledge', '')[:300]}...")---def demonstrate_knowledge_building():- """Show how knowledge builds up over iterations."""-- query = "What is the tallest building in the city where the Python programming language was created?"-- model = get_model()- search = create_search_engine("meta_search")- all_links = []-- print("\n" + "=" * 50)- print("Demonstrating Knowledge Building")- print("=" * 50)- print(f"Query: {query}")- print()-- strategy = IterativeReasoningStrategy(- model=model,- search=search,- all_links_of_system=all_links,- max_iterations=6,- confidence_threshold=0.9,- search_iterations_per_round=1,- questions_per_search=10,- )-- # Custom callback to show knowledge building- def detailed_callback(message, progress, data):- print(f"\n[{progress:3d}%] {message}")-- # If we just finished an iteration, show what we learned- if "phase" in data and data["phase"] == "reasoning" and progress > 20:- # Access the strategy's knowledge state directly- if hasattr(strategy, "knowledge_state"):- state = strategy.knowledge_state- print(- f"\n--- Knowledge State at Iteration {state.iteration} ---"- )- print(f"Facts discovered: {len(state.key_facts)}")- if state.key_facts:- print(f"Latest fact: {state.key_facts[-1]}")-- if state.candidate_answers:- best = max(- state.candidate_answers, key=lambda x: x["confidence"]- )- print(- f"Best answer so far: {best['answer']} ({best['confidence']:.1%})"- )-- print(f"Confidence: {state.confidence:.1%}")- print("-" * 40)-- strategy.set_progress_callback(detailed_callback)-- results = strategy.analyze_topic(query)-- print("\n" + "=" * 50)- print("FINAL KNOWLEDGE STATE")- print("=" * 50)-- knowledge = results.get("knowledge_state", {})-- print("\nLearned Facts (in order):")- for i, fact in enumerate(knowledge.get("key_facts", []), 1):- print(f" {i}. {fact}")-- print(f"\nFinal Answer: {results.get('current_knowledge', 'No answer')}")---if __name__ == "__main__":- # Run different test scenarios- print("ITERATIVE REASONING STRATEGY TESTS")- print("==================================\n")-- # Test 1: Complex puzzle query- test_puzzle_query()-- # Test 2: Research query- test_research_query()-- # Test 3: Knowledge building demo- demonstrate_knowledge_building()-- print("\n\nAll tests completed!")diff --git a/tests/utilities/test_db_utils.py b/tests/utilities/test_db_utils.pyindex e88a8c62e0..d6baaa9592 100644--- a/tests/utilities/test_db_utils.py+++ b/tests/utilities/test_db_utils.py@@ -1,7 +1,7 @@"""Tests for db_utils module."""import threading-from unittest.mock import Mock, patch, MagicMock+from unittest.mock import Mock, patchimport pytest@@ -247,78 +247,6 @@ class TestNoDbSettings:assert my_function.__doc__ == "My docstring."-class TestGetSettingFromDbMainThread:- """Tests for get_setting_from_db_main_thread function."""-- def test_raises_error_from_background_thread(self):- """Should raise error when called from background thread."""- from local_deep_research.utilities.db_utils import (- get_setting_from_db_main_thread,- )-- error_raised = [False]-- def background_task():- try:- get_setting_from_db_main_thread("test.key")- except RuntimeError:- error_raised[0] = True-- thread = threading.Thread(target=background_task, name="BGThread")- thread.start()- thread.join()-- assert error_raised[0], (- "Should raise RuntimeError from background thread"- )-- def test_returns_default_when_no_session(self):- """Should return default when no database session available."""- from local_deep_research.utilities.db_utils import (- get_setting_from_db_main_thread,- )-- with patch(- "local_deep_research.utilities.db_utils.has_app_context",- return_value=True,- ):- # Simulate get_user_db_session returning None- with patch(- "local_deep_research.database.session_context.get_user_db_session"- ) as mock_context:- mock_cm = MagicMock()- mock_cm.__enter__ = Mock(return_value=None)- mock_cm.__exit__ = Mock(return_value=None)- mock_context.return_value = mock_cm-- result = get_setting_from_db_main_thread(- "test.key", default_value="fallback"- )-- assert result == "fallback"-- def test_returns_default_on_exception(self):- """Should return default value on exception."""- from local_deep_research.utilities.db_utils import (- get_setting_from_db_main_thread,- )-- with patch(- "local_deep_research.utilities.db_utils.has_app_context",- return_value=True,- ):- # Force an exception in the outer try block- with patch(- "local_deep_research.database.session_context.get_user_db_session",- side_effect=Exception("DB error"),- ):- result = get_setting_from_db_main_thread(- "test.key", default_value="fallback"- )-- assert result == "fallback"--class TestDataDir:"""Tests for DATA_DIR constant."""diff --git a/tests/utilities/test_db_utils_deep_coverage.py b/tests/utilities/test_db_utils_deep_coverage.pyindex a490655970..8500d626dd 100644--- a/tests/utilities/test_db_utils_deep_coverage.py+++ b/tests/utilities/test_db_utils_deep_coverage.py@@ -4,11 +4,9 @@ Deep coverage tests for utilities/db_utils.py.Targets uncovered paths:- get_db_session: Flask session username lookup, exception in Flask context- get_settings_manager: request context username extraction-- get_setting_from_db_main_thread: successful session + settings read"""-import threading-from unittest.mock import Mock, MagicMock, patch+from unittest.mock import Mock, patchclass TestGetDbSessionFlaskSessionUsername:@@ -114,96 +112,3 @@ class TestGetSettingsManagerRequestContext:result = get_settings_manager()assert result is not None---class TestGetSettingFromDbMainThreadSuccess:- """Cover get_setting_from_db_main_thread with successful DB read."""-- def test_returns_setting_value_from_db(self):- """Should return setting value when session and manager work."""- from local_deep_research.utilities.db_utils import (- get_setting_from_db_main_thread,- )-- mock_session = Mock()- mock_ctx = MagicMock()- mock_ctx.__enter__ = Mock(return_value=mock_session)- mock_ctx.__exit__ = Mock(return_value=False)-- mock_manager = Mock()- mock_manager.get_setting.return_value = "expected_value"-- with patch(- "local_deep_research.utilities.db_utils.has_app_context",- return_value=True,- ):- with patch(- "local_deep_research.database.session_context.get_user_db_session",- return_value=mock_ctx,- ):- with patch(- "local_deep_research.utilities.db_utils.get_settings_manager",- return_value=mock_manager,- ):- result = get_setting_from_db_main_thread(- "test.key", default_value="fallback"- )-- assert result == "expected_value"- mock_manager.get_setting.assert_called_once_with(- "test.key", default="fallback"- )-- def test_inner_exception_falls_back_to_default(self):- """When inner session context raises, falls to outer try and returns default."""- from local_deep_research.utilities.db_utils import (- get_setting_from_db_main_thread,- )-- mock_ctx = MagicMock()- mock_ctx.__enter__ = Mock(side_effect=Exception("session error"))- mock_ctx.__exit__ = Mock(return_value=False)-- with patch(- "local_deep_research.utilities.db_utils.has_app_context",- return_value=True,- ):- with patch(- "local_deep_research.database.session_context.get_user_db_session",- return_value=mock_ctx,- ):- result = get_setting_from_db_main_thread(- "key", default_value="default"- )- assert result == "default"-- def test_background_thread_with_has_app_context_true(self):- """Background thread with app context should NOT raise."""- from local_deep_research.utilities.db_utils import (- get_setting_from_db_main_thread,- )-- results = [None]-- def bg_task():- with patch(- "local_deep_research.utilities.db_utils.has_app_context",- return_value=True,- ):- mock_ctx = MagicMock()- mock_ctx.__enter__ = Mock(return_value=None)- mock_ctx.__exit__ = Mock(return_value=False)- with patch(- "local_deep_research.database.session_context.get_user_db_session",- return_value=mock_ctx,- ):- results[0] = get_setting_from_db_main_thread(- "key", default_value="bg_default"- )-- thread = threading.Thread(target=bg_task, name="BGWithContext")- thread.start()- thread.join()-- # With app context, should not raise, but session is None so returns default- assert results[0] == "bg_default"diff --git a/tests/utilities/test_llm_utils.py b/tests/utilities/test_llm_utils.pyindex 7aaa19019b..12c22cbd80 100644--- a/tests/utilities/test_llm_utils.py+++ b/tests/utilities/test_llm_utils.py@@ -1,12 +1,9 @@"""Tests for llm_utils module."""-from unittest.mock import Mock, patch, MagicMock--import pytest+from unittest.mock import Mock, patchfrom local_deep_research.utilities.llm_utils import (fetch_ollama_models,- get_model,get_model_identifier,get_ollama_base_url,get_server_url,@@ -364,367 +361,3 @@ class TestFetchOllamaModels:result = fetch_ollama_models("http://localhost:11434")assert result == []---class TestGetModel:- """Tests for get_model function."""-- def test_creates_ollama_model_by_default(self):- """Should create Ollama model by default."""- mock_chat_ollama = Mock()- with patch(- "local_deep_research.utilities.llm_utils.ChatOllama",- mock_chat_ollama,- create=True,- ):- with patch.dict(- "sys.modules",- {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},- ):- get_model(model_name="llama2", model_type="ollama")-- mock_chat_ollama.assert_called_once()- call_kwargs = mock_chat_ollama.call_args.kwargs- assert call_kwargs["model"] == "llama2"-- def test_uses_default_model_name(self):- """Should use DEFAULT_MODEL from kwargs if model_name not provided."""- mock_chat_ollama = Mock()- with patch(- "local_deep_research.utilities.llm_utils.ChatOllama",- mock_chat_ollama,- create=True,- ):- with patch.dict(- "sys.modules",- {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},- ):- get_model(model_type="ollama", DEFAULT_MODEL="custom-model")-- mock_chat_ollama.assert_called_once()- call_kwargs = mock_chat_ollama.call_args.kwargs- assert call_kwargs["model"] == "custom-model"-- def test_uses_default_temperature(self):- """Should use DEFAULT_TEMPERATURE from kwargs."""- mock_chat_ollama = Mock()- with patch(- "local_deep_research.utilities.llm_utils.ChatOllama",- mock_chat_ollama,- create=True,- ):- with patch.dict(- "sys.modules",- {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},- ):- get_model(- model_name="test",- model_type="ollama",- DEFAULT_TEMPERATURE=0.5,- )-- call_kwargs = mock_chat_ollama.call_args.kwargs- assert call_kwargs["temperature"] == 0.5-- def test_uses_max_tokens(self):- """Should use max_tokens from kwargs."""- mock_chat_ollama = Mock()- with patch(- "local_deep_research.utilities.llm_utils.ChatOllama",- mock_chat_ollama,- create=True,- ):- with patch.dict(- "sys.modules",- {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},- ):- get_model(- model_name="test", model_type="ollama", max_tokens=5000- )-- call_kwargs = mock_chat_ollama.call_args.kwargs- assert call_kwargs["max_tokens"] == 5000-- def test_openai_model_requires_api_key(self):- """Should raise error if OpenAI API key not found."""- with patch(- "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"- ) as mock_get:- mock_get.return_value = None # No API key-- with pytest.raises(ValueError, match="OpenAI API key not found"):- get_model(model_name="gpt-4", model_type="openai")-- def test_anthropic_model_requires_api_key(self):- """Should raise error if Anthropic API key not found."""- with patch(- "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"- ) as mock_get:- mock_get.return_value = None # No API key-- with pytest.raises(ValueError, match="Anthropic API key not found"):- get_model(model_name="claude-3", model_type="anthropic")-- def test_openai_endpoint_requires_api_key(self):- """Should raise error if OpenAI endpoint API key not found."""- with patch(- "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"- ) as mock_get:- mock_get.return_value = None # No API key-- with pytest.raises(- ValueError, match="OpenAI endpoint API key not found"- ):- get_model(model_name="model", model_type="openai_endpoint")-- def test_unknown_model_type_falls_back_to_ollama(self):- """Should fall back to Ollama for unknown model types."""- mock_chat_ollama = Mock()- with patch(- "local_deep_research.utilities.llm_utils.ChatOllama",- mock_chat_ollama,- create=True,- ):- with patch.dict(- "sys.modules",- {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},- ):- with patch(- "local_deep_research.utilities.llm_utils.logger"- ) as mock_logger:- get_model(model_name="test", model_type="unknown_type")-- mock_logger.warning.assert_called()- mock_chat_ollama.assert_called_once()-- def test_passes_additional_kwargs(self):- """Should pass additional kwargs to model."""- mock_chat_ollama = Mock()- with patch(- "local_deep_research.utilities.llm_utils.ChatOllama",- mock_chat_ollama,- create=True,- ):- with patch.dict(- "sys.modules",- {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},- ):- get_model(- model_name="test",- model_type="ollama",- custom_param="value",- )-- call_kwargs = mock_chat_ollama.call_args.kwargs- assert call_kwargs["custom_param"] == "value"-- def test_excludes_config_kwargs_from_model(self):- """Should not pass config kwargs like DEFAULT_MODEL to model."""- mock_chat_ollama = Mock()- with patch(- "local_deep_research.utilities.llm_utils.ChatOllama",- mock_chat_ollama,- create=True,- ):- with patch.dict(- "sys.modules",- {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},- ):- get_model(- model_name="test",- model_type="ollama",- DEFAULT_MODEL="ignored",- DEFAULT_MODEL_TYPE="ignored",- DEFAULT_TEMPERATURE=0.5,- MAX_TOKENS=1000,- )-- call_kwargs = mock_chat_ollama.call_args.kwargs- assert "DEFAULT_MODEL" not in call_kwargs- assert "DEFAULT_MODEL_TYPE" not in call_kwargs- assert "DEFAULT_TEMPERATURE" not in call_kwargs- assert "MAX_TOKENS" not in call_kwargs---class TestGetModelOpenAI:- """Tests for get_model with OpenAI provider."""-- def test_creates_openai_model(self):- """Should create OpenAI model with API key."""- mock_chat_openai = Mock()- with patch(- "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"- ) as mock_get:- mock_get.return_value = "test-api-key"-- with patch.dict(- "sys.modules",- {"langchain_openai": MagicMock(ChatOpenAI=mock_chat_openai)},- ):- with patch(- "local_deep_research.utilities.llm_utils.ChatOpenAI",- mock_chat_openai,- create=True,- ):- get_model(model_name="gpt-4", model_type="openai")-- mock_chat_openai.assert_called_once()- call_kwargs = mock_chat_openai.call_args.kwargs- assert call_kwargs["model"] == "gpt-4"- assert call_kwargs["api_key"] == "test-api-key"---class TestGetModelAnthropic:- """Tests for get_model with Anthropic provider."""-- def test_creates_anthropic_model(self):- """Should create Anthropic model with API key."""- mock_chat_anthropic = Mock()- with patch(- "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"- ) as mock_get:- mock_get.return_value = "test-api-key"-- with patch.dict(- "sys.modules",- {- "langchain_anthropic": MagicMock(- ChatAnthropic=mock_chat_anthropic- )- },- ):- with patch(- "local_deep_research.utilities.llm_utils.ChatAnthropic",- mock_chat_anthropic,- create=True,- ):- get_model(model_name="claude-3", model_type="anthropic")-- mock_chat_anthropic.assert_called_once()- call_kwargs = mock_chat_anthropic.call_args.kwargs- assert call_kwargs["model"] == "claude-3"- assert call_kwargs["anthropic_api_key"] == "test-api-key"---class TestGetModelOpenAIEndpoint:- """Tests for get_model with OpenAI endpoint provider."""-- def test_creates_openai_endpoint_model(self):- """Should create OpenAI endpoint model with custom URL."""- mock_chat_openai = Mock()- with patch(- "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"- ) as mock_get:-- def side_effect(key, *args, **kwargs):- if "api_key" in key:- return "test-api-key"- return kwargs.get("default", "https://openrouter.ai/api/v1")-- mock_get.side_effect = side_effect-- with patch.dict(- "sys.modules",- {"langchain_openai": MagicMock(ChatOpenAI=mock_chat_openai)},- ):- with patch(- "local_deep_research.utilities.llm_utils.ChatOpenAI",- mock_chat_openai,- create=True,- ):- get_model(- model_name="model-name",- model_type="openai_endpoint",- OPENAI_ENDPOINT_URL="https://custom-endpoint.com/v1",- )-- mock_chat_openai.assert_called_once()- call_kwargs = mock_chat_openai.call_args.kwargs- assert (- call_kwargs["openai_api_base"]- == "https://custom-endpoint.com/v1"- )-- def test_endpoint_passes_model_name(self):- """Should pass model name to endpoint."""- mock_chat_openai = Mock()- with patch(- "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"- ) as mock_get:-- def side_effect(key, *args, **kwargs):- if "api_key" in key:- return "test-api-key"- return "https://openrouter.ai/api/v1"-- mock_get.side_effect = side_effect-- with patch.dict(- "sys.modules",- {"langchain_openai": MagicMock(ChatOpenAI=mock_chat_openai)},- ):- with patch(- "local_deep_research.utilities.llm_utils.ChatOpenAI",- mock_chat_openai,- create=True,- ):- get_model(- model_name="custom-model",- model_type="openai_endpoint",- )-- mock_chat_openai.assert_called_once()- call_kwargs = mock_chat_openai.call_args.kwargs- assert call_kwargs["model"] == "custom-model"---class TestGetModelFallback:- """Tests for get_model fallback behavior."""-- def test_default_model_values(self):- """Should use sensible defaults for model parameters."""- mock_chat_ollama = Mock()- with patch(- "local_deep_research.utilities.llm_utils.ChatOllama",- mock_chat_ollama,- create=True,- ):- with patch.dict(- "sys.modules",- {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},- ):- # Call without specifying any params- get_model()-- mock_chat_ollama.assert_called_once()- call_kwargs = mock_chat_ollama.call_args.kwargs- # Should use default model name- assert call_kwargs["model"] == "mistral"- # Should use default temperature- assert call_kwargs["temperature"] == 0.7- # Should use default max_tokens- assert call_kwargs["max_tokens"] == 30000-- def test_kwargs_override_defaults(self):- """Should allow kwargs to override default values."""- mock_chat_ollama = Mock()- with patch(- "local_deep_research.utilities.llm_utils.ChatOllama",- mock_chat_ollama,- create=True,- ):- with patch.dict(- "sys.modules",- {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},- ):- get_model(- DEFAULT_MODEL="custom-model",- DEFAULT_MODEL_TYPE="ollama",- DEFAULT_TEMPERATURE=0.3,- MAX_TOKENS=10000,- )-- call_kwargs = mock_chat_ollama.call_args.kwargs- assert call_kwargs["model"] == "custom-model"- assert call_kwargs["temperature"] == 0.3- assert call_kwargs["max_tokens"] == 10000diff --git a/tests/utilities/test_llm_utils_coverage.py b/tests/utilities/test_llm_utils_coverage.pyindex 8657846827..e1b1ce5e91 100644--- a/tests/utilities/test_llm_utils_coverage.py+++ b/tests/utilities/test_llm_utils_coverage.py@@ -4,20 +4,14 @@ Coverage tests for local_deep_research/utilities/llm_utils.py.Focuses on paths not exercised by existing test files:- _close_base_llm: close() delegation, Ollama httpx client closing,non-Ollama _client skip, missing _client attr, missing httpx client-- get_model: openai_endpoint without model required, unknown type where- Ollama import fails -> ValueError (FakeListLLM fallback removed)- fetch_ollama_models: verifies safe_get (not requests.get) is used"""-import builtins-from unittest.mock import MagicMock, Mock, patch--import pytest+from unittest.mock import Mock, patchfrom local_deep_research.utilities.llm_utils import (_close_base_llm,fetch_ollama_models,- get_model,)@@ -120,74 +114,6 @@ class TestCloseBaseLlmOllamaClient:_close_base_llm(llm)-# ----------------------------------------------------------------------------# get_model - openai_endpoint without model required-# ------------------------------------------------------------------------------class TestGetModelOpenAIEndpointNoModelRequired:- """openai_endpoint path when OPENAI_ENDPOINT_REQUIRES_MODEL is False- and model_name is None - should omit model= from ChatOpenAI call."""-- def test_no_model_param_when_not_required(self):- mock_chat_openai = Mock()- with patch(- "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"- ) as mock_get:-- def side_effect(key, *args, **kwargs):- if "api_key" in key:- return "test-key"- return kwargs.get("default", "https://openrouter.ai/api/v1")-- mock_get.side_effect = side_effect-- with patch.dict(- "sys.modules",- {"langchain_openai": MagicMock(ChatOpenAI=mock_chat_openai)},- ):- with patch(- "local_deep_research.utilities.llm_utils.ChatOpenAI",- mock_chat_openai,- create=True,- ):- get_model(- model_name=None,- model_type="openai_endpoint",- OPENAI_ENDPOINT_REQUIRES_MODEL=False,- DEFAULT_MODEL=None,- )-- mock_chat_openai.assert_called_once()- call_kwargs = mock_chat_openai.call_args.kwargs- assert "model" not in call_kwargs- assert call_kwargs["api_key"] == "test-key"---# ----------------------------------------------------------------------------# get_model - unknown type, Ollama import fails -> raises ValueError-# ------------------------------------------------------------------------------class TestGetModelUnknownTypeRaisesValueError:- """When model_type is unknown AND ChatOllama import fails,- should raise ValueError (FakeListLLM fallback was removed)."""-- def test_unknown_type_ollama_fails_raises_value_error(self):- original_import = builtins.__import__-- def custom_import(name, *args, **kwargs):- if name == "langchain_ollama":- raise ImportError("no langchain_ollama")- return original_import(name, *args, **kwargs)-- with patch("builtins.__import__", side_effect=custom_import):- with pytest.raises(- ValueError, match="No language models available"- ):- get_model(model_name="test", model_type="some_weird_type")--# ---------------------------------------------------------------------------# fetch_ollama_models - verifies safe_get usage# ---------------------------------------------------------------------------diff --git a/tests/utilities/test_llm_utils_extended.py b/tests/utilities/test_llm_utils_extended.pyindex 9e88979319..95344e2ecd 100644--- a/tests/utilities/test_llm_utils_extended.py+++ b/tests/utilities/test_llm_utils_extended.py@@ -3,16 +3,14 @@ Tests for llm_utils module - Extended Edge CasesTests cover edge cases not covered by the main test_llm_utils.py:- fetch_ollama_models with JSON decode errors (actual safe_get mocking)-- get_model initialization failures and edge cases- Handling of malformed responses"""-from unittest.mock import Mock, patch, MagicMock+from unittest.mock import Mock, patchfrom local_deep_research.utilities.llm_utils import (fetch_ollama_models,- get_model,)@@ -150,273 +148,3 @@ class TestFetchOllamaModelsWithSafeGet:assert len(result) == 1assert result[0]["value"] == "valid-model"---class TestGetModelEdgeCases:- """Tests for get_model function edge cases."""-- def test_none_model_name_uses_default(self):- """Should use default model name when None is passed."""- mock_chat_ollama = Mock()- with patch(- "local_deep_research.utilities.llm_utils.ChatOllama",- mock_chat_ollama,- create=True,- ):- with patch.dict(- "sys.modules",- {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},- ):- get_model(model_name=None, model_type="ollama")-- call_kwargs = mock_chat_ollama.call_args.kwargs- assert call_kwargs["model"] == "mistral" # Default-- def test_none_model_type_defaults_to_ollama(self):- """Should default to ollama when model_type is None."""- mock_chat_ollama = Mock()- with patch(- "local_deep_research.utilities.llm_utils.ChatOllama",- mock_chat_ollama,- create=True,- ):- with patch.dict(- "sys.modules",- {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},- ):- get_model(model_name="test", model_type=None)-- mock_chat_ollama.assert_called_once()-- def test_none_temperature_uses_default(self):- """Should use default temperature when None is passed."""- mock_chat_ollama = Mock()- with patch(- "local_deep_research.utilities.llm_utils.ChatOllama",- mock_chat_ollama,- create=True,- ):- with patch.dict(- "sys.modules",- {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},- ):- get_model(- model_name="test", model_type="ollama", temperature=None- )-- call_kwargs = mock_chat_ollama.call_args.kwargs- assert call_kwargs["temperature"] == 0.7 # Default-- def test_model_name_and_type_both_none_uses_defaults(self):- """Should use all defaults when both model_name and model_type are None."""- mock_chat_ollama = Mock()- with patch(- "local_deep_research.utilities.llm_utils.ChatOllama",- mock_chat_ollama,- create=True,- ):- with patch.dict(- "sys.modules",- {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},- ):- get_model(model_name=None, model_type=None, temperature=None)-- call_kwargs = mock_chat_ollama.call_args.kwargs- # All should use defaults- assert call_kwargs["model"] == "mistral"- assert call_kwargs["temperature"] == 0.7- assert call_kwargs["max_tokens"] == 30000-- def test_openai_model_with_valid_api_key(self):- """Should create OpenAI model when API key is available."""- mock_chat_openai = Mock()- with patch(- "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"- ) as mock_get:- mock_get.return_value = "sk-valid-api-key"-- with patch.dict(- "sys.modules",- {"langchain_openai": MagicMock(ChatOpenAI=mock_chat_openai)},- ):- with patch(- "local_deep_research.utilities.llm_utils.ChatOpenAI",- mock_chat_openai,- create=True,- ):- get_model(model_name="gpt-4", model_type="openai")-- mock_chat_openai.assert_called_once()- call_kwargs = mock_chat_openai.call_args.kwargs- assert call_kwargs["api_key"] == "sk-valid-api-key"- assert call_kwargs["model"] == "gpt-4"-- def test_anthropic_model_with_valid_api_key(self):- """Should create Anthropic model when API key is available."""- mock_chat_anthropic = Mock()- with patch(- "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"- ) as mock_get:- mock_get.return_value = "sk-ant-valid-key"-- with patch.dict(- "sys.modules",- {- "langchain_anthropic": MagicMock(- ChatAnthropic=mock_chat_anthropic- )- },- ):- with patch(- "local_deep_research.utilities.llm_utils.ChatAnthropic",- mock_chat_anthropic,- create=True,- ):- get_model(- model_name="claude-3-opus", model_type="anthropic"- )-- mock_chat_anthropic.assert_called_once()- call_kwargs = mock_chat_anthropic.call_args.kwargs- assert (- call_kwargs["anthropic_api_key"] == "sk-ant-valid-key"- )-- def test_unknown_model_type_logs_warning_and_uses_ollama(self):- """Should log warning and fall back to Ollama for unknown types."""- mock_chat_ollama = Mock()- with patch(- "local_deep_research.utilities.llm_utils.ChatOllama",- mock_chat_ollama,- create=True,- ):- with patch.dict(- "sys.modules",- {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},- ):- with patch(- "local_deep_research.utilities.llm_utils.logger"- ) as mock_logger:- get_model(- model_name="some-model",- model_type="nonexistent_provider",- )-- mock_logger.warning.assert_called()- mock_chat_ollama.assert_called_once()-- def test_custom_kwargs_passed_to_model(self):- """Should pass custom kwargs to model constructor."""- mock_chat_ollama = Mock()- with patch(- "local_deep_research.utilities.llm_utils.ChatOllama",- mock_chat_ollama,- create=True,- ):- with patch.dict(- "sys.modules",- {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},- ):- get_model(- model_name="test",- model_type="ollama",- num_ctx=4096,- keep_alive="5m",- )-- call_kwargs = mock_chat_ollama.call_args.kwargs- assert call_kwargs["num_ctx"] == 4096- assert call_kwargs["keep_alive"] == "5m"-- def test_max_tokens_from_kwargs(self):- """Should use max_tokens from kwargs over default."""- mock_chat_ollama = Mock()- with patch(- "local_deep_research.utilities.llm_utils.ChatOllama",- mock_chat_ollama,- create=True,- ):- with patch.dict(- "sys.modules",- {"langchain_ollama": MagicMock(ChatOllama=mock_chat_ollama)},- ):- get_model(- model_name="test", model_type="ollama", max_tokens=8192- )-- call_kwargs = mock_chat_ollama.call_args.kwargs- assert call_kwargs["max_tokens"] == 8192---class TestGetModelOpenAIEndpoint:- """Tests for get_model with OpenAI endpoint provider edge cases."""-- def test_custom_endpoint_url_used(self):- """Should use custom endpoint URL when provided."""- mock_chat_openai = Mock()- with patch(- "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"- ) as mock_get:-- def side_effect(key, *args, **kwargs):- if "api_key" in key:- return "test-key"- return kwargs.get("default", None)-- mock_get.side_effect = side_effect-- with patch.dict(- "sys.modules",- {"langchain_openai": MagicMock(ChatOpenAI=mock_chat_openai)},- ):- with patch(- "local_deep_research.utilities.llm_utils.ChatOpenAI",- mock_chat_openai,- create=True,- ):- get_model(- model_name="custom-model",- model_type="openai_endpoint",- OPENAI_ENDPOINT_URL="https://my-custom-endpoint.com/v1",- )-- call_kwargs = mock_chat_openai.call_args.kwargs- assert (- call_kwargs["openai_api_base"]- == "https://my-custom-endpoint.com/v1"- )-- def test_default_endpoint_url_is_openrouter(self):- """Should default to OpenRouter URL when no custom URL provided."""- mock_chat_openai = Mock()- with patch(- "local_deep_research.utilities.llm_utils.get_setting_from_snapshot"- ) as mock_get:-- def side_effect(key, *args, default=None, **kwargs):- if "api_key" in key:- return "test-key"- # Return the default for URL setting- return default or "https://openrouter.ai/api/v1"-- mock_get.side_effect = side_effect-- with patch.dict(- "sys.modules",- {"langchain_openai": MagicMock(ChatOpenAI=mock_chat_openai)},- ):- with patch(- "local_deep_research.utilities.llm_utils.ChatOpenAI",- mock_chat_openai,- create=True,- ):- get_model(- model_name="openrouter/model",- model_type="openai_endpoint",- )-- call_kwargs = mock_chat_openai.call_args.kwargs- assert (- "openrouter"- in call_kwargs.get("openai_api_base", "").lower()- )diff --git a/tests/utilities/test_search_utilities.py b/tests/utilities/test_search_utilities.pyindex 30b54b4f16..6c7507d62e 100644--- a/tests/utilities/test_search_utilities.py+++ b/tests/utilities/test_search_utilities.py@@ -6,7 +6,6 @@ Tests cover:- extract_links_from_search_results function- format_links_to_markdown function- format_findings function-- print_search_results function"""@@ -344,30 +343,6 @@ class TestFormatFindings:assert "ALL SOURCES" in result or "source1.com" in result-class TestPrintSearchResults:- """Tests for print_search_results function."""-- def test_prints_formatted_results(self):- """Test that search results are printed."""- from local_deep_research.utilities.search_utilities import (- print_search_results,- )-- results = [{"title": "Test", "link": "https://test.com", "index": "1"}]-- # Should not raise- print_search_results(results)-- def test_handles_empty_results(self):- """Test handles empty results."""- from local_deep_research.utilities.search_utilities import (- print_search_results,- )-- # Should not raise- print_search_results([])--class TestLanguageCodeMap:"""Tests for LANGUAGE_CODE_MAP constant."""diff --git a/tests/utilities/test_search_utilities_behavior.py b/tests/utilities/test_search_utilities_behavior.pyindex 5a388587d7..2a4d780c3f 100644--- a/tests/utilities/test_search_utilities_behavior.py+++ b/tests/utilities/test_search_utilities_behavior.py@@ -555,38 +555,3 @@ class TestFormatFindings:findings = [{"phase": "Research"}]result = format_findings(findings, "Summary", {})assert "No content available" in result---class TestPrintSearchResults:- """Tests for print_search_results function."""-- def test_calls_format_functions(self):- """print_search_results uses extract and format functions."""- from local_deep_research.utilities.search_utilities import (- print_search_results,- )-- # This function logs the output, so we just verify it doesn't error- results = [- {"title": "Test", "link": "https://example.com", "index": "1"}- ]- # Should not raise- print_search_results(results)-- def test_handles_empty_results(self):- """Handles empty results without error."""- from local_deep_research.utilities.search_utilities import (- print_search_results,- )-- # Should not raise- print_search_results([])-- def test_handles_none_results(self):- """Handles None results without error."""- from local_deep_research.utilities.search_utilities import (- print_search_results,- )-- # Should not raise- print_search_results(None)diff --git a/tests/utilities/test_search_utilities_coverage.py b/tests/utilities/test_search_utilities_coverage.pyindex 105a8b9d9e..21cb0221fd 100644--- a/tests/utilities/test_search_utilities_coverage.py+++ b/tests/utilities/test_search_utilities_coverage.py@@ -8,14 +8,12 @@ Focuses on gaps not covered by existing test files:- URL deduplication with index merging semantics- Citation numbering: exact format of [indices] and (source nr: ...) output- format_findings end-to-end: multiple findings with sources, all-sources footer-- print_search_results integration"""from local_deep_research.utilities.search_utilities import (extract_links_from_search_results,format_findings,format_links_to_markdown,- print_search_results,remove_think_tags,)@@ -409,30 +407,3 @@ class TestFormatFindingsEndToEnd:# Iteration 2 starts from 1 againiter2_section = result.split("Iteration 2")[1]assert "1. Q2a" in iter2_section---# ═══════════════════════════════════════════════════════════════════════════-# print_search_results — integration-# ═══════════════════════════════════════════════════════════════════════════---class TestPrintSearchResultsIntegration:- """print_search_results should not raise for any reasonable input."""-- def test_valid_results(self):- print_search_results(- [{"title": "T", "link": "https://t.com", "index": "1"}]- )-- def test_empty_list(self):- print_search_results([])-- def test_none_input(self):- """None input should not crash (extract_links_from_search_results handles it)."""- print_search_results(None)-- def test_results_without_index(self):- print_search_results([{"title": "T", "link": "https://t.com"}])-- def test_results_with_none_values(self):- print_search_results([{"title": None, "link": None, "index": None}])diff --git a/tests/utilities/test_search_utilities_safety.py b/tests/utilities/test_search_utilities_safety.pyindex c7ef207940..f47698b920 100644--- a/tests/utilities/test_search_utilities_safety.py+++ b/tests/utilities/test_search_utilities_safety.py@@ -484,37 +484,3 @@ class TestLanguageCodeMapSafety:for code in LANGUAGE_CODE_MAP.values():assert len(code) == 2---class TestPrintSearchResultsSafety:- """Tests for print_search_results function safety."""-- def test_empty_results(self):- """Empty results don't crash."""- from local_deep_research.utilities.search_utilities import (- print_search_results,- )-- # Should not raise- print_search_results([])-- def test_none_results(self):- """None results don't crash."""- from local_deep_research.utilities.search_utilities import (- extract_links_from_search_results,- )-- # extract_links handles None- result = extract_links_from_search_results(None)- assert result == []-- def test_malformed_results(self):- """Malformed results handled gracefully."""- from local_deep_research.utilities.search_utilities import (- print_search_results,- )-- # Various malformed inputs- print_search_results([None]) # List with None- print_search_results([{}]) # Empty dict- print_search_results([{"random": "keys"}]) # Wrong keys