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: Major pre-commit hook compliance improvements

LearningCircuitaf7e279db5a0
diff --git a/.pre-commit-hooks/check-env-vars.py b/.pre-commit-hooks/check-env-vars.py
index 5cfc867f2a..f329745b5f 100755
--- a/.pre-commit-hooks/check-env-vars.py
+++ b/.pre-commit-hooks/check-env-vars.py
@@ -23,6 +23,8 @@ ALLOWED_PATTERNS = {
"scripts/",
"utils/",
"cli.py",
+ # Example scripts demonstrating usage
+ "examples/",
# Specific modules that need direct access
"log_utils.py", # Logging configuration
"paths.py", # Path configuration
@@ -33,6 +35,7 @@ ALLOWED_PATTERNS = {
"alembic/",
"migrations/",
"encrypted_db.py", # Database encryption setup
+ "sqlcipher_utils.py", # SQLCipher configuration (needed before DB)
}
# Import SettingsManager to get allowed environment variables
diff --git a/.pre-commit-hooks/custom-checks.py b/.pre-commit-hooks/custom-checks.py
index 4cbfb4fa07..5872cd31e9 100755
--- a/.pre-commit-hooks/custom-checks.py
+++ b/.pre-commit-hooks/custom-checks.py
@@ -28,12 +28,17 @@ class CustomCodeChecker(ast.NodeVisitor):
for alias in node.names:
if alias.name == "logging":
self.has_standard_logging_import = True
- self.errors.append(
- (
- node.lineno,
- "Use loguru instead of standard logging library",
+ # Allow standard logging in specific files that need it
+ if not (
+ "log_utils.py" in self.filename
+ or "app_factory.py" in self.filename
+ ):
+ self.errors.append(
+ (
+ node.lineno,
+ "Use loguru instead of standard logging library",
+ )
)
- )
elif alias.name == "loguru":
self.has_loguru_import = True
self.generic_visit(node)
@@ -41,9 +46,17 @@ class CustomCodeChecker(ast.NodeVisitor):
def visit_ImportFrom(self, node):
if node.module == "logging":
self.has_standard_logging_import = True
- self.errors.append(
- (node.lineno, "Use loguru instead of standard logging library")
- )
+ # Allow standard logging in specific files that need it
+ if not (
+ "log_utils.py" in self.filename
+ or "app_factory.py" in self.filename
+ ):
+ self.errors.append(
+ (
+ node.lineno,
+ "Use loguru instead of standard logging library",
+ )
+ )
elif node.module == "loguru":
self.has_loguru_import = True
elif node.module and "sqlalchemy" in node.module:
diff --git a/examples/benchmarks/run_browsecomp.py b/examples/benchmarks/run_browsecomp.py
index 0a27748803..463bfc1a8b 100644
--- a/examples/benchmarks/run_browsecomp.py
+++ b/examples/benchmarks/run_browsecomp.py
@@ -47,7 +47,7 @@ def decrypt(ciphertext_b64: str, password: str) -> str:
decrypted = bytes(a ^ b for a, b in zip(encrypted, key, strict=False))
return decrypted.decode()
except Exception as e:
- logger.error(f"Error decrypting data: {e!s}")
+ logger.exception(f"Error decrypting data: {e!s}")
return f"Error: Could not decrypt data - {e!s}"
@@ -173,7 +173,7 @@ def run_browsecomp_with_canary(
f.write(json.dumps(result) + "\n")
except Exception as e:
- logger.error(f"Error processing example {i + 1}: {e!s}")
+ logger.exception(f"Error processing example {i + 1}: {e!s}")
# Create error result
error_result = {
@@ -212,7 +212,7 @@ def run_browsecomp_with_canary(
dataset_type="browsecomp",
)
except Exception as e:
- logger.error(f"Evaluation failed: {e!s}")
+ logger.exception(f"Evaluation failed: {e!s}")
evaluation_results = []
# Calculate basic metrics
diff --git a/examples/benchmarks/scripts/run_focused_benchmark_fixed.py b/examples/benchmarks/scripts/run_focused_benchmark_fixed.py
index 0548143947..3b38300a59 100755
--- a/examples/benchmarks/scripts/run_focused_benchmark_fixed.py
+++ b/examples/benchmarks/scripts/run_focused_benchmark_fixed.py
@@ -9,12 +9,12 @@ Updated version that properly uses the local get_llm function for grading,
accesses the database for API keys, and uses Claude Anthropic 3.7 for grading.
"""
-import logging
import os
import sys
import time
from datetime import datetime
+
# Set up Python path
src_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "src"))
if src_dir not in sys.path:
@@ -29,13 +29,6 @@ if os.path.exists(os.path.join(data_dir, "ldr.db")):
else:
print(f"Warning: Database not found at {os.path.join(data_dir, 'ldr.db')}")
-# Configure logging
-logging.basicConfig(
- level=logging.INFO,
- format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
-)
-logger = logging.getLogger(__name__)
-
def setup_grading_config():
"""
diff --git a/examples/benchmarks/scripts/run_grader_only.py b/examples/benchmarks/scripts/run_grader_only.py
index f9193f75c5..d01b1968f8 100644
--- a/examples/benchmarks/scripts/run_grader_only.py
+++ b/examples/benchmarks/scripts/run_grader_only.py
@@ -7,11 +7,11 @@ without re-executing the benchmark itself.
"""
import argparse
-import logging
import os
import sys
import time
+
# Set up Python path
src_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "src"))
if src_dir not in sys.path:
@@ -26,13 +26,6 @@ if os.path.exists(os.path.join(data_dir, "ldr.db")):
else:
print(f"Warning: Database not found at {os.path.join(data_dir, 'ldr.db')}")
-# Configure logging
-logging.basicConfig(
- level=logging.INFO,
- format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
-)
-logger = logging.getLogger(__name__)
-
def setup_grading_config():
"""
diff --git a/examples/elasticsearch_search_example.py b/examples/elasticsearch_search_example.py
index b9fbeb1f2b..824ce68c6e 100644
--- a/examples/elasticsearch_search_example.py
+++ b/examples/elasticsearch_search_example.py
@@ -169,7 +169,7 @@ def main():
logger.exception(
f"运行示例时出错: {e!s}"
) # Error running example: {str(e)}
- logger.error(
+ logger.info(
"请确保 Elasticsearch 正在运行,默认地址为 http://localhost:9200"
) # Make sure Elasticsearch is running, default address is http://localhost:9200
diff --git a/examples/optimization/browsecomp_optimization.py b/examples/optimization/browsecomp_optimization.py
index 620f1f8fcd..c652ae2fb4 100755
--- a/examples/optimization/browsecomp_optimization.py
+++ b/examples/optimization/browsecomp_optimization.py
@@ -15,11 +15,11 @@ Usage:
"""
import json
-import logging
import os
import sys
from datetime import datetime
+
from local_deep_research.benchmarks.optimization import optimize_parameters
# Add the src directory to the Python path
@@ -28,13 +28,6 @@ project_root = os.path.abspath(
)
sys.path.insert(0, os.path.join(project_root, "src"))
-# Configure logging to see progress
-logging.basicConfig(
- level=logging.INFO,
- format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
-)
-logger = logging.getLogger(__name__)
-
def main():
# Create timestamp for unique output directory
diff --git a/examples/optimization/gemini_optimization.py b/examples/optimization/gemini_optimization.py
index 3476be9e55..a9adf0a765 100644
--- a/examples/optimization/gemini_optimization.py
+++ b/examples/optimization/gemini_optimization.py
@@ -19,11 +19,12 @@ Usage:
import argparse
import json
-import logging
import os
import sys
from datetime import datetime
+from loguru import logger
+
# Import the optimization functionality
from local_deep_research.benchmarks.optimization import (
optimize_for_quality,
@@ -31,13 +32,6 @@ from local_deep_research.benchmarks.optimization import (
optimize_parameters,
)
-# Configure logging to see progress
-logging.basicConfig(
- level=logging.INFO,
- format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
-)
-logger = logging.getLogger(__name__)
-
def setup_gemini_config(api_key=None):
"""
diff --git a/examples/optimization/run_multi_benchmark.py b/examples/optimization/run_multi_benchmark.py
index b9e5b400e6..4db5388b44 100755
--- a/examples/optimization/run_multi_benchmark.py
+++ b/examples/optimization/run_multi_benchmark.py
@@ -13,12 +13,13 @@ Usage:
python ../examples/optimization/run_multi_benchmark.py
"""
-import logging
import os
import sys
from datetime import datetime
from typing import Any, Dict
+from loguru import logger
+
# Add src directory to Python path
src_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../src"))
if src_dir not in sys.path:
@@ -45,13 +46,6 @@ except ImportError as e:
print("Current sys.path:", sys.path)
sys.exit(1)
-# Configure logging
-logging.basicConfig(
- level=logging.INFO,
- format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
-)
-logger = logging.getLogger(__name__)
-
def print_optimization_results(params: Dict[str, Any], score: float):
"""Print optimization results in a nicely formatted way."""
@@ -180,7 +174,7 @@ def main():
)
print_optimization_results(params1, score1)
except Exception as e:
- logger.error(f"Error running SimpleQA optimization: {e}")
+ logger.exception(f"Error running SimpleQA optimization: {e}")
print(f"Error: {e}")
# Run 2: BrowseComp benchmark only (minimal test)
@@ -207,7 +201,7 @@ def main():
)
except Exception as e:
- logger.error(f"Error running BrowseComp evaluation: {e}")
+ logger.exception(f"Error running BrowseComp evaluation: {e}")
print(f"Error: {e}")
# Run 3: Combined benchmark with weights (minimal test)
@@ -239,7 +233,7 @@ def main():
)
except Exception as e:
- logger.error(f"Error running combined benchmark evaluation: {e}")
+ logger.exception(f"Error running combined benchmark evaluation: {e}")
print(f"Error: {e}")
# Run 4: Combined benchmark with speed optimization
@@ -265,7 +259,7 @@ def main():
print("Speed metrics weighting: Quality (20%), Speed (80%)")
except Exception as e:
- logger.error(
+ logger.exception(
f"Error running speed optimization with multi-benchmark: {e}"
)
print(f"Error: {e}")
@@ -295,7 +289,7 @@ def main():
)
except Exception as e:
- logger.error(
+ logger.exception(
f"Error running efficiency optimization with multi-benchmark: {e}"
)
print(f"Error: {e}")
diff --git a/examples/optimization/run_parallel_benchmark.py b/examples/optimization/run_parallel_benchmark.py
index c5112f328e..b71c96fa7f 100755
--- a/examples/optimization/run_parallel_benchmark.py
+++ b/examples/optimization/run_parallel_benchmark.py
@@ -15,25 +15,19 @@ Usage:
import argparse
import concurrent.futures
-import logging
import os
import sys
import time
from datetime import datetime
+from loguru import logger
+
# Add the src directory to the Python path
project_root = os.path.abspath(
os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
)
sys.path.insert(0, os.path.join(project_root, "src"))
-# Configure logging
-logging.basicConfig(
- level=logging.INFO,
- format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
-)
-logger = logging.getLogger(__name__)
-
def run_simpleqa_benchmark(
num_examples,
@@ -225,14 +219,14 @@ def main():
simpleqa_results = simpleqa_future.result()
print("SimpleQA benchmark completed successfully")
except Exception as e:
- logger.error(f"Error in SimpleQA benchmark: {e}")
+ logger.exception(f"Error in SimpleQA benchmark: {e}")
simpleqa_results = None
try:
browsecomp_results = browsecomp_future.result()
print("BrowseComp benchmark completed successfully")
except Exception as e:
- logger.error(f"Error in BrowseComp benchmark: {e}")
+ logger.exception(f"Error in BrowseComp benchmark: {e}")
browsecomp_results = None
# Calculate total time
@@ -294,7 +288,7 @@ def main():
json.dump(summary, f, indent=2)
except Exception as e:
- logger.error(f"Error saving summary: {e}")
+ logger.exception(f"Error saving summary: {e}")
return 0
diff --git a/examples/optimization/strategy_benchmark_plan.py b/examples/optimization/strategy_benchmark_plan.py
index c40251a8cb..3c809a9de7 100755
--- a/examples/optimization/strategy_benchmark_plan.py
+++ b/examples/optimization/strategy_benchmark_plan.py
@@ -79,7 +79,7 @@ def run_strategy_comparison():
)
except Exception as e:
logger.exception(f"Error initializing LLM or search settings: {e!s}")
- logger.error("Please check your database configuration")
+ logger.info("Please check your database configuration")
return {"error": str(e)}
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
base_output_dir = f"strategy_benchmark_results_{timestamp}"
diff --git a/examples/optimization/update_llm_config.py b/examples/optimization/update_llm_config.py
index f62fcc2281..4b7536bc81 100755
--- a/examples/optimization/update_llm_config.py
+++ b/examples/optimization/update_llm_config.py
@@ -18,24 +18,18 @@ Usage:
"""
import argparse
-import logging
import os
import sys
from typing import Optional
+from loguru import logger
+
# Add the src directory to the Python path
project_root = os.path.abspath(
os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
)
sys.path.insert(0, os.path.join(project_root, "src"))
-# Configure logging
-logging.basicConfig(
- level=logging.INFO,
- format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
-)
-logger = logging.getLogger(__name__)
-
def update_llm_configuration(
model_name: Optional[str] = None,
@@ -66,7 +60,7 @@ def update_llm_configuration(
update_db_setting,
)
except ImportError:
- logger.error(
+ logger.exception(
"Could not import database utilities. Make sure you're in the correct directory."
)
return False
diff --git a/examples/run_benchmark.py b/examples/run_benchmark.py
index aabc699db2..9e6df9a58b 100644
--- a/examples/run_benchmark.py
+++ b/examples/run_benchmark.py
@@ -6,22 +6,15 @@ This script demonstrates how to run SimpleQA and BrowseComp benchmarks programma
"""
import argparse
-import logging
import os
+
from local_deep_research.api.benchmark_functions import (
compare_configurations,
evaluate_browsecomp,
evaluate_simpleqa,
)
-# Configure logging
-logging.basicConfig(
- level=logging.INFO,
- format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
-)
-logger = logging.getLogger(__name__)
-
def main():
"""Run benchmark examples."""
diff --git a/src/local_deep_research/advanced_search_system/questions/entity_aware_question.py b/src/local_deep_research/advanced_search_system/questions/entity_aware_question.py
index 428a8c8978..c4fc57091d 100644
--- a/src/local_deep_research/advanced_search_system/questions/entity_aware_question.py
+++ b/src/local_deep_research/advanced_search_system/questions/entity_aware_question.py
@@ -179,5 +179,5 @@ Only provide the numbered sub-questions."""
return questions
except Exception as e:
- logger.error(f"Error generating sub-questions: {e!s}")
+ logger.exception(f"Error generating sub-questions: {e!s}")
return []
diff --git a/src/local_deep_research/advanced_search_system/strategies/modular_strategy.py b/src/local_deep_research/advanced_search_system/strategies/modular_strategy.py
index fc56d986a8..b5c640a75a 100644
--- a/src/local_deep_research/advanced_search_system/strategies/modular_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/modular_strategy.py
@@ -1134,9 +1134,6 @@ Provide a clear, factual answer that addresses the original question and explain
except Exception as e:
logger.exception(f"Error in analyze_topic: {e}")
- import traceback
-
- logger.error(f"Traceback: {traceback.format_exc()}")
return {
"findings": [],
"iterations": 0,
diff --git a/src/local_deep_research/benchmarks/runners.py b/src/local_deep_research/benchmarks/runners.py
index 1b4fd6fabd..dfe0948928 100644
--- a/src/local_deep_research/benchmarks/runners.py
+++ b/src/local_deep_research/benchmarks/runners.py
@@ -243,7 +243,7 @@ def run_benchmark(
)
except Exception as e:
- logger.error(f"Error processing example {i + 1}: {e!s}")
+ logger.exception(f"Error processing example {i + 1}: {e!s}")
# Create error result
error_result = {
@@ -316,7 +316,7 @@ def run_benchmark(
),
)
except Exception as e:
- logger.error(f"Automated evaluation failed: {e!s}")
+ logger.exception(f"Automated evaluation failed: {e!s}")
if progress_callback:
progress_callback(
diff --git a/src/local_deep_research/web/routes/benchmark_routes.py b/src/local_deep_research/web/routes/benchmark_routes.py
index 038bd638e5..b6bc38c680 100644
--- a/src/local_deep_research/web/routes/benchmark_routes.py
+++ b/src/local_deep_research/web/routes/benchmark_routes.py
@@ -57,7 +57,7 @@ def run_benchmark_task(job_id, benchmark_type, params, callback=None):
callback(job_id, result)
except Exception as e:
- logger.error(f"Error running benchmark job {job_id}: {e!s}")
+ logger.exception(f"Error running benchmark job {job_id}: {e!s}")
running_jobs[job_id]["status"] = "error"
running_jobs[job_id]["error"] = str(e)
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 d0e88382f8..d195244daf 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
@@ -83,7 +83,7 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
f"Elasticsearch version: {info.get('version', {}).get('number')}"
)
except Exception as e:
- logger.error(f"Failed to connect to Elasticsearch: {e!s}")
+ logger.exception(f"Failed to connect to Elasticsearch: {e!s}")
raise ConnectionError(f"Could not connect to Elasticsearch: {e!s}")
def _get_previews(self, query: str) -> List[Dict[str, Any]]:
@@ -177,7 +177,7 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
return previews
except Exception as e:
- logger.error(f"Error getting Elasticsearch previews: {e!s}")
+ logger.exception(f"Error getting Elasticsearch previews: {e!s}")
return []
def _get_full_content(
@@ -237,7 +237,7 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
result[key] = value
except Exception as e:
- logger.error(
+ logger.exception(
f"Error fetching full content for document {doc_id}: {e!s}"
)
# Keep the preview data if we can't get the full content
@@ -284,7 +284,7 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
return self._get_full_content(previews)
except Exception as e:
- logger.error(f"Error in query_string search: {e!s}")
+ logger.exception(f"Error in query_string search: {e!s}")
return []
def search_by_dsl(self, query_dsl: Dict[str, Any]) -> List[Dict[str, Any]]:
@@ -309,7 +309,7 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
return self._get_full_content(previews)
except Exception as e:
- logger.error(f"Error in DSL search: {e!s}")
+ logger.exception(f"Error in DSL search: {e!s}")
return []
def _process_es_response(
diff --git a/tests/api_tests/fix_search_engines.py b/tests/api_tests/fix_search_engines.py
index 85f8928ea0..a53e2c8fbf 100644
--- a/tests/api_tests/fix_search_engines.py
+++ b/tests/api_tests/fix_search_engines.py
@@ -67,7 +67,7 @@ def fix_search_engines_for_user(username: str, password: str):
return True
except Exception as e:
- logger.error(f"Failed to fix search engines: {e}")
+ logger.exception(f"Failed to fix search engines: {e}")
db_session.rollback()
return False
finally:
diff --git a/tests/feature_tests/test_custom_context.py b/tests/feature_tests/test_custom_context.py
index 4cadc3948d..d79bd1ec1f 100644
--- a/tests/feature_tests/test_custom_context.py
+++ b/tests/feature_tests/test_custom_context.py
@@ -5,14 +5,11 @@ This script tests if we can set a custom context window size for different model
It simulates the fix for issue #241: https://github.com/LearningCircuit/local-deep-research/issues/241
"""
-import logging
import sys
from pathlib import Path
from typing import Any, Dict, Optional
-# Configure logging
-logging.basicConfig(level=logging.INFO)
-logger = logging.getLogger(__name__)
+from loguru import logger
# Add the src directory to the path before importing project modules
src_path = str(Path(__file__).parent.parent.parent / "src")
@@ -134,7 +131,7 @@ def test_custom_context_size():
result = modify_llm_creation(provider)
results[provider] = result
except Exception as e:
- logger.error(f"Error testing provider {provider}: {e!s}")
+ logger.exception(f"Error testing provider {provider}: {e!s}")
results[provider] = {"error": str(e)}
# Show summary
diff --git a/tests/test_google_pse.py b/tests/test_google_pse.py
index c1b14d5f07..49d1f717e5 100644
--- a/tests/test_google_pse.py
+++ b/tests/test_google_pse.py
@@ -3,19 +3,13 @@ Test script for Google Programmable Search Engine integration.
Run this script to verify that your Google PSE API key and search engine ID are working.
"""
-import logging
import os
import time
import pytest
import requests
from dotenv import load_dotenv
-
-# Set up logging
-logging.basicConfig(
- level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s"
-)
-logger = logging.getLogger(__name__)
+from loguru import logger
# Load environment variables from .env file
load_dotenv()