~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
fix: address logging injection and uninitialized variables issues across codebase
hashedviking9a07513fdfad
diff --git a/docs/security/analyze_sarif.ps1 b/docs/security/analyze_sarif.ps1new file mode 100644index 0000000000..ae60f4794f--- /dev/null+++ b/docs/security/analyze_sarif.ps1@@ -0,0 +1,131 @@+# CodeQL SARIF Analysis Script for Windows+# This script analyzes CodeQL SARIF results using Ollama for human-readable explanations++# Configuration+$config = @{+ SarifPath = "python-results.sarif"+ OutputPath = "codeql_analysis_results.txt"+ OllamaEndpoint = "http://localhost:11434/api/generate"+ Model = "deepseek-r1:32b"+}++# Function to check if Ollama is running+function Test-OllamaConnection {+ try {+ $response = Invoke-WebRequest -Uri $config.OllamaEndpoint -Method GET -UseBasicParsing+ return $response.StatusCode -eq 200+ } catch {+ return $false+ }+}++# Function to validate SARIF file+function Test-SarifFile {+ param (+ [string]$Path+ )++ if (-not (Test-Path $Path)) {+ Write-Error "SARIF file not found at: $Path"+ return $false+ }++ try {+ $content = Get-Content $Path -Raw+ $json = $content | ConvertFrom-Json+ return $true+ } catch {+ Write-Error "Invalid SARIF file format: $_"+ return $false+ }+}++# Main script+Write-Host "CodeQL SARIF Analysis Tool" -ForegroundColor Cyan+Write-Host "=========================" -ForegroundColor Cyan++# Check if Ollama is running+Write-Host "Checking Ollama connection..." -NoNewline+if (-not (Test-OllamaConnection)) {+ Write-Host " FAILED" -ForegroundColor Red+ Write-Error "Ollama is not running. Please start Ollama first."+ exit 1+}+Write-Host " OK" -ForegroundColor Green++# Validate SARIF file+Write-Host "Validating SARIF file..." -NoNewline+if (-not (Test-SarifFile $config.SarifPath)) {+ Write-Host " FAILED" -ForegroundColor Red+ exit 1+}+Write-Host " OK" -ForegroundColor Green++# Read SARIF content+try {+ Write-Host "Reading SARIF file..." -NoNewline+ $sarifContent = Get-Content $config.SarifPath -Raw+ Write-Host " OK" -ForegroundColor Green+} catch {+ Write-Host " FAILED" -ForegroundColor Red+ Write-Error "Failed to read SARIF file: $_"+ exit 1+}++# Prepare the prompt+$prompt = @"+Please analyze these security findings from CodeQL analysis.+Focus on:+1. Critical vulnerabilities+2. High priority issues+3. Potential impact+4. Recommended fixes++Here is the analysis data:+$sarifContent+"@++# Prepare the request body+$body = @{+ model = $config.Model+ prompt = $prompt+} | ConvertTo-Json++# Make the request to Ollama and process the streaming response+try {+ Write-Host "Analyzing results with Ollama..." -NoNewline+ $response = ""+ $request = [System.Net.WebRequest]::Create($config.OllamaEndpoint)+ $request.Method = "POST"+ $request.ContentType = "application/json"++ $streamWriter = New-Object System.IO.StreamWriter($request.GetRequestStream())+ $streamWriter.Write($body)+ $streamWriter.Flush()+ $streamWriter.Close()++ $responseStream = $request.GetResponse().GetResponseStream()+ $streamReader = New-Object System.IO.StreamReader($responseStream)++ while (-not $streamReader.EndOfStream) {+ $line = $streamReader.ReadLine()+ if ($line) {+ $jsonResponse = $line | ConvertFrom-Json+ if ($jsonResponse.response) {+ $response += $jsonResponse.response+ }+ }+ }++ # Save the processed response to a file+ $response | Out-File -FilePath $config.OutputPath -Encoding UTF8+ Write-Host " OK" -ForegroundColor Green++ Write-Host "`nAnalysis complete!" -ForegroundColor Green+ Write-Host "Results saved to: $($config.OutputPath)" -ForegroundColor Yellow+ Write-Host "You can view the results by opening: $($config.OutputPath)" -ForegroundColor Yellow+} catch {+ Write-Host " FAILED" -ForegroundColor Red+ Write-Error "Failed to analyze with Ollama: $_"+ exit 1+}diff --git a/docs/security/analyze_sarif.sh b/docs/security/analyze_sarif.shnew file mode 100644index 0000000000..a93a1a9793--- /dev/null+++ b/docs/security/analyze_sarif.sh@@ -0,0 +1,111 @@+#!/bin/bash++# CodeQL SARIF Analysis Script for Unix/Linux+# This script analyzes CodeQL SARIF results using Ollama for human-readable explanations++# Configuration+SARIF_PATH="python-results.sarif"+OUTPUT_PATH="codeql_analysis_results.txt"+OLLAMA_ENDPOINT="http://localhost:11434/api/generate"+MODEL="deepseek-r1:32b"++# Colors for output+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+CYAN='\033[0;36m'+NC='\033[0m' # No Color++# Function to check if Ollama is running+check_ollama() {+ echo -n "Checking Ollama connection... "+ if curl -s "$OLLAMA_ENDPOINT" > /dev/null; then+ echo -e "${GREEN}OK${NC}"+ return 0+ else+ echo -e "${RED}FAILED${NC}"+ echo -e "${RED}Error: Ollama is not running. Please start Ollama first.${NC}"+ return 1+ fi+}++# Function to validate SARIF file+validate_sarif() {+ echo -n "Validating SARIF file... "+ if [ ! -f "$SARIF_PATH" ]; then+ echo -e "${RED}FAILED${NC}"+ echo -e "${RED}Error: SARIF file not found at: $SARIF_PATH${NC}"+ return 1+ fi++ if jq empty "$SARIF_PATH" 2>/dev/null; then+ echo -e "${GREEN}OK${NC}"+ return 0+ else+ echo -e "${RED}FAILED${NC}"+ echo -e "${RED}Error: Invalid SARIF file format${NC}"+ return 1+ fi+}++# Main script+echo -e "${CYAN}CodeQL SARIF Analysis Tool${NC}"+echo -e "${CYAN}=========================${NC}"++# Check if required tools are installed+command -v curl >/dev/null 2>&1 || { echo -e "${RED}Error: curl is required but not installed.${NC}"; exit 1; }+command -v jq >/dev/null 2>&1 || { echo -e "${RED}Error: jq is required but not installed.${NC}"; exit 1; }++# Check if Ollama is running+check_ollama || exit 1++# Validate SARIF file+validate_sarif || exit 1++# Read SARIF content+echo -n "Reading SARIF file... "+if SARIF_CONTENT=$(cat "$SARIF_PATH"); then+ echo -e "${GREEN}OK${NC}"+else+ echo -e "${RED}FAILED${NC}"+ echo -e "${RED}Error: Failed to read SARIF file${NC}"+ exit 1+fi++# Prepare the prompt+PROMPT="Please analyze these security findings from CodeQL analysis.+Focus on:+1. Critical vulnerabilities+2. High priority issues+3. Potential impact+4. Recommended fixes++Here is the analysis data:+$SARIF_CONTENT"++# Prepare the request body+REQUEST_BODY=$(jq -n \+ --arg model "$MODEL" \+ --arg prompt "$PROMPT" \+ '{"model": $model, "prompt": $prompt}')++# Make the request to Ollama and process the streaming response+echo -n "Analyzing results with Ollama... "+if curl -s -X POST "$OLLAMA_ENDPOINT" \+ -H "Content-Type: application/json" \+ -d "$REQUEST_BODY" | \+ while IFS= read -r line; do+ if [ ! -z "$line" ]; then+ echo "$line" | jq -r '.response // empty'+ fi+ done > "$OUTPUT_PATH"; then+ echo -e "${GREEN}OK${NC}"+else+ echo -e "${RED}FAILED${NC}"+ echo -e "${RED}Error: Failed to analyze with Ollama${NC}"+ exit 1+fi++echo -e "\n${GREEN}Analysis complete!${NC}"+echo -e "${YELLOW}Results saved to: $OUTPUT_PATH${NC}"+echo -e "${YELLOW}You can view the results by opening: $OUTPUT_PATH${NC}"diff --git a/src/analyze_sarif.ps1 b/src/analyze_sarif.ps1deleted file mode 100644index 55955e7bc5..0000000000--- a/src/analyze_sarif.ps1+++ /dev/null@@ -1,71 +0,0 @@-# Define paths-$sarifPath = "python-results.sarif"-$outputPath = "codeql_analysis_results.txt"--# Check if SARIF file exists-if (-not (Test-Path $sarifPath)) {- Write-Error "SARIF file not found at: $sarifPath"- exit 1-}--# Read SARIF content-try {- $sarifContent = Get-Content $sarifPath -Raw-} catch {- Write-Error "Failed to read SARIF file: $_"- exit 1-}--# Prepare the prompt-$prompt = @"-Please analyze these security findings from CodeQL analysis.-Focus on:-1. Critical vulnerabilities-2. High priority issues-3. Potential impact-4. Recommended fixes--Here is the analysis data:-$sarifContent-"@--# Prepare the request body-$body = @{- model = "deepseek-r1:32b"- prompt = $prompt-} | ConvertTo-Json--# Make the request to Ollama and process the streaming response-try {- $response = ""- $request = [System.Net.WebRequest]::Create("http://localhost:11434/api/generate")- $request.Method = "POST"- $request.ContentType = "application/json"-- $streamWriter = New-Object System.IO.StreamWriter($request.GetRequestStream())- $streamWriter.Write($body)- $streamWriter.Flush()- $streamWriter.Close()-- $responseStream = $request.GetResponse().GetResponseStream()- $streamReader = New-Object System.IO.StreamReader($responseStream)-- while (-not $streamReader.EndOfStream) {- $line = $streamReader.ReadLine()- if ($line) {- $jsonResponse = $line | ConvertFrom-Json- if ($jsonResponse.response) {- $response += $jsonResponse.response- }- }- }-- # Save the processed response to a file- $response | Out-File -FilePath $outputPath -Encoding UTF8-- Write-Host "Analysis complete. Results saved to: $outputPath"- Write-Host "You can view the results by opening: $outputPath"-} catch {- Write-Error "Failed to analyze with Ollama: $_"- exit 1-}diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.pyindex 668284c670..e9656b2da3 100644--- a/src/local_deep_research/api/research_functions.py+++ b/src/local_deep_research/api/research_functions.py@@ -54,7 +54,7 @@ def quick_summary(- 'iterations': Number of iterations performed- 'questions': Questions generated during research"""- logger.info(f"Generating quick summary for query: {query}")+ logger.info("Generating quick summary for query: %s", query)# Get language model with custom temperaturellm = get_llm(temperature=temperature)@@ -139,7 +139,7 @@ def generate_report(- 'content': The full report content in markdown format- 'metadata': Report metadata including generated timestamp and query"""- logger.info(f"Generating comprehensive research report for query: {query}")+ logger.info("Generating comprehensive research report for query: %s", query)# Get language model with custom temperaturellm = get_llm(temperature=temperature)diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.pyindex d06d07424c..170041b567 100644--- a/src/local_deep_research/search_system.py+++ b/src/local_deep_research/search_system.py@@ -139,7 +139,7 @@ class AdvancedSearchSystem:return responsedef analyze_topic(self, query: str) -> Dict:- logger.info(f"Starting research on topic: {query}")+ logger.info("Starting research on topic: %s", query)findings = []current_knowledge = ""diff --git a/src/local_deep_research/web/database/migrations.py b/src/local_deep_research/web/database/migrations.pyindex 6b3de24371..ee3acff480 100644--- a/src/local_deep_research/web/database/migrations.py+++ b/src/local_deep_research/web/database/migrations.py@@ -1,42 +1,17 @@import logging-import os-from sqlalchemy import create_engine, inspect-from sqlalchemy.ext.declarative import declarative_base-from sqlalchemy.orm import sessionmaker+from sqlalchemy import inspect+from ..models.settings import Settingfrom ..services.settings_manager import SettingsManager-from .models import Base, Setting, SettingType+from .models import Base, SettingType-# Setup logginglogger = logging.getLogger(__name__)-def run_migrations(engine, db_session=None):- """- Run any necessary database migrations-- Args:- engine: SQLAlchemy engine- db_session: Optional SQLAlchemy session- """- # Create all tables if they don't exist- inspector = inspect(engine)- if not inspector.has_table("settings"):- logger.info("Creating settings table")- Base.metadata.create_all(engine, tables=[Setting.__table__])-- # Import existing settings from files- if db_session:- migrate_settings_from_files(db_session)--def migrate_settings_from_files(db_session):"""- Migrate settings from config files to database-- Args:- db_session: SQLAlchemy session+ Migrate settings from files to database"""# Check if settings table is emptysettings_count = db_session.query(Setting).count()@@ -44,24 +19,41 @@ def migrate_settings_from_files(db_session):if settings_count == 0:logger.info("Settings table is empty, importing from files")- # Create settings manager- settings_manager = SettingsManager(db_session)-- # Import all settings from files+ # Create settings manager and import settingstry:- success = settings_manager.import_from_file()+ settings_mgr = SettingsManager(db_session)+ success = settings_mgr.import_from_file()if success:logger.info("Successfully imported settings from files")else:logger.warning("Failed to import some settings from files")except Exception as e:- logger.error(f"Error importing settings from files: {e}")+ logger.error("Error importing settings from files: %s", e)else:logger.info(- f"Settings table already has {settings_count} rows, skipping import"+ "Settings table already has %s rows, skipping import", settings_count)+def run_migrations(engine, db_session=None):+ """+ Run any necessary database migrations++ Args:+ engine: SQLAlchemy engine+ db_session: Optional SQLAlchemy session+ """+ # Create all tables if they don't exist+ inspector = inspect(engine)+ if not inspector.has_table("settings"):+ logger.info("Creating settings table")+ Base.metadata.create_all(engine, tables=[Setting.__table__])++ # Import existing settings from files+ if db_session:+ migrate_settings_from_files(db_session)++def setup_predefined_settings(db_session):"""Set up predefined settings with UI metadata@@ -300,7 +292,7 @@ def setup_predefined_settings(db_session):# Skip if no valid typeif not setting_type:- logger.warning(f"Skipping setting {key} - unknown type")+ logger.warning("Skipping setting %s - unknown type", key)continue# Check if setting exists@@ -308,7 +300,7 @@ def setup_predefined_settings(db_session):if existing:# Update existing setting- logger.debug(f"Updating existing setting: {key}")+ logger.debug("Updating existing setting: %s", key)# Only update metadata, not the value (to preserve user settings)existing.name = setting_dict.get("name", existing.name)@@ -329,7 +321,7 @@ def setup_predefined_settings(db_session):existing.value = setting_dict["value"]else:# Create new setting- logger.info(f"Creating new setting: {key}")+ logger.info("Creating new setting: %s", key)setting = Setting(key=key,value=setting_dict.get("value"),@@ -353,7 +345,7 @@ def setup_predefined_settings(db_session):db_session.commit()except Exception as e:- logger.error(f"Error ensuring setting {setting_dict.get('key')}: {e}")+ logger.error("Error ensuring setting %s: %s", setting_dict.get("key"), e)db_session.rollback()# Log completiondiff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 21ab0a852f..15e1880622 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -85,7 +85,9 @@ def run_research_process(cleanup_research_resources(research_id, active_research, termination_flags)return- logger.info(f"Starting research process for ID {research_id}, query: {query}")+ logger.info(+ "Starting research process for ID %s, query: %s", research_id, query+ )# Extract key parametersmodel_provider = kwargs.get("model_provider")@@ -99,9 +101,17 @@ def run_research_process(# Log all parameters for debugginglogger.info(- f"Research parameters: provider={model_provider}, model={model}, search_engine={search_engine}, "- f"max_results={max_results}, time_period={time_period}, iterations={iterations}, "- f"questions_per_iteration={questions_per_iteration}, custom_endpoint={custom_endpoint}"+ "Research parameters: provider=%s, model=%s, search_engine=%s, "+ "max_results=%s, time_period=%s, iterations=%s, "+ "questions_per_iteration=%s, custom_endpoint=%s",+ model_provider,+ model,+ search_engine,+ max_results,+ time_period,+ iterations,+ questions_per_iteration,+ custom_endpoint,)# Set up the AI Context Manager@@ -262,11 +272,13 @@ def run_research_process(settings.llm.provider = model_provider# Set custom endpoint if provided for OpenAI endpoint provider- if model_provider == "OPENAI_ENDPOINT" and custom_endpoint:- original_endpoint = getattr(- settings.llm, "openai_endpoint_url", ""- )- settings.llm.openai_endpoint_url = custom_endpoint+ original_endpoint = None+ if custom_endpoint and model_provider == "OPENAI_ENDPOINT":+ if hasattr(settings.llm, "openai_endpoint_url"):+ original_endpoint = getattr(+ settings.llm, "openai_endpoint_url", None+ )+ settings.llm.openai_endpoint_url = custom_endpoint# Get LLM with the overridden settingssystem.model = get_llm()@@ -274,15 +286,20 @@ def run_research_process(# Restore original settingssettings.llm.model = original_modelsettings.llm.provider = original_provider- if model_provider == "OPENAI_ENDPOINT" and custom_endpoint:+ if original_endpoint is not None:settings.llm.openai_endpoint_url = original_endpointlogger.info(- f"Successfully set LLM to: provider={model_provider}, model={model}"+ "Successfully set LLM to: provider=%s, model=%s",+ model_provider,+ model,)except Exception as e:logger.error(- f"Error setting LLM provider={model_provider}, model={model}: {str(e)}"+ "Error setting LLM provider=%s, model=%s: %s",+ model_provider,+ model,+ str(e),)logger.error(traceback.format_exc())@@ -293,21 +310,29 @@ def run_research_process(original_search = settings.search.toolsettings.search.tool = search_engine+ # Initialize all variables with default values+ original_max_results = None+ original_time_period = None+ original_iterations = None+ original_questions = None+# Set other search parameters if provided- if max_results:+ if max_results and hasattr(settings.search, "max_results"):original_max_results = settings.search.max_resultssettings.search.max_results = int(max_results)- if time_period:+ if time_period and hasattr(settings.search, "time_period"):original_time_period = settings.search.time_periodsettings.search.time_period = time_period- if iterations:+ if iterations and hasattr(settings.search, "iterations"):original_iterations = settings.search.iterationssettings.search.iterations = int(iterations)system.max_iterations = int(iterations)- if questions_per_iteration:+ if questions_per_iteration and hasattr(+ settings.search, "questions_per_iteration"+ ):original_questions = settings.search.questions_per_iterationsettings.search.questions_per_iteration = int(questions_per_iteration@@ -321,19 +346,23 @@ def run_research_process(# Restore original settingssettings.search.tool = original_search- if max_results:++ if original_max_results is not None:settings.search.max_results = original_max_results- if time_period:++ if original_time_period is not None:settings.search.time_period = original_time_period- if iterations:++ if original_iterations is not None:settings.search.iterations = original_iterations- if questions_per_iteration:++ if original_questions is not None:settings.search.questions_per_iteration = original_questions- logger.info(f"Successfully set search engine to: {search_engine}")+ logger.info("Successfully set search engine to: %s", search_engine)except Exception as e:logger.error(- f"Error setting search engine to {search_engine}: {str(e)}"+ "Error setting search engine to %s: %s", search_engine, str(e))# Run the search@@ -383,13 +412,15 @@ def run_research_process(if results.get("findings") or results.get("formatted_findings"):raw_formatted_findings = results["formatted_findings"]logger.info(- f"Found formatted_findings of length: {len(str(raw_formatted_findings))}"+ "Found formatted_findings of length: %s",+ len(str(raw_formatted_findings)),)try:clean_markdown = raw_formatted_findingslogger.info(- f"Successfully converted to clean markdown of length: {len(clean_markdown)}"+ "Successfully converted to clean markdown of length: %s",+ len(clean_markdown),)# First send a progress update for generating the summary@@ -418,7 +449,7 @@ def run_research_process({"phase": "report_complete"},)- logger.info(f"Writing report to: {report_path}")+ logger.info("Writing report to: %s", report_path)with open(report_path, "w", encoding="utf-8") as f:f.write("# Quick Research Summary\n\n")f.write(f"Query: {query}\n\n")@@ -437,7 +468,7 @@ def run_research_process(now = datetime.utcnow()completed_at = now.isoformat()- logger.info(f"Updating database for research_id: {research_id}")+ logger.info("Updating database for research_id: %s", research_id)# Get the start time from the databaseconn = get_db_connection()cursor = conn.cursor()@@ -476,15 +507,17 @@ def run_research_process()# Clean up resources- logger.info(f"Cleaning up resources for research_id: {research_id}")+ logger.info(+ "Cleaning up resources for research_id: %s", research_id+ )cleanup_research_resources(research_id, active_research, termination_flags)- logger.info(f"Resources cleaned up for research_id: {research_id}")+ logger.info("Resources cleaned up for research_id: %s", research_id)except Exception as inner_e:logger.error(- f"Error during quick summary generation: {str(inner_e)}"+ "Error during quick summary generation: %s", str(inner_e))logger.error(traceback.format_exc())raise Exception(f"Error generating quick summary: {str(inner_e)}")@@ -672,7 +705,7 @@ def cleanup_research_resources(research_id, active_research, termination_flags):active_research: Dictionary of active research processestermination_flags: Dictionary of termination flags"""- logger.info(f"Cleaning up resources for research {research_id}")+ logger.info("Cleaning up resources for research %s", research_id)# Get the current status from the database to determine the final status messagecurrent_status = "completed" # Default@@ -687,7 +720,7 @@ def cleanup_research_resources(research_id, active_research, termination_flags):current_status = result[0]conn.close()except Exception as e:- logger.error(f"Error retrieving research status during cleanup: {e}")+ logger.error("Error retrieving research status during cleanup: %s", e)# Remove from active researchif research_id in active_research:@@ -722,7 +755,9 @@ def cleanup_research_resources(research_id, active_research, termination_flags):}logger.info(- f"Sending final {current_status} socket message for research {research_id}"+ "Sending final %s socket message for research %s",+ current_status,+ research_id,)from ..services.socket_service import emit_to_subscribers@@ -730,7 +765,7 @@ def cleanup_research_resources(research_id, active_research, termination_flags):emit_to_subscribers("research_progress", research_id, final_message)except Exception as e:- logger.error(f"Error sending final cleanup message: {e}")+ logger.error("Error sending final cleanup message: %s", e)def handle_termination(research_id, active_research, termination_flags):diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py b/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.pyindex 2102c0374c..11ac87b93e 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py@@ -132,7 +132,7 @@ class GooglePSESearchEngine(BaseSearchEngine):# If we've made a request recently, wait until the minimum interval has passedif elapsed < self.min_request_interval:sleep_time = self.min_request_interval - elapsed- logger.debug(f"Rate limiting: sleeping for {sleep_time:.2f}s")+ logger.debug("Rate limiting: sleeping for %.2f s", sleep_time)time.sleep(sleep_time)# Update the last request time@@ -181,14 +181,19 @@ class GooglePSESearchEngine(BaseSearchEngine):jitter = random.uniform(0.5, 1.5)sleep_time = self.retry_delay * (2 ** (attempt - 1)) * jitterlogger.info(- f"Retry attempt {attempt + 1} / {self.max_retries} for "- f"query '{query}'. Waiting {sleep_time:.2f}s"+ "Retry attempt %s / %s for query '%s'. Waiting %s s",+ attempt + 1,+ self.max_retries,+ query,+ f"{sleep_time:.2f}",)time.sleep(sleep_time)# Make the requestlogger.debug(- f"Making request to Google PSE API: {query} (start_index={start_index})"+ "Making request to Google PSE API: %s (start_index=%s)",+ query,+ start_index,)response = requests.get(url, params=params, timeout=10)@@ -200,13 +205,18 @@ class GooglePSESearchEngine(BaseSearchEngine):except RequestException as e:logger.warning(- f"Request error on attempt {attempt + 1}"- f" / {self.max_retries}: {str(e)}"+ "Request error on attempt %s / %s: %s",+ attempt + 1,+ self.max_retries,+ str(e),)last_exception = eexcept Exception as e:logger.warning(- f"Error on attempt {attempt + 1} / {self.max_retries}:" f" {str(e)}"+ "Error on attempt %s / %s: %s",+ attempt + 1,+ self.max_retries,+ str(e),)last_exception = e@@ -275,10 +285,10 @@ class GooglePSESearchEngine(BaseSearchEngine):time.sleep(self.min_request_interval)except Exception as e:- logger.error(f"Error getting search results: {str(e)}")+ logger.error("Error getting search results: %s", str(e))break- logger.info(f"Retrieved {len(results)} search results for query: '{query}'")+ logger.info("Retrieved %s search results for query: '%s'", len(results), query)return resultsdef _get_full_content(diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.pyindex 99873b4abf..e13b206845 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py@@ -100,7 +100,7 @@ class PubMedSearchEngine(BaseSearchEngine):data = response.json()count = int(data["esearchresult"]["count"])- logger.info(f"Query '{query}' has {count} total results in PubMed")+ logger.info("Query '%s' has %s total results in PubMed", query, count)return countexcept Exception as e:@@ -319,7 +319,7 @@ Return ONLY the search query without any explanations.self._simplify_query_cache = optimized_query# Log original and optimized queries- logger.info(f"Original query: '{query}'")+ logger.info("Original query: '%s'", query)logger.info(f"Optimized for PubMed: '{optimized_query}'")return optimized_querydiff --git a/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py b/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.pyindex 55317af524..7e08b75d60 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py@@ -127,7 +127,7 @@ class SemanticScholarSearchEngine(BaseSearchEngine):if elapsed < self.rate_limit_wait:wait_time = self.rate_limit_wait - elapsed- logger.debug(f"Rate limiting: waiting {wait_time:.2f}s")+ logger.debug("Rate limiting: waiting %.2f s", wait_time)time.sleep(wait_time)self.last_request_time = time.time()@@ -314,7 +314,8 @@ Return ONLY the optimized search query with no explanation.if '"' in query:unquoted_query = query.replace('"', "")logger.info(- f"No results with quoted terms, trying without quotes: {unquoted_query}"+ "No results with quoted terms, trying without quotes: %s",+ unquoted_query,)papers = self._direct_search(unquoted_query)@@ -359,17 +360,19 @@ Format each query on a new line with no numbering or explanation. Keep each quer# Try each alternative queryfor alt_query in alt_queries[:3]: # Limit to first 3 alternatives- logger.info(f"Trying LLM-suggested query: {alt_query}")+ logger.info("Trying LLM-suggested query: %s", alt_query)alt_papers = self._direct_search(alt_query)if alt_papers:logger.info(- f"Found {len(alt_papers)} papers using LLM-suggested query: {alt_query}"+ "Found %s papers using LLM-suggested query: %s",+ len(alt_papers),+ alt_query,)strategy = "llm_alternative"return alt_papers, strategyexcept Exception as e:- logger.error(f"Error using LLM for query refinement: {e}")+ logger.error("Error using LLM for query refinement: %s", e)# Fall through to simpler strategies# Fallback: Try with the longest words (likely specific terms)@@ -379,7 +382,7 @@ Format each query on a new line with no numbering or explanation. Keep each quer# Use up to 3 of the longest wordslonger_words = sorted(longer_words, key=len, reverse=True)[:3]key_terms_query = " ".join(longer_words)- logger.info(f"Trying with key terms: {key_terms_query}")+ logger.info("Trying with key terms: %s", key_terms_query)papers = self._direct_search(key_terms_query)if papers:@@ -390,7 +393,7 @@ Format each query on a new line with no numbering or explanation. Keep each querif words:longest_word = max(words, key=len)if len(longest_word) > 5: # Only use if it's reasonably long- logger.info(f"Trying with single key term: {longest_word}")+ logger.info("Trying with single key term: %s", longest_word)papers = self._direct_search(longest_word)if papers:diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py b/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.pyindex 05bfddc222..5d9defb5d4 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py@@ -56,7 +56,7 @@ class WikipediaSearchEngine(BaseSearchEngine):Returns:List of preview dictionaries"""- logger.info(f"Getting Wikipedia page previews for query: {query}")+ logger.info("Getting Wikipedia page previews for query: %s", query)try:# Get search results (just titles)@@ -67,7 +67,7 @@ class WikipediaSearchEngine(BaseSearchEngine):)if not search_results:- logger.info(f"No Wikipedia results found for query: {query}")+ logger.info("No Wikipedia results found for query: %s", query)return []# Create a cache for full pages (will be populated on-demand)@@ -236,11 +236,12 @@ class WikipediaSearchEngine(BaseSearchEngine):Returns:Dictionary with page information"""- # Check if we should include full content- include_content = not (- hasattr(search_config, "SEARCH_SNIPPETS_ONLY")- and search_config.SEARCH_SNIPPETS_ONLY- )+ # Initialize include_content with our instance value+ include_content = self.include_content++ # Check if we should override with config setting+ if hasattr(search_config, "SEARCH_SNIPPETS_ONLY"):+ include_content = not search_config.SEARCH_SNIPPETS_ONLYtry:page = wikipedia.page(title, auto_suggest=False)