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.

Install Ruff and fix all the Ruff errors. (#428)

Daniel Petti0a488db0815a
diff --git a/.github/sync-config.yml b/.github/sync-config.yml
index 7cffe0d549..03e9830da1 100644
--- a/.github/sync-config.yml
+++ b/.github/sync-config.yml
@@ -24,7 +24,7 @@ sync:
# Reviewers to assign for conflict resolution
conflict_reviewers:
- - "LearningCircuit"
+ - "LearningCircuit"
- "djpetti"
- "HashedViking"
# Additional settings
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index c84ce6a892..93c8d1fa7a 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -12,16 +12,12 @@ repos:
- id: forbid-new-submodules
- id: no-commit-to-branch
args: ['--branch', 'main']
- - repo: https://github.com/psf/black
- rev: 25.1.0
+ - repo: https://github.com/astral-sh/ruff-pre-commit
+ # Ruff version.
+ rev: v0.11.12
hooks:
- - id: black
- - repo: https://github.com/PyCQA/flake8.git
- rev: 7.1.2
- hooks:
- - id: flake8
- - repo: https://github.com/timothycrosley/isort
- rev: 6.0.1
- hooks:
- - id: isort
- args: ["--profile", "black"]
+ # Run the linter.
+ - id: ruff
+ args: [ --fix ]
+ # Run the formatter.
+ - id: ruff-format
diff --git a/cookiecutter-docker/hooks/post_gen_project.py b/cookiecutter-docker/hooks/post_gen_project.py
index bd1deeae51..069ad7eac0 100644
--- a/cookiecutter-docker/hooks/post_gen_project.py
+++ b/cookiecutter-docker/hooks/post_gen_project.py
@@ -16,7 +16,9 @@ def main():
# Move the entrypoint script to the scripts directory.
entrypoint_path = output_dir / "ollama_entrypoint.sh"
- entrypoint_path.rename(output_dir.parent / "scripts" / "ollama_entrypoint.sh")
+ entrypoint_path.rename(
+ output_dir.parent / "scripts" / "ollama_entrypoint.sh"
+ )
# Delete the directory.
shutil.rmtree(output_dir)
diff --git a/examples/benchmarks/browsecomp/run_browsecomp_fixed_v2.py b/examples/benchmarks/browsecomp/run_browsecomp_fixed_v2.py
index 4ec8588cd4..89a4158200 100755
--- a/examples/benchmarks/browsecomp/run_browsecomp_fixed_v2.py
+++ b/examples/benchmarks/browsecomp/run_browsecomp_fixed_v2.py
@@ -3,6 +3,7 @@
Fixed BrowseComp benchmark script that properly handles decryption.
This version uses the canary string from each example as the decryption key.
"""
+
import base64
import hashlib
import json
@@ -20,7 +21,6 @@ sys.path.insert(0, current_dir)
try:
from local_deep_research.api import quick_summary
- from local_deep_research.config.llm_config import get_llm
except ImportError as e:
print(f"Error importing from api: {e}")
sys.exit(1)
@@ -102,7 +102,9 @@ def run_browsecomp_evaluation(
# Display sample canary
if examples:
- print(f"Sample canary: {examples[0].get('canary', 'No canary found')[:30]}...")
+ print(
+ f"Sample canary: {examples[0].get('canary', 'No canary found')[:30]}..."
+ )
# Sample examples if specified
if num_examples and num_examples < len(examples):
@@ -117,7 +119,7 @@ def run_browsecomp_evaluation(
results = []
correct_count = 0
- print(f"\nStarting BrowseComp evaluation with settings:")
+ print("\nStarting BrowseComp evaluation with settings:")
print(f"- Number of examples: {len(examples)}")
print(f"- Search iterations: {search_iterations}")
print(f"- Questions per iteration: {questions_per_iteration}")
@@ -128,7 +130,9 @@ def run_browsecomp_evaluation(
for i, example in enumerate(examples):
# Decrypt the problem and answer using the canary
try:
- problem = decrypt(example.get("problem", ""), example.get("canary", ""))
+ problem = decrypt(
+ example.get("problem", ""), example.get("canary", "")
+ )
correct_answer = decrypt(
example.get("answer", ""), example.get("canary", "")
)
@@ -156,18 +160,30 @@ def run_browsecomp_evaluation(
response = summary.get("summary", "")
# Clean up the response for better evaluation
- response = response.replace("[1]", "").replace("[2]", "").replace("[3]", "")
+ response = (
+ response.replace("[1]", "")
+ .replace("[2]", "")
+ .replace("[3]", "")
+ )
response = " ".join(
- [line for line in response.split("\n") if not line.startswith("[")]
+ [
+ line
+ for line in response.split("\n")
+ if not line.startswith("[")
+ ]
)
# Extract the final answer from the response
answer_match = re.search(r"Exact Answer:\s*(.*?)(?:\n|$)", response)
- exact_answer = answer_match.group(1).strip() if answer_match else "None"
+ exact_answer = (
+ answer_match.group(1).strip() if answer_match else "None"
+ )
# Extract confidence from the response
confidence_match = re.search(r"Confidence:\s*(\d+)%", response)
- confidence = confidence_match.group(1) if confidence_match else "100"
+ confidence = (
+ confidence_match.group(1) if confidence_match else "100"
+ )
# Simple accuracy check (for basic reporting)
# Note: Real evaluation would use a more sophisticated approach
@@ -196,7 +212,7 @@ def run_browsecomp_evaluation(
print(f" Response: {exact_answer}")
print(f" Correct: {is_correct}")
print(
- f" Current accuracy: {correct_count}/{i+1} ({(correct_count/(i+1))*100:.1f}%)"
+ f" Current accuracy: {correct_count}/{i + 1} ({(correct_count / (i + 1)) * 100:.1f}%)"
)
except Exception as e:
@@ -233,7 +249,7 @@ def run_browsecomp_evaluation(
with open(report_path, "w") as f:
json.dump(report, f, indent=2)
- print(f"\nEvaluation complete.")
+ print("\nEvaluation complete.")
print(f"Results saved to {output_path}")
print(f"Summary saved to {report_path}")
print(f"Final accuracy: {accuracy:.4f} ({correct_count}/{len(examples)})")
@@ -255,10 +271,16 @@ if __name__ == "__main__":
help="Number of examples to use (default: 10)",
)
parser.add_argument(
- "--iterations", type=int, default=2, help="Search iterations (default: 2)"
+ "--iterations",
+ type=int,
+ default=2,
+ help="Search iterations (default: 2)",
)
parser.add_argument(
- "--questions", type=int, default=9, help="Questions per iteration (default: 9)"
+ "--questions",
+ type=int,
+ default=9,
+ help="Questions per iteration (default: 9)",
)
parser.add_argument(
"--search-tool",
diff --git a/examples/benchmarks/claude_grading/benchmark.py b/examples/benchmarks/claude_grading/benchmark.py
index 201c9f2466..63bc1032e2 100755
--- a/examples/benchmarks/claude_grading/benchmark.py
+++ b/examples/benchmarks/claude_grading/benchmark.py
@@ -34,7 +34,8 @@ else:
# Configure logging
logging.basicConfig(
- level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+ level=logging.INFO,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
@@ -110,7 +111,9 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):
from local_deep_research.benchmarks.evaluators.composite import (
CompositeBenchmarkEvaluator,
)
- from local_deep_research.benchmarks.evaluators.simpleqa import SimpleQAEvaluator
+ from local_deep_research.benchmarks.evaluators.simpleqa import (
+ SimpleQAEvaluator,
+ )
from local_deep_research.config.llm_config import get_llm
except ImportError as e:
print(f"Error importing benchmark components: {e}")
@@ -157,7 +160,9 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):
# Create timestamp for output
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
- output_dir = os.path.join("benchmark_results", f"claude_grading_{timestamp}")
+ output_dir = os.path.join(
+ "benchmark_results", f"claude_grading_{timestamp}"
+ )
os.makedirs(output_dir, exist_ok=True)
config = {
@@ -189,7 +194,9 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):
)
simpleqa_duration = time.time() - simpleqa_start
- print(f"SimpleQA evaluation complete in {simpleqa_duration:.1f} seconds")
+ print(
+ f"SimpleQA evaluation complete in {simpleqa_duration:.1f} seconds"
+ )
print(f"SimpleQA accuracy: {simpleqa_results.get('accuracy', 0):.4f}")
print(f"SimpleQA metrics: {simpleqa_results.get('metrics', {})}")
@@ -223,12 +230,16 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):
)
browsecomp_duration = time.time() - browsecomp_start
- print(f"BrowseComp evaluation complete in {browsecomp_duration:.1f} seconds")
+ print(
+ f"BrowseComp evaluation complete in {browsecomp_duration:.1f} seconds"
+ )
print(f"BrowseComp score: {browsecomp_results.get('score', 0):.4f}")
print(f"BrowseComp metrics: {browsecomp_results.get('metrics', {})}")
# Save results
- with open(os.path.join(output_dir, "browsecomp_results.json"), "w") as f:
+ with open(
+ os.path.join(output_dir, "browsecomp_results.json"), "w"
+ ) as f:
json.dump(browsecomp_results, f, indent=2)
except Exception as e:
print(f"Error during BrowseComp evaluation: {e}")
@@ -245,7 +256,9 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):
try:
# Create composite evaluator with benchmark weights (without evaluation_config parameter)
benchmark_weights = {"simpleqa": 0.5, "browsecomp": 0.5}
- composite = CompositeBenchmarkEvaluator(benchmark_weights=benchmark_weights)
+ composite = CompositeBenchmarkEvaluator(
+ benchmark_weights=benchmark_weights
+ )
composite_results = composite.evaluate(
config,
num_examples=examples,
@@ -253,7 +266,9 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):
)
composite_duration = time.time() - composite_start
- print(f"Composite evaluation complete in {composite_duration:.1f} seconds")
+ print(
+ f"Composite evaluation complete in {composite_duration:.1f} seconds"
+ )
print(f"Composite score: {composite_results.get('score', 0):.4f}")
# Save results
@@ -278,9 +293,15 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):
print("Restored original graders.get_evaluation_llm function")
return {
- "simpleqa": simpleqa_results if "simpleqa_results" in locals() else None,
- "browsecomp": browsecomp_results if "browsecomp_results" in locals() else None,
- "composite": composite_results if "composite_results" in locals() else None,
+ "simpleqa": simpleqa_results
+ if "simpleqa_results" in locals()
+ else None,
+ "browsecomp": browsecomp_results
+ if "browsecomp_results" in locals()
+ else None,
+ "composite": composite_results
+ if "composite_results" in locals()
+ else None,
}
@@ -298,7 +319,10 @@ def main():
help="Strategy to evaluate (default: source_based)",
)
parser.add_argument(
- "--iterations", type=int, default=1, help="Number of iterations (default: 1)"
+ "--iterations",
+ type=int,
+ default=1,
+ help="Number of iterations (default: 1)",
)
parser.add_argument(
"--examples",
@@ -318,7 +342,9 @@ def main():
# Run the evaluation
results = run_benchmark(
- strategy=args.strategy, iterations=args.iterations, examples=args.examples
+ strategy=args.strategy,
+ iterations=args.iterations,
+ examples=args.examples,
)
# Return success if at least one benchmark completed
diff --git a/examples/benchmarks/gemini/run_gemini_benchmark_fixed.py b/examples/benchmarks/gemini/run_gemini_benchmark_fixed.py
index afcae65ac5..5f45b5d51e 100755
--- a/examples/benchmarks/gemini/run_gemini_benchmark_fixed.py
+++ b/examples/benchmarks/gemini/run_gemini_benchmark_fixed.py
@@ -42,12 +42,16 @@ def patched_get_llm(
model_name=None, temperature=None, provider=None, openai_endpoint_url=None
):
"""Patched version that always uses Gemini via OpenRouter"""
- if model_name == "gemma3:12b": # This is the default model that causes the error
+ if (
+ model_name == "gemma3:12b"
+ ): # This is the default model that causes the error
print("Overriding local model with Gemini 2.0 Flash")
model_name = "google/gemini-2.0-flash-001"
provider = "openai_endpoint"
openai_endpoint_url = "https://openrouter.ai/api/v1"
- return original_get_llm(model_name, temperature, provider, openai_endpoint_url)
+ return original_get_llm(
+ model_name, temperature, provider, openai_endpoint_url
+ )
# Apply the patch
@@ -59,7 +63,9 @@ def run_benchmark(examples=1):
try:
# Create timestamp for output
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
- output_dir = os.path.join("../../benchmark_results", f"gemini_eval_{timestamp}")
+ output_dir = os.path.join(
+ "../../benchmark_results", f"gemini_eval_{timestamp}"
+ )
os.makedirs(output_dir, exist_ok=True)
# Setup the Gemini configuration
@@ -80,14 +86,21 @@ def run_benchmark(examples=1):
)
simpleqa_duration = time.time() - simpleqa_start
- print(f"SimpleQA evaluation complete in {simpleqa_duration:.1f} seconds")
- if isinstance(simpleqa_results, dict) and "accuracy" in simpleqa_results:
+ print(
+ f"SimpleQA evaluation complete in {simpleqa_duration:.1f} seconds"
+ )
+ if (
+ isinstance(simpleqa_results, dict)
+ and "accuracy" in simpleqa_results
+ ):
print(f"SimpleQA accuracy: {simpleqa_results['accuracy']:.4f}")
else:
print("SimpleQA accuracy: N/A")
# Run BrowseComp benchmark
- print(f"\n=== Running BrowseComp benchmark with {examples} examples ===")
+ print(
+ f"\n=== Running BrowseComp benchmark with {examples} examples ==="
+ )
browsecomp_start = time.time()
browsecomp_results = evaluate_browsecomp(
@@ -101,14 +114,19 @@ def run_benchmark(examples=1):
)
browsecomp_duration = time.time() - browsecomp_start
- print(f"BrowseComp evaluation complete in {browsecomp_duration:.1f} seconds")
- if isinstance(browsecomp_results, dict) and "accuracy" in browsecomp_results:
+ print(
+ f"BrowseComp evaluation complete in {browsecomp_duration:.1f} seconds"
+ )
+ if (
+ isinstance(browsecomp_results, dict)
+ and "accuracy" in browsecomp_results
+ ):
print(f"BrowseComp accuracy: {browsecomp_results['accuracy']:.4f}")
else:
print("BrowseComp accuracy: N/A")
# Generate summary
- print(f"\n=== Evaluation Summary ===")
+ print("\n=== Evaluation Summary ===")
print(f"Examples: {examples}")
print(f"Model: {gemini_config.get('model_name', 'unknown')}")
print(f"Provider: {gemini_config.get('provider', 'unknown')}")
@@ -131,7 +149,9 @@ def main():
# Parse command line arguments
import argparse
- parser = argparse.ArgumentParser(description="Run benchmark with Gemini 2.0 Flash")
+ parser = argparse.ArgumentParser(
+ description="Run benchmark with Gemini 2.0 Flash"
+ )
parser.add_argument(
"--examples",
type=int,
@@ -141,7 +161,9 @@ def main():
args = parser.parse_args()
- print(f"Starting benchmark with Gemini 2.0 Flash on {args.examples} examples")
+ print(
+ f"Starting benchmark with Gemini 2.0 Flash on {args.examples} examples"
+ )
# Run the evaluation
results = run_benchmark(examples=args.examples)
diff --git a/examples/benchmarks/run_browsecomp.py b/examples/benchmarks/run_browsecomp.py
index 481f592195..9ffd5264a9 100644
--- a/examples/benchmarks/run_browsecomp.py
+++ b/examples/benchmarks/run_browsecomp.py
@@ -17,24 +17,13 @@ import argparse
import base64
import hashlib
import json
-import logging
import os
import re
import sys
import time
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict
-# Configure logging
-logging.basicConfig(
- level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
-)
-logger = logging.getLogger(__name__)
-
-# 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"))
+from loguru import logger
from local_deep_research.api import quick_summary
from local_deep_research.benchmarks.datasets import load_dataset
@@ -94,7 +83,9 @@ def run_browsecomp_with_canary(
# Set up output files
timestamp = time.strftime("%Y%m%d_%H%M%S")
- results_file = os.path.join(output_dir, f"browsecomp_{timestamp}_results.jsonl")
+ results_file = os.path.join(
+ output_dir, f"browsecomp_{timestamp}_results.jsonl"
+ )
evaluation_file = os.path.join(
output_dir, f"browsecomp_{timestamp}_evaluation.jsonl"
)
@@ -147,11 +138,15 @@ def run_browsecomp_with_canary(
# Extract exact answer from the response
answer_match = re.search(r"Exact Answer:\s*(.*?)(?:\n|$)", response)
- exact_answer = answer_match.group(1).strip() if answer_match else "None"
+ exact_answer = (
+ answer_match.group(1).strip() if answer_match else "None"
+ )
# Extract confidence from the response
confidence_match = re.search(r"Confidence:\s*(\d+)%", response)
- confidence = confidence_match.group(1) if confidence_match else "100"
+ confidence = (
+ confidence_match.group(1) if confidence_match else "100"
+ )
# Format result
result = {
@@ -226,7 +221,8 @@ def run_browsecomp_with_canary(
)
accuracy = correct_count / len(results) if results else 0
avg_time = (
- sum(result.get("processing_time", 0) for result in results) / len(results)
+ sum(result.get("processing_time", 0) for result in results)
+ / len(results)
if results
else 0
)
diff --git a/examples/benchmarks/run_gemini_benchmark.py b/examples/benchmarks/run_gemini_benchmark.py
index 15ae0161e1..f57e3ce310 100644
--- a/examples/benchmarks/run_gemini_benchmark.py
+++ b/examples/benchmarks/run_gemini_benchmark.py
@@ -15,16 +15,9 @@ Usage:
import argparse
import os
-import sys
import time
from datetime import datetime
-# 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"))
-
# Import the benchmark functionality
from local_deep_research.benchmarks.benchmark_functions import (
evaluate_browsecomp,
@@ -118,17 +111,24 @@ def run_benchmark(args):
)
duration = time.time() - start_time
- print(f"{benchmark['name']} evaluation complete in {duration:.1f} seconds")
+ print(
+ f"{benchmark['name']} evaluation complete in {duration:.1f} seconds"
+ )
- if isinstance(benchmark_result, dict) and "accuracy" in benchmark_result:
- print(f"{benchmark['name']} accuracy: {benchmark_result['accuracy']:.4f}")
+ if (
+ isinstance(benchmark_result, dict)
+ and "accuracy" in benchmark_result
+ ):
+ print(
+ f"{benchmark['name']} accuracy: {benchmark_result['accuracy']:.4f}"
+ )
else:
print(f"{benchmark['name']} accuracy: N/A")
results[benchmark["name"].lower()] = benchmark_result
# Print summary
- print(f"\n=== Benchmark Summary ===")
+ print("\n=== Benchmark Summary ===")
print(f"Model: {config['model_name']}")
print(f"Provider: {config['provider']}")
print(f"Examples: {args.examples}")
@@ -145,7 +145,10 @@ def main():
# API key is required
parser.add_argument(
- "--api-key", type=str, required=True, help="OpenRouter API key (required)"
+ "--api-key",
+ type=str,
+ required=True,
+ help="OpenRouter API key (required)",
)
# Benchmark selection (at least one required)
@@ -159,7 +162,10 @@ def main():
# Benchmark parameters
parser.add_argument(
- "--examples", type=int, default=3, help="Number of examples to run (default: 3)"
+ "--examples",
+ type=int,
+ default=3,
+ help="Number of examples to run (default: 3)",
)
parser.add_argument(
"--iterations",
@@ -168,7 +174,10 @@ def main():
help="Number of search iterations (default: 2)",
)
parser.add_argument(
- "--questions", type=int, default=3, help="Questions per iteration (default: 3)"
+ "--questions",
+ type=int,
+ default=3,
+ help="Questions per iteration (default: 3)",
)
parser.add_argument(
"--search-tool",
@@ -192,7 +201,9 @@ def main():
"At least one benchmark must be selected (--simpleqa or --browsecomp)"
)
- print(f"Starting benchmarks with Gemini 2.0 Flash on {args.examples} examples")
+ print(
+ f"Starting benchmarks with Gemini 2.0 Flash on {args.examples} examples"
+ )
run_benchmark(args)
diff --git a/examples/benchmarks/run_resumable_parallel_benchmark.py b/examples/benchmarks/run_resumable_parallel_benchmark.py
index ab75a69004..7ed173ef3b 100644
--- a/examples/benchmarks/run_resumable_parallel_benchmark.py
+++ b/examples/benchmarks/run_resumable_parallel_benchmark.py
@@ -17,7 +17,6 @@ Usage:
import argparse
import concurrent.futures
import json
-import logging
import os
import sys
import time
@@ -25,11 +24,7 @@ from datetime import datetime
from pathlib import Path
from typing import Any, Dict, Optional, Tuple
-# 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"))
+from loguru import logger
from local_deep_research.api import quick_summary
from local_deep_research.benchmarks.datasets import load_dataset
@@ -37,14 +32,17 @@ from local_deep_research.benchmarks.graders import (
extract_answer_from_response,
grade_results,
)
-from local_deep_research.benchmarks.metrics import calculate_metrics, generate_report
+from local_deep_research.benchmarks.metrics import (
+ calculate_metrics,
+ generate_report,
+)
from local_deep_research.benchmarks.runners import format_query
-# Configure logging
-logging.basicConfig(
- level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+
+# Add the src directory to the Python path
+project_root = os.path.abspath(
+ os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
)
-logger = logging.getLogger(__name__)
def load_existing_results(results_file: str) -> Dict[str, Dict]:
@@ -62,12 +60,16 @@ def load_existing_results(results_file: str) -> Dict[str, Dict]:
if result_id:
results[result_id] = result
except json.JSONDecodeError:
- logger.warning(f"Skipping invalid JSON line: {line[:50]}...")
+ logger.warning(
+ f"Skipping invalid JSON line: {line[:50]}..."
+ )
logger.info(f"Loaded {len(results)} existing results")
return results
-def find_latest_results_file(output_dir: str, dataset_type: str) -> Optional[str]:
+def find_latest_results_file(
+ output_dir: str, dataset_type: str
+) -> Optional[str]:
"""Find the most recent results file for a dataset."""
# First try dataset subdirectory
dataset_dir = os.path.join(output_dir, dataset_type)
@@ -109,16 +111,22 @@ def run_resumable_benchmark(
# Determine output files
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
- results_file = os.path.join(output_dir, f"{dataset_type}_{timestamp}_results.jsonl")
+ results_file = os.path.join(
+ output_dir, f"{dataset_type}_{timestamp}_results.jsonl"
+ )
evaluation_file = os.path.join(
output_dir, f"{dataset_type}_{timestamp}_evaluation.jsonl"
)
- report_file = os.path.join(output_dir, f"{dataset_type}_{timestamp}_report.md")
+ report_file = os.path.join(
+ output_dir, f"{dataset_type}_{timestamp}_report.md"
+ )
# Load existing results if resuming
existing_results = {}
if resume_from:
- existing_results_file = find_latest_results_file(resume_from, dataset_type)
+ existing_results_file = find_latest_results_file(
+ resume_from, dataset_type
+ )
if existing_results_file:
existing_results = load_existing_results(existing_results_file)
logger.info(
@@ -244,7 +252,9 @@ def run_resumable_benchmark(
dataset_type=dataset_type,
evaluation_config=evaluation_config,
)
- logger.info(f"Evaluation results for {dataset_type}: {evaluation_results}")
+ logger.info(
+ f"Evaluation results for {dataset_type}: {evaluation_results}"
+ )
# Calculate metrics
metrics = calculate_metrics(evaluation_file)
@@ -276,7 +286,9 @@ def run_resumable_benchmark(
def run_simpleqa_benchmark_wrapper(args: Tuple) -> Dict[str, Any]:
"""Wrapper for running SimpleQA benchmark in parallel."""
- num_examples, output_dir, resume_from, search_config, evaluation_config = args
+ num_examples, output_dir, resume_from, search_config, evaluation_config = (
+ args
+ )
logger.info(f"Starting SimpleQA benchmark with {num_examples} examples")
start_time = time.time()
@@ -298,7 +310,9 @@ def run_simpleqa_benchmark_wrapper(args: Tuple) -> Dict[str, Any]:
def run_browsecomp_benchmark_wrapper(args: Tuple) -> Dict[str, Any]:
"""Wrapper for running BrowseComp benchmark in parallel."""
- num_examples, output_dir, resume_from, search_config, evaluation_config = args
+ num_examples, output_dir, resume_from, search_config, evaluation_config = (
+ args
+ )
logger.info(f"Starting BrowseComp benchmark with {num_examples} examples")
start_time = time.time()
@@ -321,7 +335,9 @@ def run_browsecomp_benchmark_wrapper(args: Tuple) -> Dict[str, Any]:
return results
-def setup_llm_environment(model=None, provider=None, endpoint_url=None, api_key=None):
+def setup_llm_environment(
+ model=None, provider=None, endpoint_url=None, api_key=None
+):
"""Set up environment variables for LLM configuration."""
if model:
os.environ["LDR_LLM__MODEL"] = model
@@ -368,7 +384,8 @@ def main():
# LLM configuration options
parser.add_argument(
- "--model", help="Model name for the LLM (e.g., 'google/gemini-2.0-flash-001')"
+ "--model",
+ help="Model name for the LLM (e.g., 'google/gemini-2.0-flash-001')",
)
parser.add_argument(
"--provider",
@@ -390,7 +407,9 @@ def main():
project_root, "benchmark_results", f"resumed_benchmark_{timestamp}"
)
os.makedirs(output_dir, exist_ok=True)
- logger.info(f"Resuming from {args.resume_from}, new results in {output_dir}")
+ logger.info(
+ f"Resuming from {args.resume_from}, new results in {output_dir}"
+ )
else:
# Create new timestamp directory
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
diff --git a/examples/benchmarks/run_simpleqa.py b/examples/benchmarks/run_simpleqa.py
index 517b44c566..187c34f01f 100644
--- a/examples/benchmarks/run_simpleqa.py
+++ b/examples/benchmarks/run_simpleqa.py
@@ -17,12 +17,6 @@ import argparse
import os
import sys
-# 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"))
-
# Import the benchmark functionality
from local_deep_research.benchmarks.benchmark_functions import evaluate_simpleqa
@@ -48,13 +42,17 @@ def main():
default=os.path.join("examples", "benchmarks", "results", "simpleqa"),
help="Output directory",
)
- parser.add_argument("--no-eval", action="store_true", help="Skip evaluation")
+ parser.add_argument(
+ "--no-eval", action="store_true", help="Skip evaluation"
+ )
# Optional evaluation parameters
parser.add_argument(
"--human-eval", action="store_true", help="Use human evaluation"
)
- parser.add_argument("--eval-model", type=str, help="Model to use for evaluation")
+ parser.add_argument(
+ "--eval-model", type=str, help="Model to use for evaluation"
+ )
parser.add_argument(
"--eval-provider", type=str, help="Provider to use for evaluation"
)
@@ -64,7 +62,9 @@ def main():
"--search-model", type=str, help="Model to use for the search system"
)
parser.add_argument(
- "--search-provider", type=str, help="Provider to use for the search system"
+ "--search-provider",
+ type=str,
+ help="Provider to use for the search system",
)
parser.add_argument(
"--endpoint-url",
diff --git a/examples/benchmarks/scripts/run_benchmark_with_claude_grading.py b/examples/benchmarks/scripts/run_benchmark_with_claude_grading.py
index e5529b729a..3dfc22e221 100755
--- a/examples/benchmarks/scripts/run_benchmark_with_claude_grading.py
+++ b/examples/benchmarks/scripts/run_benchmark_with_claude_grading.py
@@ -34,7 +34,8 @@ else:
# Configure logging
logging.basicConfig(
- level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+ level=logging.INFO,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
@@ -110,7 +111,9 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):
from local_deep_research.benchmarks.evaluators.composite import (
CompositeBenchmarkEvaluator,
)
- from local_deep_research.benchmarks.evaluators.simpleqa import SimpleQAEvaluator
+ from local_deep_research.benchmarks.evaluators.simpleqa import (
+ SimpleQAEvaluator,
+ )
from local_deep_research.config.llm_config import get_llm
except ImportError as e:
print(f"Error importing benchmark components: {e}")
@@ -157,7 +160,9 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):
# Create timestamp for output
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
- output_dir = os.path.join("benchmark_results", f"claude_grading_{timestamp}")
+ output_dir = os.path.join(
+ "benchmark_results", f"claude_grading_{timestamp}"
+ )
os.makedirs(output_dir, exist_ok=True)
config = {
@@ -189,7 +194,9 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):
)
simpleqa_duration = time.time() - simpleqa_start
- print(f"SimpleQA evaluation complete in {simpleqa_duration:.1f} seconds")
+ print(
+ f"SimpleQA evaluation complete in {simpleqa_duration:.1f} seconds"
+ )
print(f"SimpleQA accuracy: {simpleqa_results.get('accuracy', 0):.4f}")
print(f"SimpleQA metrics: {simpleqa_results.get('metrics', {})}")
@@ -223,12 +230,16 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):
)
browsecomp_duration = time.time() - browsecomp_start
- print(f"BrowseComp evaluation complete in {browsecomp_duration:.1f} seconds")
+ print(
+ f"BrowseComp evaluation complete in {browsecomp_duration:.1f} seconds"
+ )
print(f"BrowseComp score: {browsecomp_results.get('score', 0):.4f}")
print(f"BrowseComp metrics: {browsecomp_results.get('metrics', {})}")
# Save results
- with open(os.path.join(output_dir, "browsecomp_results.json"), "w") as f:
+ with open(
+ os.path.join(output_dir, "browsecomp_results.json"), "w"
+ ) as f:
json.dump(browsecomp_results, f, indent=2)
except Exception as e:
print(f"Error during BrowseComp evaluation: {e}")
@@ -245,7 +256,9 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):
try:
# Create composite evaluator with benchmark weights (without evaluation_config parameter)
benchmark_weights = {"simpleqa": 0.5, "browsecomp": 0.5}
- composite = CompositeBenchmarkEvaluator(benchmark_weights=benchmark_weights)
+ composite = CompositeBenchmarkEvaluator(
+ benchmark_weights=benchmark_weights
+ )
composite_results = composite.evaluate(
config,
num_examples=examples,
@@ -253,7 +266,9 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):
)
composite_duration = time.time() - composite_start
- print(f"Composite evaluation complete in {composite_duration:.1f} seconds")
+ print(
+ f"Composite evaluation complete in {composite_duration:.1f} seconds"
+ )
print(f"Composite score: {composite_results.get('score', 0):.4f}")
# Save results
@@ -266,7 +281,7 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):
traceback.print_exc()
# Generate summary
- print(f"\n=== Evaluation Summary ===")
+ print("\n=== Evaluation Summary ===")
print(f"Strategy: {strategy}")
print(f"Iterations: {iterations}")
print(f"Examples: {examples}")
@@ -278,9 +293,15 @@ def run_benchmark(strategy="source_based", iterations=1, examples=5):
print("Restored original graders.get_evaluation_llm function")
return {
- "simpleqa": simpleqa_results if "simpleqa_results" in locals() else None,
- "browsecomp": browsecomp_results if "browsecomp_results" in locals() else None,
- "composite": composite_results if "composite_results" in locals() else None,
+ "simpleqa": simpleqa_results
+ if "simpleqa_results" in locals()
+ else None,
+ "browsecomp": browsecomp_results
+ if "browsecomp_results" in locals()
+ else None,
+ "composite": composite_results
+ if "composite_results" in locals()
+ else None,
}
@@ -298,7 +319,10 @@ def main():
help="Strategy to evaluate (default: source_based)",
)
parser.add_argument(
- "--iterations", type=int, default=1, help="Number of iterations (default: 1)"
+ "--iterations",
+ type=int,
+ default=1,
+ help="Number of iterations (default: 1)",
)
parser.add_argument(
"--examples",
@@ -316,7 +340,9 @@ def main():
# Run the evaluation
results = run_benchmark(
- strategy=args.strategy, iterations=args.iterations, examples=args.examples
+ strategy=args.strategy,
+ iterations=args.iterations,
+ examples=args.examples,
)
# Return success if at least one benchmark completed
diff --git a/examples/benchmarks/scripts/run_focused_benchmark_fixed.py b/examples/benchmarks/scripts/run_focused_benchmark_fixed.py
index 3497674f0a..0548143947 100755
--- a/examples/benchmarks/scripts/run_focused_benchmark_fixed.py
+++ b/examples/benchmarks/scripts/run_focused_benchmark_fixed.py
@@ -31,7 +31,8 @@ else:
# Configure logging
logging.basicConfig(
- level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+ level=logging.INFO,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
@@ -107,7 +108,9 @@ def run_direct_evaluation(strategy="source_based", iterations=1, examples=5):
from local_deep_research.benchmarks.evaluators.composite import (
CompositeBenchmarkEvaluator,
)
- from local_deep_research.benchmarks.evaluators.simpleqa import SimpleQAEvaluator
+ from local_deep_research.benchmarks.evaluators.simpleqa import (
+ SimpleQAEvaluator,
+ )
from local_deep_research.config.llm_config import get_llm
except ImportError as e:
print(f"Error importing benchmark components: {e}")
@@ -186,7 +189,9 @@ def run_direct_evaluation(strategy="source_based", iterations=1, examples=5):
)
simpleqa_duration = time.time() - simpleqa_start
- print(f"SimpleQA evaluation complete in {simpleqa_duration:.1f} seconds")
+ print(
+ f"SimpleQA evaluation complete in {simpleqa_duration:.1f} seconds"
+ )
print(f"SimpleQA accuracy: {simpleqa_results.get('accuracy', 0):.4f}")
print(f"SimpleQA metrics: {simpleqa_results.get('metrics', {})}")
@@ -220,12 +225,16 @@ def run_direct_evaluation(strategy="source_based", iterations=1, examples=5):
)
browsecomp_duration = time.time() - browsecomp_start
- print(f"BrowseComp evaluation complete in {browsecomp_duration:.1f} seconds")
+ print(
+ f"BrowseComp evaluation complete in {browsecomp_duration:.1f} seconds"
+ )
print(f"BrowseComp score: {browsecomp_results.get('score', 0):.4f}")
print(f"BrowseComp metrics: {browsecomp_results.get('metrics', {})}")
# Save results
- with open(os.path.join(output_dir, "browsecomp_results.json"), "w") as f:
+ with open(
+ os.path.join(output_dir, "browsecomp_results.json"), "w"
+ ) as f:
json.dump(browsecomp_results, f, indent=2)
except Exception as e:
print(f"Error during BrowseComp evaluation: {e}")
@@ -242,7 +251,9 @@ def run_direct_evaluation(strategy="source_based", iterations=1, examples=5):
try:
# Create composite evaluator with benchmark weights (without evaluation_config parameter)
benchmark_weights = {"simpleqa": 0.5, "browsecomp": 0.5}
- composite = CompositeBenchmarkEvaluator(benchmark_weights=benchmark_weights)
+ composite = CompositeBenchmarkEvaluator(
+ benchmark_weights=benchmark_weights
+ )
composite_results = composite.evaluate(
config,
num_examples=examples,
@@ -250,7 +261,9 @@ def run_direct_evaluation(strategy="source_based", iterations=1, examples=5):
)
composite_duration = time.time() - composite_start
- print(f"Composite evaluation complete in {composite_duration:.1f} seconds")
+ print(
+ f"Composite evaluation complete in {composite_duration:.1f} seconds"
+ )
print(f"Composite score: {composite_results.get('score', 0):.4f}")
# Save results
@@ -263,7 +276,7 @@ def run_direct_evaluation(strategy="source_based", iterations=1, examples=5):
traceback.print_exc()
# Generate summary
- print(f"\n=== Evaluation Summary ===")
+ print("\n=== Evaluation Summary ===")
print(f"Strategy: {strategy}")
print(f"Iterations: {iterations}")
print(f"Examples: {examples}")
@@ -275,9 +288,15 @@ def run_direct_evaluation(strategy="source_based", iterations=1, examples=5):
print("Restored original graders.get_evaluation_llm function")
return {
- "simpleqa": simpleqa_results if "simpleqa_results" in locals() else None,
- "browsecomp": browsecomp_results if "browsecomp_results" in locals() else None,
- "composite": composite_results if "composite_results" in locals() else None,
+ "simpleqa": simpleqa_results
+ if "simpleqa_results" in locals()
+ else None,
+ "browsecomp": browsecomp_results
+ if "browsecomp_results" in locals()
+ else None,
+ "composite": composite_results
+ if "composite_results" in locals()
+ else None,
}
@@ -285,7 +304,9 @@ def main():
# Parse command line arguments
import argparse
- parser = argparse.ArgumentParser(description="Run focused strategy benchmark")
+ parser = argparse.ArgumentParser(
+ description="Run focused strategy benchmark"
+ )
parser.add_argument(
"--strategy",
type=str,
@@ -293,7 +314,10 @@ def main():
help="Strategy to evaluate (default: source_based)",
)
parser.add_argument(
- "--iterations", type=int, default=1, help="Number of iterations (default: 1)"
+ "--iterations",
+ type=int,
+ default=1,
+ help="Number of iterations (default: 1)",
)
parser.add_argument(
"--examples",
@@ -311,7 +335,9 @@ def main():
# Run the evaluation
results = run_direct_evaluation(
- strategy=args.strategy, iterations=args.iterations, examples=args.examples
+ strategy=args.strategy,
+ iterations=args.iterations,
+ examples=args.examples,
)
# Return success if at least one benchmark completed
diff --git a/examples/benchmarks/scripts/run_grader_only.py b/examples/benchmarks/scripts/run_grader_only.py
index 0adc0b6e75..f9193f75c5 100644
--- a/examples/benchmarks/scripts/run_grader_only.py
+++ b/examples/benchmarks/scripts/run_grader_only.py
@@ -11,7 +11,6 @@ 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"))
@@ -29,7 +28,8 @@ else:
# Configure logging
logging.basicConfig(
- level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+ level=logging.INFO,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
@@ -150,7 +150,7 @@ def grade_benchmark_results(results_path, dataset_type="simpleqa"):
evaluation_path = os.path.join(results_dir, evaluation_filename)
# Run the grading
- print(f"Starting grading of benchmark results...")
+ print("Starting grading of benchmark results...")
grading_start_time = time.time()
try:
evaluation_results = grade_results(
@@ -159,7 +159,7 @@ def grade_benchmark_results(results_path, dataset_type="simpleqa"):
dataset_type=dataset_type,
evaluation_config=evaluation_config,
progress_callback=lambda current, total, meta: print(
- f"Grading progress: {current+1}/{total} ({((current+1)/total*100):.1f}%)"
+ f"Grading progress: {current + 1}/{total} ({((current + 1) / total * 100):.1f}%)"
),
)
@@ -234,7 +234,9 @@ def generate_summary(evaluation_path, output_dir=None):
generate_report(
metrics=metrics,
output_file=report_path,
- dataset_type="simpleqa" if "simpleqa" in evaluation_path else "browsecomp",
+ dataset_type="simpleqa"
+ if "simpleqa" in evaluation_path
+ else "browsecomp",
)
# Print summary
@@ -262,7 +264,10 @@ def main():
description="Run Claude API grading on existing benchmark results"
)
parser.add_argument(
- "--results", type=str, required=True, help="Path to the results JSONL file"
+ "--results",
+ type=str,
+ required=True,
+ help="Path to the results JSONL file",
)
parser.add_argument(
"--dataset-type",
diff --git a/examples/elasticsearch_search_example.py b/examples/elasticsearch_search_example.py
index d38ada573b..007061b3ce 100644
--- a/examples/elasticsearch_search_example.py
+++ b/examples/elasticsearch_search_example.py
@@ -169,7 +169,9 @@ def main():
advanced_search_examples(index_name)
except Exception as e:
- logger.error(f"运行示例时出错: {str(e)}") # Error running example: {str(e)}
+ logger.error(
+ f"运行示例时出错: {str(e)}"
+ ) # Error running example: {str(e)}
logger.error(
"请确保 Elasticsearch 正在运行,默认地址为 http://localhost:9200"
) # Make sure Elasticsearch is running, default address is http://localhost:9200
diff --git a/examples/example_browsecomp.py b/examples/example_browsecomp.py
index 7aaaeb4c04..e967628370 100644
--- a/examples/example_browsecomp.py
+++ b/examples/example_browsecomp.py
@@ -9,7 +9,8 @@ import sys
# Configure logging
logging.basicConfig(
- level=logging.DEBUG, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+ level=logging.DEBUG,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger()
@@ -35,7 +36,9 @@ def test_browsecomp_decryption():
print("Error: No examples loaded from dataset")
return
- print(f"Successfully loaded {len(examples)} examples from BrowseComp dataset\n")
+ print(
+ f"Successfully loaded {len(examples)} examples from BrowseComp dataset\n"
+ )
# Check if decryption worked by examining examples
for i, example in enumerate(examples):
@@ -48,12 +51,16 @@ def test_browsecomp_decryption():
print(
f" Original problem (encrypted): {example.get('original_problem', '')[:50]}..."
)
- print(f" Decrypted problem: {example.get('problem', '')[:50]}...")
+ print(
+ f" Decrypted problem: {example.get('problem', '')[:50]}..."
+ )
print(
f" Decrypted answer: {example.get('correct_answer', '')[:50]}..."
)
else:
- print(" Decryption may have failed - no original_problem field")
+ print(
+ " Decryption may have failed - no original_problem field"
+ )
print(f" Problem: {example.get('problem', '')[:50]}...")
print(f" Answer: {example.get('answer', '')[:50]}...")
@@ -97,7 +104,9 @@ def test_simpleqa_loading():
print("Error: No examples loaded from dataset")
return
- print(f"Successfully loaded {len(examples)} examples from SimpleQA dataset\n")
+ print(
+ f"Successfully loaded {len(examples)} examples from SimpleQA dataset\n"
+ )
# Check examples
for i, example in enumerate(examples):
diff --git a/examples/optimization/browsecomp_optimization.py b/examples/optimization/browsecomp_optimization.py
index c44fa54b8c..620f1f8fcd 100755
--- a/examples/optimization/browsecomp_optimization.py
+++ b/examples/optimization/browsecomp_optimization.py
@@ -30,7 +30,8 @@ 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"
+ level=logging.INFO,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
@@ -43,7 +44,9 @@ def main():
)
os.makedirs(output_dir, exist_ok=True)
- print(f"Starting BrowseComp optimization - results will be saved to {output_dir}")
+ print(
+ f"Starting BrowseComp optimization - results will be saved to {output_dir}"
+ )
# Define a simple parameter space for demonstration
param_space = {
@@ -74,7 +77,9 @@ def main():
output_dir=output_dir,
n_trials=3, # Small number for demo purposes
search_tool="searxng",
- benchmark_weights={"browsecomp": 1.0}, # Specify BrowseComp benchmark only
+ benchmark_weights={
+ "browsecomp": 1.0
+ }, # Specify BrowseComp benchmark only
)
print(f"Best balanced parameters: {balanced_params}")
@@ -84,7 +89,10 @@ def main():
summary = {
"timestamp": timestamp,
"benchmark_weights": {"browsecomp": 1.0},
- "balanced": {"parameters": balanced_params, "score": float(balanced_score)},
+ "balanced": {
+ "parameters": balanced_params,
+ "score": float(balanced_score),
+ },
}
with open(
diff --git a/examples/optimization/example_multi_benchmark.py b/examples/optimization/example_multi_benchmark.py
index 7692a1ff85..22e1f30de8 100644
--- a/examples/optimization/example_multi_benchmark.py
+++ b/examples/optimization/example_multi_benchmark.py
@@ -16,7 +16,9 @@ print(f"Current directory: {os.getcwd()}")
print(f"Python path: {sys.path}")
# Add appropriate paths
-sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
+sys.path.insert(
+ 0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))
+)
try:
# Try to import from the local module structure
@@ -44,7 +46,9 @@ except ImportError:
# Create simulation functions if imports fail
def optimize_parameters(*args, **kwargs):
- benchmark_weights = kwargs.get("benchmark_weights", {"simpleqa": 1.0})
+ benchmark_weights = kwargs.get(
+ "benchmark_weights", {"simpleqa": 1.0}
+ )
print(
f"SIMULATION: optimize_parameters called with benchmark_weights={benchmark_weights}"
)
@@ -79,7 +83,9 @@ except ImportError:
}, 0.75
def optimize_for_quality(*args, **kwargs):
- benchmark_weights = kwargs.get("benchmark_weights", {"simpleqa": 1.0})
+ benchmark_weights = kwargs.get(
+ "benchmark_weights", {"simpleqa": 1.0}
+ )
print(
f"SIMULATION: optimize_for_quality called with benchmark_weights={benchmark_weights}"
)
@@ -90,7 +96,9 @@ except ImportError:
}, 0.85
def optimize_for_speed(*args, **kwargs):
- benchmark_weights = kwargs.get("benchmark_weights", {"simpleqa": 1.0})
+ benchmark_weights = kwargs.get(
+ "benchmark_weights", {"simpleqa": 1.0}
+ )
print(
f"SIMULATION: optimize_for_speed called with benchmark_weights={benchmark_weights}"
)
diff --git a/examples/optimization/example_optimization.py b/examples/optimization/example_optimization.py
index c9d5c67adf..bfd3b81c1d 100644
--- a/examples/optimization/example_optimization.py
+++ b/examples/optimization/example_optimization.py
@@ -13,30 +13,20 @@ Usage:
pdm run python examples/optimization/example_optimization.py
"""
-
import json
import logging
import os
-import sys
from datetime import datetime
-# 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"))
-
# Import the optimization functionality
from local_deep_research.benchmarks.optimization import (
- optimize_for_quality,
- optimize_for_speed,
optimize_parameters,
)
-from local_deep_research.benchmarks.optimization.metrics import calculate_combined_score
# Configure logging to see progress
logging.basicConfig(
- level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+ level=logging.INFO,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
@@ -44,11 +34,16 @@ def main():
# Create timestamp for unique output directory
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_dir = os.path.join(
- "examples", "optimization", "results", f"optimization_results_{timestamp}"
+ "examples",
+ "optimization",
+ "results",
+ f"optimization_results_{timestamp}",
)
os.makedirs(output_dir, exist_ok=True)
- print(f"Starting quick optimization demo - results will be saved to {output_dir}")
+ print(
+ f"Starting quick optimization demo - results will be saved to {output_dir}"
+ )
# Demo with just a single simple optimization
print("\n=== Running quick demo optimization ===")
diff --git a/examples/optimization/example_quick_optimization.py b/examples/optimization/example_quick_optimization.py
index 580a4f258b..aaae7de1a4 100644
--- a/examples/optimization/example_quick_optimization.py
+++ b/examples/optimization/example_quick_optimization.py
@@ -13,7 +13,6 @@ Usage:
pdm run python examples/optimization/example_quick_optimization.py
"""
-
import json
import logging
import os
@@ -24,7 +23,8 @@ from typing import Any, Dict, Tuple
# Configure logging
logging.basicConfig(
- level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+ level=logging.INFO,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
@@ -140,7 +140,9 @@ def optimize_for_speed(
}
return simulate_optimization(
- param_space=param_space, n_trials=n_trials, metric_weights=metric_weights
+ param_space=param_space,
+ n_trials=n_trials,
+ metric_weights=metric_weights,
)
@@ -182,7 +184,9 @@ def optimize_for_quality(
}
return simulate_optimization(
- param_space=param_space, n_trials=n_trials, metric_weights=metric_weights
+ param_space=param_space,
+ n_trials=n_trials,
+ metric_weights=metric_weights,
)
@@ -194,7 +198,9 @@ def main():
)
os.makedirs(output_dir, exist_ok=True)
- print(f"Starting quick optimization demo - results will be saved to {output_dir}")
+ print(
+ f"Starting quick optimization demo - results will be saved to {output_dir}"
+ )
# Create a simple parameter space for demonstration
param_space = {
@@ -242,15 +248,23 @@ def main():
# Save results
summary = {
"timestamp": timestamp,
- "balanced": {"parameters": balanced_params, "score": float(balanced_score)},
+ "balanced": {
+ "parameters": balanced_params,
+ "score": float(balanced_score),
+ },
"speed": {"parameters": speed_params, "score": float(speed_score)},
- "quality": {"parameters": quality_params, "score": float(quality_score)},
+ "quality": {
+ "parameters": quality_params,
+ "score": float(quality_score),
+ },
}
with open(os.path.join(output_dir, "optimization_summary.json"), "w") as f:
json.dump(summary, f, indent=2)
- print(f"\nDemo complete! Results saved to {output_dir}/optimization_summary.json")
+ print(
+ f"\nDemo complete! Results saved to {output_dir}/optimization_summary.json"
+ )
print("\nRecommended parameters:")
print(f"- For balanced performance: {balanced_params}")
print(f"- For speed: {speed_params}")
@@ -259,7 +273,9 @@ def main():
print(
"\nNote: This is a simulation for demonstration purposes only. Real optimization"
)
- print("would run actual benchmarks with these parameters to evaluate performance.")
+ print(
+ "would run actual benchmarks with these parameters to evaluate performance."
+ )
if __name__ == "__main__":
diff --git a/examples/optimization/gemini_optimization.py b/examples/optimization/gemini_optimization.py
index 855ccf8898..3476be9e55 100644
--- a/examples/optimization/gemini_optimization.py
+++ b/examples/optimization/gemini_optimization.py
@@ -24,12 +24,6 @@ import os
import sys
from datetime import datetime
-# 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"))
-
# Import the optimization functionality
from local_deep_research.benchmarks.optimization import (
optimize_for_quality,
@@ -39,7 +33,8 @@ from local_deep_research.benchmarks.optimization import (
# Configure logging to see progress
logging.basicConfig(
- level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+ level=logging.INFO,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
@@ -118,13 +113,17 @@ def main():
print(
f"Starting optimization with Gemini 2.0 Flash - results will be saved to {output_dir}"
)
- print(f"Using model: {gemini_config['model_name']} via {gemini_config['provider']}")
+ print(
+ f"Using model: {gemini_config['model_name']} via {gemini_config['provider']}"
+ )
# Set environment variables to ensure proper API access
os.environ["OPENAI_ENDPOINT_API_KEY"] = gemini_config["api_key"]
os.environ["LDR_LLM__OPENAI_ENDPOINT_API_KEY"] = gemini_config["api_key"]
os.environ["OPENAI_ENDPOINT_URL"] = gemini_config["openai_endpoint_url"]
- os.environ["LDR_LLM__OPENAI_ENDPOINT_URL"] = gemini_config["openai_endpoint_url"]
+ os.environ["LDR_LLM__OPENAI_ENDPOINT_URL"] = gemini_config[
+ "openai_endpoint_url"
+ ]
os.environ["LDR_LLM__PROVIDER"] = gemini_config["provider"]
os.environ["LDR_LLM__MODEL"] = gemini_config["model_name"]
diff --git a/examples/optimization/llm_multi_benchmark.py b/examples/optimization/llm_multi_benchmark.py
index aa2bea74d2..106fc62fc5 100644
--- a/examples/optimization/llm_multi_benchmark.py
+++ b/examples/optimization/llm_multi_benchmark.py
@@ -11,29 +11,16 @@ Usage:
"""
import argparse
-import logging
import os
import sys
from datetime import datetime
from typing import Any, Dict, Optional
-# Add src directory to 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"))
-
-from local_deep_research.benchmarks.evaluators import CompositeBenchmarkEvaluator
+from loguru import logger
# Import benchmark optimization functions
from local_deep_research.benchmarks.optimization.api import optimize_parameters
-# Configure logging
-logging.basicConfig(
- level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
-)
-logger = logging.getLogger(__name__)
-
def setup_llm_config(
model: Optional[str] = None,
@@ -130,14 +117,17 @@ def main():
output_dir = args.output_dir
else:
output_dir = os.path.join(
- "examples", "optimization", "results", f"llm_multi_benchmark_{timestamp}"
+ "examples",
+ "optimization",
+ "results",
+ f"llm_multi_benchmark_{timestamp}",
)
os.makedirs(output_dir, exist_ok=True)
print(f"Results will be saved to: {output_dir}")
# Set up LLM configuration
- llm_config = setup_llm_config(
+ setup_llm_config(
model=args.model,
provider=args.provider,
endpoint_url=args.endpoint_url,
@@ -211,7 +201,7 @@ def main():
print(f" OPTIMIZATION RESULTS - {args.mode.upper()} MODE ")
print("=" * 50)
print(f"SCORE: {score:.4f}")
- print(f"Benchmark weights: SimpleQA 70%, BrowseComp 30%")
+ print("Benchmark weights: SimpleQA 70%, BrowseComp 30%")
print(f"Metrics weights: {metric_weights}")
if args.model and args.provider:
@@ -225,7 +215,9 @@ def main():
# Save results to file
import json
- with open(os.path.join(output_dir, "multi_benchmark_results.json"), "w") as f:
+ with open(
+ os.path.join(output_dir, "multi_benchmark_results.json"), "w"
+ ) as f:
json.dump(
{
"timestamp": timestamp,
diff --git a/examples/optimization/multi_benchmark_simulation.py b/examples/optimization/multi_benchmark_simulation.py
index 5365de8e00..4751e381c3 100644
--- a/examples/optimization/multi_benchmark_simulation.py
+++ b/examples/optimization/multi_benchmark_simulation.py
@@ -15,7 +15,8 @@ from typing import Any, Dict, Optional, Tuple
# Configure logging
logging.basicConfig(
- level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+ level=logging.INFO,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
@@ -23,7 +24,9 @@ logger = logging.getLogger(__name__)
class BenchmarkSimulator:
"""Simulates running benchmarks without actually executing them."""
- def __init__(self, name: str, quality_bias: float = 0.7, speed_factor: float = 0.2):
+ def __init__(
+ self, name: str, quality_bias: float = 0.7, speed_factor: float = 0.2
+ ):
"""
Initialize benchmark simulator.
@@ -62,7 +65,9 @@ class BenchmarkSimulator:
self.quality_bias + (iterations * 0.04) - random.uniform(0, 0.2)
)
# SimpleQA is fast
- speed_score = 1.0 - (iterations * questions * self.speed_factor * 0.5)
+ speed_score = 1.0 - (
+ iterations * questions * self.speed_factor * 0.5
+ )
else:
# BrowseComp likes more questions per iteration
quality_score = (
@@ -190,7 +195,9 @@ class OptunaOptimizerSimulator:
"""
self.benchmark_weights = benchmark_weights or {"simpleqa": 1.0}
self.metric_weights = metric_weights or {"quality": 0.6, "speed": 0.4}
- self.benchmark_simulator = CompositeBenchmarkSimulator(benchmark_weights)
+ self.benchmark_simulator = CompositeBenchmarkSimulator(
+ benchmark_weights
+ )
def optimize(
self, param_space: Dict[str, Any], n_trials: int = 10
@@ -228,7 +235,9 @@ class OptunaOptimizerSimulator:
elif param_type == "categorical":
params[param_name] = random.choice(param_config["choices"])
- logger.info(f"Trial {i + 1}/{n_trials}: Testing parameters: {params}")
+ logger.info(
+ f"Trial {i + 1}/{n_trials}: Testing parameters: {params}"
+ )
# Simulate benchmark evaluation
result = self.benchmark_simulator.evaluate(params)
@@ -401,7 +410,9 @@ def main():
print(f"- 60/40 weighted: {params3}")
print("\nNote: This is a simulation for demonstration purposes only.")
- print("Real optimization would run actual benchmarks to evaluate performance.")
+ print(
+ "Real optimization would run actual benchmarks to evaluate performance."
+ )
if __name__ == "__main__":
diff --git a/examples/optimization/multi_benchmark_speed_demo.py b/examples/optimization/multi_benchmark_speed_demo.py
index f7fef99984..e1c2085175 100644
--- a/examples/optimization/multi_benchmark_speed_demo.py
+++ b/examples/optimization/multi_benchmark_speed_demo.py
@@ -78,7 +78,9 @@ class SimulatedCompositeBenchmarkEvaluator:
def evaluate(self, system_config, num_examples=1, output_dir=None):
"""Run evaluation for all benchmarks with weights."""
- print(f"[SIM] Running composite evaluation with {num_examples} examples")
+ print(
+ f"[SIM] Running composite evaluation with {num_examples} examples"
+ )
# Run each benchmark
benchmark_results = {}
@@ -124,7 +126,9 @@ class SimulatedOptimizer:
self.benchmark_weights = benchmark_weights or {"simpleqa": 1.0}
# Create evaluator
- self.evaluator = SimulatedCompositeBenchmarkEvaluator(self.benchmark_weights)
+ self.evaluator = SimulatedCompositeBenchmarkEvaluator(
+ self.benchmark_weights
+ )
print("[SIM] Created optimizer with:")
print(f"[SIM] - Metric weights: {self.metric_weights}")
@@ -165,7 +169,9 @@ class SimulatedOptimizer:
return best_trial, best_score
-def optimize_for_quality(query: str, benchmark_weights: Dict[str, float] = None):
+def optimize_for_quality(
+ query: str, benchmark_weights: Dict[str, float] = None
+):
"""Simulate quality-focused optimization."""
print("\n🔍 Simulating quality-focused optimization...")
@@ -197,7 +203,9 @@ def optimize_for_speed(query: str, benchmark_weights: Dict[str, float] = None):
return optimizer.optimize()
-def optimize_for_efficiency(query: str, benchmark_weights: Dict[str, float] = None):
+def optimize_for_efficiency(
+ query: str, benchmark_weights: Dict[str, float] = None
+):
"""Simulate efficiency-focused optimization."""
print("\n🔍 Simulating efficiency-focused optimization...")
@@ -264,7 +272,9 @@ def main():
query=query, benchmark_weights={"simpleqa": 0.6, "browsecomp": 0.4}
)
print_optimization_results(params5, score5)
- print("Efficiency metrics weighting: Quality (40%), Speed (30%), Resource (30%)")
+ print(
+ "Efficiency metrics weighting: Quality (40%), Speed (30%), Resource (30%)"
+ )
if __name__ == "__main__":
diff --git a/examples/optimization/run_gemini_benchmark.py b/examples/optimization/run_gemini_benchmark.py
index 421fcfc472..221f1145af 100755
--- a/examples/optimization/run_gemini_benchmark.py
+++ b/examples/optimization/run_gemini_benchmark.py
@@ -30,7 +30,8 @@ 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"
+ level=logging.INFO,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
@@ -46,7 +47,10 @@ def setup_gemini_config(api_key: Optional[str] = None) -> Dict[str, Any]:
Dictionary with Gemini configuration
"""
# Import database utilities
- from local_deep_research.utilities.db_utils import get_db_setting, update_db_setting
+ from local_deep_research.utilities.db_utils import (
+ get_db_setting,
+ update_db_setting,
+ )
# Check if API key exists in database
if not api_key:
@@ -133,7 +137,9 @@ def run_benchmarks(
try:
if benchmark.lower() == "simpleqa":
- logger.info(f"Running SimpleQA benchmark with {examples} examples")
+ logger.info(
+ f"Running SimpleQA benchmark with {examples} examples"
+ )
benchmark_results = evaluate_simpleqa(
num_examples=examples,
search_iterations=search_iterations,
@@ -145,7 +151,9 @@ def run_benchmarks(
output_dir=os.path.join(output_dir, "simpleqa"),
)
elif benchmark.lower() == "browsecomp":
- logger.info(f"Running BrowseComp benchmark with {examples} examples")
+ logger.info(
+ f"Running BrowseComp benchmark with {examples} examples"
+ )
benchmark_results = evaluate_browsecomp(
num_examples=examples,
search_iterations=search_iterations,
@@ -163,7 +171,9 @@ def run_benchmarks(
duration = time.time() - start_time
# Log results
- logger.info(f"{benchmark} benchmark completed in {duration:.1f} seconds")
+ logger.info(
+ f"{benchmark} benchmark completed in {duration:.1f} seconds"
+ )
if isinstance(benchmark_results, dict):
accuracy = benchmark_results.get("accuracy", "N/A")
logger.info(f"{benchmark} accuracy: {accuracy}")
@@ -195,7 +205,9 @@ def run_benchmarks(
if "error" in benchmark_results:
logger.info(f"{benchmark}: ERROR - {benchmark_results['error']}")
else:
- accuracy = benchmark_results.get("results", {}).get("accuracy", "N/A")
+ accuracy = benchmark_results.get("results", {}).get(
+ "accuracy", "N/A"
+ )
duration = benchmark_results.get("duration", 0)
logger.info(
f"{benchmark}: Accuracy = {accuracy}, Duration = {duration:.1f}s"
@@ -224,8 +236,12 @@ def run_benchmarks(
if "error" not in r
else None
),
- "duration": r.get("duration", 0) if "error" not in r else 0,
- "error": r.get("error", None) if "error" in r else None,
+ "duration": r.get("duration", 0)
+ if "error" not in r
+ else 0,
+ "error": r.get("error", None)
+ if "error" in r
+ else None,
}
for b, r in results.items()
},
@@ -252,7 +268,10 @@ def main():
# Benchmark configuration
parser.add_argument(
- "--examples", type=int, default=5, help="Number of examples for each benchmark"
+ "--examples",
+ type=int,
+ default=5,
+ help="Number of examples for each benchmark",
)
parser.add_argument(
"--benchmarks",
@@ -261,12 +280,20 @@ def main():
help="Benchmarks to run (default: both)",
)
parser.add_argument(
- "--search-iterations", type=int, default=2, help="Number of search iterations"
+ "--search-iterations",
+ type=int,
+ default=2,
+ help="Number of search iterations",
+ )
+ parser.add_argument(
+ "--questions-per-iteration",
+ type=int,
+ default=3,
+ help="Questions per iteration",
)
parser.add_argument(
- "--questions-per-iteration", type=int, default=3, help="Questions per iteration"
+ "--search-tool", default="searxng", help="Search tool to use"
)
- parser.add_argument("--search-tool", default="searxng", help="Search tool to use")
# API key
parser.add_argument(
@@ -274,7 +301,9 @@ def main():
)
# Output directory
- parser.add_argument("--output-dir", help="Directory to save results (optional)")
+ parser.add_argument(
+ "--output-dir", help="Directory to save results (optional)"
+ )
args = parser.parse_args()
diff --git a/examples/optimization/run_multi_benchmark.py b/examples/optimization/run_multi_benchmark.py
index 89a47aa651..b9e5b400e6 100755
--- a/examples/optimization/run_multi_benchmark.py
+++ b/examples/optimization/run_multi_benchmark.py
@@ -35,7 +35,9 @@ else:
# Import benchmark optimization functions
try:
- from local_deep_research.benchmarks.optimization.api import optimize_parameters
+ from local_deep_research.benchmarks.optimization.api import (
+ optimize_parameters,
+ )
print("Successfully imported optimization API")
except ImportError as e:
@@ -45,7 +47,8 @@ except ImportError as e:
# Configure logging
logging.basicConfig(
- level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+ level=logging.INFO,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
@@ -156,7 +159,10 @@ def main():
print("Benchmark evaluation complete!")
print(f"Quality score: {quality_results.get('quality_score', 0.0):.4f}")
- print("Benchmark weights used:", quality_results.get("benchmark_weights", {}))
+ print(
+ "Benchmark weights used:",
+ quality_results.get("benchmark_weights", {}),
+ )
print(
"Individual benchmark results:",
list(quality_results.get("benchmark_results", {}).keys()),
@@ -192,7 +198,9 @@ def main():
print("BrowseComp evaluation complete!")
print(f"Quality score: {bc_results.get('quality_score', 0.0):.4f}")
- print("Benchmark weights used:", bc_results.get("benchmark_weights", {}))
+ print(
+ "Benchmark weights used:", bc_results.get("benchmark_weights", {})
+ )
print(
"Individual benchmark results:",
list(bc_results.get("benchmark_results", {}).keys()),
@@ -221,7 +229,10 @@ def main():
print("Combined benchmark evaluation complete!")
print(f"Quality score: {combo_results.get('quality_score', 0.0):.4f}")
- print("Benchmark weights used:", combo_results.get("benchmark_weights", {}))
+ print(
+ "Benchmark weights used:",
+ combo_results.get("benchmark_weights", {}),
+ )
print(
"Individual benchmark results:",
list(combo_results.get("benchmark_results", {}).keys()),
@@ -235,7 +246,9 @@ def main():
print("\n🔍 Running combined benchmarks with speed optimization...")
try:
# Import the necessary function
- from local_deep_research.benchmarks.optimization.api import optimize_for_speed
+ from local_deep_research.benchmarks.optimization.api import (
+ optimize_for_speed,
+ )
print("Running speed optimization with multi-benchmark weights...")
# Very minimal run with just 1 trial for demonstration
@@ -252,7 +265,9 @@ def main():
print("Speed metrics weighting: Quality (20%), Speed (80%)")
except Exception as e:
- logger.error(f"Error running speed optimization with multi-benchmark: {e}")
+ logger.error(
+ f"Error running speed optimization with multi-benchmark: {e}"
+ )
print(f"Error: {e}")
# Run 5: Combined benchmark with efficiency optimization (balancing quality, speed and resources)
@@ -280,7 +295,9 @@ def main():
)
except Exception as e:
- logger.error(f"Error running efficiency optimization with multi-benchmark: {e}")
+ logger.error(
+ f"Error running efficiency optimization with multi-benchmark: {e}"
+ )
print(f"Error: {e}")
print("\nSkipping full optimization runs for time constraints.")
@@ -291,7 +308,9 @@ def main():
print(
" 2. Combined benchmarks with weights benchmark_weights={'simpleqa': 0.6, 'browsecomp': 0.4}"
)
- print(" 3. Speed optimization with benchmark_weights using optimize_for_speed()")
+ print(
+ " 3. Speed optimization with benchmark_weights using optimize_for_speed()"
+ )
print(
" 4. Efficiency optimization with benchmark_weights using optimize_for_efficiency()"
)
diff --git a/examples/optimization/run_optimization.py b/examples/optimization/run_optimization.py
index 142d642e02..369e624531 100644
--- a/examples/optimization/run_optimization.py
+++ b/examples/optimization/run_optimization.py
@@ -19,12 +19,6 @@ import os
import sys
from datetime import datetime
-# 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"))
-
# Import the optimization functionality
from local_deep_research.benchmarks.optimization import (
optimize_for_efficiency,
@@ -45,11 +39,14 @@ def main():
default=os.path.join("examples", "optimization", "results"),
help="Directory to save results",
)
- parser.add_argument("--search-tool", default="searxng", help="Search tool to use")
+ parser.add_argument(
+ "--search-tool", default="searxng", help="Search tool to use"
+ )
# LLM configuration options
parser.add_argument(
- "--model", help="Model name for the LLM (e.g., 'claude-3-sonnet-20240229')"
+ "--model",
+ help="Model name for the LLM (e.g., 'claude-3-sonnet-20240229')",
)
parser.add_argument(
"--provider",
@@ -68,7 +65,10 @@ def main():
)
parser.add_argument(
- "--trials", type=int, default=30, help="Number of parameter combinations to try"
+ "--trials",
+ type=int,
+ default=30,
+ help="Number of parameter combinations to try",
)
parser.add_argument(
"--mode",
diff --git a/examples/optimization/run_parallel_benchmark.py b/examples/optimization/run_parallel_benchmark.py
index 0f8a617110..c5112f328e 100755
--- a/examples/optimization/run_parallel_benchmark.py
+++ b/examples/optimization/run_parallel_benchmark.py
@@ -29,16 +29,24 @@ 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"
+ level=logging.INFO,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
def run_simpleqa_benchmark(
- num_examples, output_dir, model=None, provider=None, endpoint_url=None, api_key=None
+ num_examples,
+ output_dir,
+ model=None,
+ provider=None,
+ endpoint_url=None,
+ api_key=None,
):
"""Run SimpleQA benchmark with specified number of examples."""
- from local_deep_research.benchmarks.benchmark_functions import evaluate_simpleqa
+ from local_deep_research.benchmarks.benchmark_functions import (
+ evaluate_simpleqa,
+ )
logger.info(f"Starting SimpleQA benchmark with {num_examples} examples")
start_time = time.time()
@@ -68,10 +76,17 @@ def run_simpleqa_benchmark(
def run_browsecomp_benchmark(
- num_examples, output_dir, model=None, provider=None, endpoint_url=None, api_key=None
+ num_examples,
+ output_dir,
+ model=None,
+ provider=None,
+ endpoint_url=None,
+ api_key=None,
):
"""Run BrowseComp benchmark with specified number of examples."""
- from local_deep_research.benchmarks.benchmark_functions import evaluate_browsecomp
+ from local_deep_research.benchmarks.benchmark_functions import (
+ evaluate_browsecomp,
+ )
logger.info(f"Starting BrowseComp benchmark with {num_examples} examples")
start_time = time.time()
@@ -100,7 +115,9 @@ def run_browsecomp_benchmark(
return results
-def setup_llm_environment(model=None, provider=None, endpoint_url=None, api_key=None):
+def setup_llm_environment(
+ model=None, provider=None, endpoint_url=None, api_key=None
+):
"""Set up environment variables for LLM configuration."""
if model:
os.environ["LDR_LLM__MODEL"] = model
@@ -143,7 +160,8 @@ def main():
# LLM configuration options
parser.add_argument(
- "--model", help="Model name for the LLM (e.g., 'claude-3-sonnet-20240229')"
+ "--model",
+ help="Model name for the LLM (e.g., 'claude-3-sonnet-20240229')",
)
parser.add_argument(
"--provider",
@@ -233,7 +251,9 @@ def main():
print("SimpleQA: Failed or no results")
if browsecomp_results and isinstance(browsecomp_results, dict):
- print(f"BrowseComp accuracy: {browsecomp_results.get('accuracy', 'N/A')}")
+ print(
+ f"BrowseComp accuracy: {browsecomp_results.get('accuracy', 'N/A')}"
+ )
else:
print("BrowseComp: Failed or no results")
@@ -250,13 +270,17 @@ def main():
"total_duration": total_duration,
"simpleqa": {
"accuracy": (
- simpleqa_results.get("accuracy") if simpleqa_results else None
+ simpleqa_results.get("accuracy")
+ if simpleqa_results
+ else None
),
"completed": simpleqa_results is not None,
},
"browsecomp": {
"accuracy": (
- browsecomp_results.get("accuracy") if browsecomp_results else None
+ browsecomp_results.get("accuracy")
+ if browsecomp_results
+ else None
),
"completed": browsecomp_results is not None,
},
diff --git a/examples/optimization/strategy_benchmark_plan.py b/examples/optimization/strategy_benchmark_plan.py
index f92965be62..1f0f9c838e 100755
--- a/examples/optimization/strategy_benchmark_plan.py
+++ b/examples/optimization/strategy_benchmark_plan.py
@@ -28,11 +28,14 @@ project_root = os.path.abspath(
sys.path.insert(0, os.path.join(project_root, "src"))
# Now we can import from the local project
-from local_deep_research.benchmarks.optimization.optuna_optimizer import OptunaOptimizer
+from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ OptunaOptimizer,
+)
# Configure logging
logging.basicConfig(
- level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+ level=logging.INFO,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
@@ -190,7 +193,9 @@ def run_strategy_comparison():
# Run speed optimization
speed_start = time.time()
- best_speed_params, best_speed_score = speed_optimizer.optimize(strategy_param_space)
+ best_speed_params, best_speed_score = speed_optimizer.optimize(
+ strategy_param_space
+ )
speed_end = time.time()
speed_result = {
@@ -273,7 +278,9 @@ def run_strategy_comparison():
# Run multi-benchmark optimization
multi_start = time.time()
- best_multi_params, best_multi_score = multi_optimizer.optimize(strategy_param_space)
+ best_multi_params, best_multi_score = multi_optimizer.optimize(
+ strategy_param_space
+ )
multi_end = time.time()
multi_result = {
@@ -293,7 +300,9 @@ def run_strategy_comparison():
json.dump(multi_result, f, indent=2)
# ====== Save summary of all executions ======
- execution_stats["total_duration"] = time.time() - execution_stats["start_time"]
+ execution_stats["total_duration"] = (
+ time.time() - execution_stats["start_time"]
+ )
execution_stats["timestamp"] = timestamp
with open(os.path.join(base_output_dir, "summary.json"), "w") as f:
@@ -311,8 +320,8 @@ def generate_summary_report(base_dir, stats):
# Strategy Benchmark Results Summary
## Overview
-- **Date:** {datetime.fromtimestamp(stats['start_time']).strftime('%Y-%m-%d %H:%M:%S')}
-- **Total Duration:** {stats['total_duration'] / 3600:.2f} hours
+- **Date:** {datetime.fromtimestamp(stats["start_time"]).strftime("%Y-%m-%d %H:%M:%S")}
+- **Total Duration:** {stats["total_duration"] / 3600:.2f} hours
- **Number of Examples per Experiment:** {NUM_EXAMPLES}
## Experiment Results
@@ -320,10 +329,10 @@ def generate_summary_report(base_dir, stats):
"""
# Add detailed results for each experiment
for exp in stats["experiments"]:
- summary_text += f"""### {exp['experiment'].replace('_', ' ').title()}
-- **Best Parameters:** {json.dumps(exp['best_params'], indent=2)}
-- **Best Score:** {exp['best_score']:.4f}
-- **Duration:** {exp['duration_seconds'] / 60:.2f} minutes
+ summary_text += f"""### {exp["experiment"].replace("_", " ").title()}
+- **Best Parameters:** {json.dumps(exp["best_params"], indent=2)}
+- **Best Score:** {exp["best_score"]:.4f}
+- **Duration:** {exp["duration_seconds"] / 60:.2f} minutes
"""
@@ -337,7 +346,9 @@ def generate_summary_report(base_dir, stats):
for exp in stats["experiments"]:
best_strategy = exp["best_params"].get("search_strategy", "unknown")
other_params = {
- k: v for k, v in exp["best_params"].items() if k != "search_strategy"
+ k: v
+ for k, v in exp["best_params"].items()
+ if k != "search_strategy"
}
summary_text += f"| {exp['experiment'].replace('_', ' ').title()} | {best_strategy} | {other_params} | {exp['best_score']:.4f} |\n"
@@ -422,10 +433,14 @@ def run_strategy_simulation(num_examples=10):
except Exception as e:
logger.warning(f"Could not initialize real optimizer: {str(e)}")
- logger.warning("Falling back to pure simulation mode (no real benchmarks)")
+ logger.warning(
+ "Falling back to pure simulation mode (no real benchmarks)"
+ )
# Simulate optimization if real system is unavailable
- logger.info("Running purely simulated optimization (no real benchmarks)")
+ logger.info(
+ "Running purely simulated optimization (no real benchmarks)"
+ )
best_params, best_score = simulate_optimization(
strategy_param_space,
n_trials=5,
@@ -441,7 +456,9 @@ def run_strategy_simulation(num_examples=10):
"best_score": best_score,
}
- with open(os.path.join(sim_output_dir, "simulation_results.json"), "w") as f:
+ with open(
+ os.path.join(sim_output_dir, "simulation_results.json"), "w"
+ ) as f:
json.dump(sim_result, f, indent=2)
return sim_result
@@ -513,8 +530,12 @@ def simulate_optimization(
# More iterations generally means higher quality but lower speed
iterations = params.get("iterations", 1)
- quality_score += iterations * 0.05 # More iterations slightly improves quality
- speed_score -= iterations * 0.15 # More iterations significantly reduces speed
+ quality_score += (
+ iterations * 0.05
+ ) # More iterations slightly improves quality
+ speed_score -= (
+ iterations * 0.15
+ ) # More iterations significantly reduces speed
# Normalize scores to 0-1 range
quality_score = max(0.0, min(1.0, quality_score))
diff --git a/examples/optimization/update_llm_config.py b/examples/optimization/update_llm_config.py
index aceea76418..ddef647a4f 100755
--- a/examples/optimization/update_llm_config.py
+++ b/examples/optimization/update_llm_config.py
@@ -31,7 +31,8 @@ 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"
+ level=logging.INFO,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
@@ -111,11 +112,15 @@ def update_llm_configuration(
if provider == "openai_endpoint":
if endpoint_url:
update_db_setting("llm.openai_endpoint.url", endpoint_url)
- logger.info(f"Updated llm.openai_endpoint.url to {endpoint_url}")
+ logger.info(
+ f"Updated llm.openai_endpoint.url to {endpoint_url}"
+ )
if api_key:
update_db_setting("llm.openai_endpoint.api_key", api_key)
- logger.info("Updated llm.openai_endpoint.api_key (value hidden)")
+ logger.info(
+ "Updated llm.openai_endpoint.api_key (value hidden)"
+ )
elif provider == "openai":
if api_key:
diff --git a/examples/programmatic_access.ipynb b/examples/programmatic_access.ipynb
index e4884d31db..c7baf3ed0b 100644
--- a/examples/programmatic_access.ipynb
+++ b/examples/programmatic_access.ipynb
@@ -150,12 +150,12 @@
"# Generate a summary with custom parameters\n",
"custom_summary = quick_summary(\n",
" query=\"renewable energy trends\",\n",
- " search_tool=\"wikipedia\", # Use Wikipedia as the search engine\n",
+ " search_tool=\"wikipedia\", # Use Wikipedia as the search engine\n",
")\n",
"\n",
"print(f\"Research completed with {custom_summary['iterations']} iterations\")\n",
"print(\"Questions researched:\")\n",
- "for iteration, questions in custom_summary['questions'].items():\n",
+ "for iteration, questions in custom_summary[\"questions\"].items():\n",
" for q in questions:\n",
" print(f\"- {q}\")\n",
"\n",
@@ -427,12 +427,16 @@
],
"source": [
"# Generate a comprehensive report\n",
- "report = generate_report(\"impact of artificial intelligence on healthcare\",\n",
- " iterations=1, \n",
- " questions_per_iteration=1, \n",
+ "report = generate_report(\n",
+ " \"impact of artificial intelligence on healthcare\",\n",
+ " iterations=1,\n",
+ " questions_per_iteration=1,\n",
" searches_per_section=1,\n",
- " provider=\"openai_endpoint\", model_name=\"llama-3.3-70b-instruct\", openai_endpoint_url=\"https://api.ai.it.ufl.edu/v1/\", search_tool=\"wikipedia\"\n",
- " )\n",
+ " provider=\"openai_endpoint\",\n",
+ " model_name=\"llama-3.3-70b-instruct\",\n",
+ " openai_endpoint_url=\"https://api.ai.it.ufl.edu/v1/\",\n",
+ " search_tool=\"wikipedia\",\n",
+ ")\n",
"\n",
"# Print report metadata\n",
"print(\"Report metadata:\")\n",
@@ -536,18 +540,20 @@
"# Research with custom search settings\n",
"advanced_summary = quick_summary(\n",
" query=\"latest climate change research\",\n",
- " search_tool=\"auto\", # Auto-select best search engine\n",
- " iterations=2, # Perform 2 research cycles\n",
- " questions_per_iteration=3, # 3 questions per cycle\n",
- " max_results=50, # Consider up to 50 search results\n",
- " max_filtered_results=10, # Keep 10 most relevant results\n",
- " region=\"us\", # US region focus\n",
- " time_period=\"m\", # Focus on last month\n",
- " temperature=0.5 # Lower temperature for more focused generation\n",
+ " search_tool=\"auto\", # Auto-select best search engine\n",
+ " iterations=2, # Perform 2 research cycles\n",
+ " questions_per_iteration=3, # 3 questions per cycle\n",
+ " max_results=50, # Consider up to 50 search results\n",
+ " max_filtered_results=10, # Keep 10 most relevant results\n",
+ " region=\"us\", # US region focus\n",
+ " time_period=\"m\", # Focus on last month\n",
+ " temperature=0.5, # Lower temperature for more focused generation\n",
")\n",
"\n",
"print(f\"Research completed with {advanced_summary['iterations']} iterations\")\n",
- "print(f\"Generated {sum(len(qs) for qs in advanced_summary['questions'].values())} questions\")\n",
+ "print(\n",
+ " f\"Generated {sum(len(qs) for qs in advanced_summary['questions'].values())} questions\"\n",
+ ")\n",
"print(\"\\nSummary preview:\")\n",
"print(advanced_summary[\"summary\"][:500] + \"...\")"
]
diff --git a/examples/run_benchmark.py b/examples/run_benchmark.py
index 896ab5838b..aabc699db2 100644
--- a/examples/run_benchmark.py
+++ b/examples/run_benchmark.py
@@ -17,7 +17,8 @@ from local_deep_research.api.benchmark_functions import (
# Configure logging
logging.basicConfig(
- level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+ level=logging.INFO,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
@@ -40,12 +41,16 @@ def main():
parser.add_argument(
"--questions", type=int, default=3, help="Questions per iteration"
)
- parser.add_argument("--search-tool", default="searxng", help="Search tool to use")
+ parser.add_argument(
+ "--search-tool", default="searxng", help="Search tool to use"
+ )
parser.add_argument(
"--human-eval", action="store_true", help="Use human evaluation"
)
parser.add_argument(
- "--output-dir", default="benchmark_results", help="Directory to save results"
+ "--output-dir",
+ default="benchmark_results",
+ help="Directory to save results",
)
args = parser.parse_args()
diff --git a/kill_servers.py b/kill_servers.py
index 1e79034e7f..6faff1230c 100644
--- a/kill_servers.py
+++ b/kill_servers.py
@@ -29,7 +29,11 @@ def kill_flask_servers():
os.kill(pid, signal.SIGTERM)
killed_pids.append(pid)
- except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
+ except (
+ psutil.NoSuchProcess,
+ psutil.AccessDenied,
+ psutil.ZombieProcess,
+ ):
pass
if killed_pids:
@@ -66,7 +70,11 @@ def check_flask_servers():
):
pid = proc.info["pid"]
running_servers.append(pid)
- except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
+ except (
+ psutil.NoSuchProcess,
+ psutil.AccessDenied,
+ psutil.ZombieProcess,
+ ):
pass
return running_servers
@@ -158,7 +166,9 @@ def start_flask_server(port=5000):
f"http://localhost:{port}/", timeout=2
) as response:
if response.status == 200:
- print(f"Server is responsive at http://localhost:{port}/")
+ print(
+ f"Server is responsive at http://localhost:{port}/"
+ )
else:
print(
f"Warning: Server responded with status {response.status}"
@@ -188,7 +198,9 @@ def start_flask_server(port=5000):
def start_flask_server_windows(port=5000):
"""Start a Flask server using Windows 'start' command which is more reliable for Windows environments."""
- print(f"Starting Flask server on port {port} using Windows 'start' command...")
+ print(
+ f"Starting Flask server on port {port} using Windows 'start' command..."
+ )
# Get the virtual environment Python executable
venv_path = os.path.join(".venv", "Scripts", "python.exe")
diff --git a/pdm.lock b/pdm.lock
index 9697c440ad..88810ec5b0 100644
--- a/pdm.lock
+++ b/pdm.lock
@@ -5,7 +5,7 @@
groups = ["default", "dev"]
strategy = ["inherit_metadata"]
lock_version = "4.5.0"
-content_hash = "sha256:59113a0f41e3a79668d8038215686242a2b01966e1e09033d882e2be8b38c6a6"
+content_hash = "sha256:42a52cddece9cec9857a7c427db1e49c6a8a00129884d1d1a1f24538d10d2169"
[[metadata.targets]]
requires_python = ">=3.10"
@@ -397,42 +397,6 @@ files = [
{file = "binaryornot-0.4.4.tar.gz", hash = "sha256:359501dfc9d40632edc9fac890e19542db1a287bbcfa58175b66658392018061"},
]
-[[package]]
-name = "black"
-version = "25.1.0"
-requires_python = ">=3.9"
-summary = "The uncompromising code formatter."
-groups = ["dev"]
-dependencies = [
- "click>=8.0.0",
- "mypy-extensions>=0.4.3",
- "packaging>=22.0",
- "pathspec>=0.9.0",
- "platformdirs>=2",
- "tomli>=1.1.0; python_version < \"3.11\"",
- "typing-extensions>=4.0.1; python_version < \"3.11\"",
-]
-files = [
- {file = "black-25.1.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:759e7ec1e050a15f89b770cefbf91ebee8917aac5c20483bc2d80a6c3a04df32"},
- {file = "black-25.1.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:0e519ecf93120f34243e6b0054db49c00a35f84f195d5bce7e9f5cfc578fc2da"},
- {file = "black-25.1.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:055e59b198df7ac0b7efca5ad7ff2516bca343276c466be72eb04a3bcc1f82d7"},
- {file = "black-25.1.0-cp310-cp310-win_amd64.whl", hash = "sha256:db8ea9917d6f8fc62abd90d944920d95e73c83a5ee3383493e35d271aca872e9"},
- {file = "black-25.1.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:a39337598244de4bae26475f77dda852ea00a93bd4c728e09eacd827ec929df0"},
- {file = "black-25.1.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:96c1c7cd856bba8e20094e36e0f948718dc688dba4a9d78c3adde52b9e6c2299"},
- {file = "black-25.1.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bce2e264d59c91e52d8000d507eb20a9aca4a778731a08cfff7e5ac4a4bb7096"},
- {file = "black-25.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:172b1dbff09f86ce6f4eb8edf9dede08b1fce58ba194c87d7a4f1a5aa2f5b3c2"},
- {file = "black-25.1.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4b60580e829091e6f9238c848ea6750efed72140b91b048770b64e74fe04908b"},
- {file = "black-25.1.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1e2978f6df243b155ef5fa7e558a43037c3079093ed5d10fd84c43900f2d8ecc"},
- {file = "black-25.1.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3b48735872ec535027d979e8dcb20bf4f70b5ac75a8ea99f127c106a7d7aba9f"},
- {file = "black-25.1.0-cp312-cp312-win_amd64.whl", hash = "sha256:ea0213189960bda9cf99be5b8c8ce66bb054af5e9e861249cd23471bd7b0b3ba"},
- {file = "black-25.1.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8f0b18a02996a836cc9c9c78e5babec10930862827b1b724ddfe98ccf2f2fe4f"},
- {file = "black-25.1.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:afebb7098bfbc70037a053b91ae8437c3857482d3a690fefc03e9ff7aa9a5fd3"},
- {file = "black-25.1.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:030b9759066a4ee5e5aca28c3c77f9c64789cdd4de8ac1df642c40b708be6171"},
- {file = "black-25.1.0-cp313-cp313-win_amd64.whl", hash = "sha256:a22f402b410566e2d1c950708c77ebf5ebd5d0d88a6a2e87c86d9fb48afa0d18"},
- {file = "black-25.1.0-py3-none-any.whl", hash = "sha256:95e8176dae143ba9097f351d174fdaf0ccd29efb414b362ae3fd72bf0f710717"},
- {file = "black-25.1.0.tar.gz", hash = "sha256:33496d5cd1222ad73391352b4ae8da15253c5de89b93a80b3e2c8d9a19ec2666"},
-]
-
[[package]]
name = "bleach"
version = "6.2.0"
@@ -1241,22 +1205,6 @@ files = [
{file = "filetype-1.2.0.tar.gz", hash = "sha256:66b56cd6474bf41d8c54660347d37afcc3f7d1970648de365c102ef77548aadb"},
]
-[[package]]
-name = "flake8"
-version = "7.2.0"
-requires_python = ">=3.9"
-summary = "the modular source code checker: pep8 pyflakes and co"
-groups = ["dev"]
-dependencies = [
- "mccabe<0.8.0,>=0.7.0",
- "pycodestyle<2.14.0,>=2.13.0",
- "pyflakes<3.4.0,>=3.3.0",
-]
-files = [
- {file = "flake8-7.2.0-py2.py3-none-any.whl", hash = "sha256:93b92ba5bdb60754a6da14fa3b93a9361fd00a59632ada61fd7b130436c40343"},
- {file = "flake8-7.2.0.tar.gz", hash = "sha256:fa558ae3f6f7dbf2b4f22663e5343b6b6023620461f8d4ff2019ef4b5ee70426"},
-]
-
[[package]]
name = "flask"
version = "3.1.1"
@@ -1791,17 +1739,6 @@ files = [
{file = "isoduration-20.11.0.tar.gz", hash = "sha256:ac2f9015137935279eac671f94f89eb00584f940f5dc49462a0c4ee692ba1bd9"},
]
-[[package]]
-name = "isort"
-version = "6.0.1"
-requires_python = ">=3.9.0"
-summary = "A Python utility / library to sort Python imports."
-groups = ["dev"]
-files = [
- {file = "isort-6.0.1-py3-none-any.whl", hash = "sha256:2dc5d7f65c9678d94c88dfc29161a320eec67328bc97aad576874cb4be1e9615"},
- {file = "isort-6.0.1.tar.gz", hash = "sha256:1cb5df28dfbc742e490c5e41bad6da41b805b0a8be7bc93cd0fb2a8a890ac450"},
-]
-
[[package]]
name = "itsdangerous"
version = "2.2.0"
@@ -2895,17 +2832,6 @@ files = [
{file = "matplotlib_inline-0.1.7.tar.gz", hash = "sha256:8423b23ec666be3d16e16b60bdd8ac4e86e840ebd1dd11a30b9f117f2fa0ab90"},
]
-[[package]]
-name = "mccabe"
-version = "0.7.0"
-requires_python = ">=3.6"
-summary = "McCabe checker, plugin for flake8"
-groups = ["dev"]
-files = [
- {file = "mccabe-0.7.0-py2.py3-none-any.whl", hash = "sha256:6c2d30ab6be0e4a46919781807b4f0d834ebdd6c6e3dca0bda5a15f863427b6e"},
- {file = "mccabe-0.7.0.tar.gz", hash = "sha256:348e0240c33b60bbdf4e523192ef919f28cb2c3d7d5c7794f74009290f236325"},
-]
-
[[package]]
name = "mdurl"
version = "0.1.2"
@@ -3058,7 +2984,7 @@ name = "mypy-extensions"
version = "1.1.0"
requires_python = ">=3.8"
summary = "Type system extensions for programs checked with the mypy type checker."
-groups = ["default", "dev"]
+groups = ["default"]
files = [
{file = "mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505"},
{file = "mypy_extensions-1.1.0.tar.gz", hash = "sha256:52e68efc3284861e772bbcd66823fde5ae21fd2fdb51c62a211403730b916558"},
@@ -3518,17 +3444,6 @@ files = [
{file = "parso-0.8.4.tar.gz", hash = "sha256:eb3a7b58240fb99099a345571deecc0f9540ea5f4dd2fe14c2a99d6b281ab92d"},
]
-[[package]]
-name = "pathspec"
-version = "0.12.1"
-requires_python = ">=3.8"
-summary = "Utility library for gitignore style pattern matching of file paths."
-groups = ["dev"]
-files = [
- {file = "pathspec-0.12.1-py3-none-any.whl", hash = "sha256:a0d503e138a4c123b27490a4f7beda6a01c6f288df0e4a8b79c7eb0dc7b4cc08"},
- {file = "pathspec-0.12.1.tar.gz", hash = "sha256:a482d51503a1ab33b1c67a6c3813a26953dbdc71c31dacaef9a838c4e29f5712"},
-]
-
[[package]]
name = "pdfminer-six"
version = "20250327"
@@ -3901,17 +3816,6 @@ files = [
{file = "pure_eval-0.2.3.tar.gz", hash = "sha256:5f4e983f40564c576c7c8635ae88db5956bb2229d7e9237d03b3c0b0190eaf42"},
]
-[[package]]
-name = "pycodestyle"
-version = "2.13.0"
-requires_python = ">=3.9"
-summary = "Python style guide checker"
-groups = ["dev"]
-files = [
- {file = "pycodestyle-2.13.0-py2.py3-none-any.whl", hash = "sha256:35863c5974a271c7a726ed228a14a4f6daf49df369d8c50cd9a6f58a5e143ba9"},
- {file = "pycodestyle-2.13.0.tar.gz", hash = "sha256:c8415bf09abe81d9c7f872502a6eee881fbe85d8763dd5b9924bb0a01d67efae"},
-]
-
[[package]]
name = "pycparser"
version = "2.22"
@@ -4059,17 +3963,6 @@ files = [
{file = "pyee-13.0.0.tar.gz", hash = "sha256:b391e3c5a434d1f5118a25615001dbc8f669cf410ab67d04c4d4e07c55481c37"},
]
-[[package]]
-name = "pyflakes"
-version = "3.3.2"
-requires_python = ">=3.9"
-summary = "passive checker of Python programs"
-groups = ["dev"]
-files = [
- {file = "pyflakes-3.3.2-py2.py3-none-any.whl", hash = "sha256:5039c8339cbb1944045f4ee5466908906180f13cc99cc9949348d10f82a5c32a"},
- {file = "pyflakes-3.3.2.tar.gz", hash = "sha256:6dfd61d87b97fba5dcfaaf781171ac16be16453be6d816147989e7f6e6a9576b"},
-]
-
[[package]]
name = "pygments"
version = "2.19.1"
@@ -4176,6 +4069,20 @@ files = [
{file = "pytest_mock-3.14.1.tar.gz", hash = "sha256:159e9edac4c451ce77a5cdb9fc5d1100708d2dd4ba3c3df572f14097351af80e"},
]
+[[package]]
+name = "pytest-timeout"
+version = "2.4.0"
+requires_python = ">=3.7"
+summary = "pytest plugin to abort hanging tests"
+groups = ["dev"]
+dependencies = [
+ "pytest>=7.0.0",
+]
+files = [
+ {file = "pytest_timeout-2.4.0-py3-none-any.whl", hash = "sha256:c42667e5cdadb151aeb5b26d114aff6bdf5a907f176a007a30b940d3d865b5c2"},
+ {file = "pytest_timeout-2.4.0.tar.gz", hash = "sha256:7e68e90b01f9eff71332b25001f85c75495fc4e3a836701876183c4bcfd0540a"},
+]
+
[[package]]
name = "python-dateutil"
version = "2.9.0.post0"
@@ -4806,6 +4713,33 @@ files = [
{file = "rpds_py-0.25.1.tar.gz", hash = "sha256:8960b6dac09b62dac26e75d7e2c4a22efb835d827a7278c34f72b2b84fa160e3"},
]
+[[package]]
+name = "ruff"
+version = "0.11.12"
+requires_python = ">=3.7"
+summary = "An extremely fast Python linter and code formatter, written in Rust."
+groups = ["dev"]
+files = [
+ {file = "ruff-0.11.12-py3-none-linux_armv6l.whl", hash = "sha256:c7680aa2f0d4c4f43353d1e72123955c7a2159b8646cd43402de6d4a3a25d7cc"},
+ {file = "ruff-0.11.12-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:2cad64843da9f134565c20bcc430642de897b8ea02e2e79e6e02a76b8dcad7c3"},
+ {file = "ruff-0.11.12-py3-none-macosx_11_0_arm64.whl", hash = "sha256:9b6886b524a1c659cee1758140138455d3c029783d1b9e643f3624a5ee0cb0aa"},
+ {file = "ruff-0.11.12-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3cc3a3690aad6e86c1958d3ec3c38c4594b6ecec75c1f531e84160bd827b2012"},
+ {file = "ruff-0.11.12-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f97fdbc2549f456c65b3b0048560d44ddd540db1f27c778a938371424b49fe4a"},
+ {file = "ruff-0.11.12-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:74adf84960236961090e2d1348c1a67d940fd12e811a33fb3d107df61eef8fc7"},
+ {file = "ruff-0.11.12-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:b56697e5b8bcf1d61293ccfe63873aba08fdbcbbba839fc046ec5926bdb25a3a"},
+ {file = "ruff-0.11.12-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4d47afa45e7b0eaf5e5969c6b39cbd108be83910b5c74626247e366fd7a36a13"},
+ {file = "ruff-0.11.12-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:692bf9603fe1bf949de8b09a2da896f05c01ed7a187f4a386cdba6760e7f61be"},
+ {file = "ruff-0.11.12-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:08033320e979df3b20dba567c62f69c45e01df708b0f9c83912d7abd3e0801cd"},
+ {file = "ruff-0.11.12-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:929b7706584f5bfd61d67d5070f399057d07c70585fa8c4491d78ada452d3bef"},
+ {file = "ruff-0.11.12-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:7de4a73205dc5756b8e09ee3ed67c38312dce1aa28972b93150f5751199981b5"},
+ {file = "ruff-0.11.12-py3-none-musllinux_1_2_i686.whl", hash = "sha256:2635c2a90ac1b8ca9e93b70af59dfd1dd2026a40e2d6eebaa3efb0465dd9cf02"},
+ {file = "ruff-0.11.12-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:d05d6a78a89166f03f03a198ecc9d18779076ad0eec476819467acb401028c0c"},
+ {file = "ruff-0.11.12-py3-none-win32.whl", hash = "sha256:f5a07f49767c4be4772d161bfc049c1f242db0cfe1bd976e0f0886732a4765d6"},
+ {file = "ruff-0.11.12-py3-none-win_amd64.whl", hash = "sha256:5a4d9f8030d8c3a45df201d7fb3ed38d0219bccd7955268e863ee4a115fa0832"},
+ {file = "ruff-0.11.12-py3-none-win_arm64.whl", hash = "sha256:65194e37853158d368e333ba282217941029a28ea90913c67e558c611d04daa5"},
+ {file = "ruff-0.11.12.tar.gz", hash = "sha256:43cf7f69c7d7c7d7513b9d59c5d8cafd704e05944f978614aa9faff6ac202603"},
+]
+
[[package]]
name = "safetensors"
version = "0.5.3"
diff --git a/pyproject.toml b/pyproject.toml
index 4a03be8b3b..618b3fd5f8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -83,6 +83,7 @@ include-package-data = true
"local_deep_research.defaults" = ["*.toml", "*.py", "*.template", ".env.template"]
+
[tool.pdm]
distribution = true
version = { source = "file", path = "src/local_deep_research/__version__.py" }
@@ -93,10 +94,7 @@ include_packages = ["torch", "torch*"]
[dependency-groups]
dev = [
- "isort>=6.0.1",
- "black>=25.1.0",
"pre-commit>=4.2.0",
- "flake8>=7.1.2",
"jupyter>=1.1.1",
"cookiecutter>=2.6.0",
"pandas>=2.2.3",
@@ -105,6 +103,7 @@ dev = [
"pytest>=8.3.5",
"pytest-cov>=6.1.1",
"pytest-timeout>=2.3.1",
+ "ruff>=0.11.12",
]
[tool.pytest.ini_options]
@@ -113,3 +112,60 @@ markers = [
"integration: marks integration tests",
"slow: marks slow tests",
]
+
+[tool.ruff]
+# Exclude a variety of commonly ignored directories.
+exclude = [
+ ".bzr",
+ ".direnv",
+ ".eggs",
+ ".git",
+ ".git-rewrite",
+ ".hg",
+ ".ipynb_checkpoints",
+ ".mypy_cache",
+ ".nox",
+ ".pants.d",
+ ".pyenv",
+ ".pytest_cache",
+ ".pytype",
+ ".ruff_cache",
+ ".svn",
+ ".tox",
+ ".venv",
+ ".vscode",
+ "__pypackages__",
+ "_build",
+ "buck-out",
+ "build",
+ "dist",
+ "node_modules",
+ "site-packages",
+ "venv",
+]
+
+# Same as Black.
+line-length = 80
+indent-width = 4
+
+[tool.ruff.lint]
+# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default.
+select = ["E4", "E7", "E9", "F"]
+ignore = ["E722"]
+
+# Allow fix for all enabled rules (when `--fix`) is provided.
+fixable = ["ALL"]
+unfixable = []
+
+# Allow unused variables when underscore-prefixed.
+dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
+
+[tool.ruff.format]
+# Like Black, use double quotes for strings.
+quote-style = "double"
+# Like Black, indent with spaces, rather than tabs.
+indent-style = "space"
+# Like Black, respect magic trailing commas.
+skip-magic-trailing-comma = false
+# Like Black, automatically detect the appropriate line ending.
+line-ending = "auto"
diff --git a/src/local_deep_research/__init__.py b/src/local_deep_research/__init__.py
index 37099ecf07..782d266271 100644
--- a/src/local_deep_research/__init__.py
+++ b/src/local_deep_research/__init__.py
@@ -37,4 +37,6 @@ __all__ = [
"get_search",
"get_report_generator",
"get_advanced_search_system",
+ "main",
+ "__version__",
]
diff --git a/src/local_deep_research/advanced_search_system/answer_decoding/browsecomp_answer_decoder.py b/src/local_deep_research/advanced_search_system/answer_decoding/browsecomp_answer_decoder.py
index d88526cad1..176a541548 100644
--- a/src/local_deep_research/advanced_search_system/answer_decoding/browsecomp_answer_decoder.py
+++ b/src/local_deep_research/advanced_search_system/answer_decoding/browsecomp_answer_decoder.py
@@ -67,7 +67,9 @@ class BrowseCompAnswerDecoder:
logger.debug(f"Answer appears to be plaintext: {clean_answer}")
return clean_answer, None
- logger.info(f"Attempting to decode potentially encoded answer: {clean_answer}")
+ logger.info(
+ f"Attempting to decode potentially encoded answer: {clean_answer}"
+ )
# Try each encoding scheme
for scheme in self.encoding_schemes:
@@ -84,7 +86,9 @@ class BrowseCompAnswerDecoder:
continue
# No successful decoding
- logger.warning(f"Could not decode answer, returning original: {clean_answer}")
+ logger.warning(
+ f"Could not decode answer, returning original: {clean_answer}"
+ )
return clean_answer, None
def is_likely_direct_answer(self, answer: str) -> bool:
@@ -149,7 +153,9 @@ class BrowseCompAnswerDecoder:
return True
# Check character distribution - encoded text often has unusual distribution
- char_diversity = len(set(answer)) / len(answer) if len(answer) > 0 else 0
+ char_diversity = (
+ len(set(answer)) / len(answer) if len(answer) > 0 else 0
+ )
if char_diversity < 0.3: # Low diversity suggests repetitive/encoded
return False
@@ -305,7 +311,18 @@ class BrowseCompAnswerDecoder:
base_score = letter_score / letter_count
# Bonus for common English words
- common_words = ["the", "and", "of", "to", "a", "in", "is", "it", "you", "that"]
+ common_words = [
+ "the",
+ "and",
+ "of",
+ "to",
+ "a",
+ "in",
+ "is",
+ "it",
+ "you",
+ "that",
+ ]
word_bonus = sum(1 for word in common_words if word in text_lower)
return min(1.0, base_score + word_bonus * 0.1)
@@ -344,7 +361,9 @@ class BrowseCompAnswerDecoder:
"alpha": sum(1 for c in decoded if c.isalpha()),
"digit": sum(1 for c in decoded if c.isdigit()),
"space": sum(1 for c in decoded if c.isspace()),
- "punct": sum(1 for c in decoded if not c.isalnum() and not c.isspace()),
+ "punct": sum(
+ 1 for c in decoded if not c.isalnum() and not c.isspace()
+ ),
}
total_chars = len(decoded)
@@ -377,14 +396,19 @@ class BrowseCompAnswerDecoder:
for i, pattern in enumerate(self.encoded_patterns):
if re.search(pattern, answer):
analysis["pattern_matches"].append(
- {"pattern": pattern, "type": ["base64", "hex", "url", "random"][i]}
+ {
+ "pattern": pattern,
+ "type": ["base64", "hex", "url", "random"][i],
+ }
)
# Try each decoding scheme
for scheme in self.encoding_schemes:
try:
decoded = self.apply_decoding_scheme(answer, scheme)
- is_valid = self.validate_decoded_answer(decoded) if decoded else False
+ is_valid = (
+ self.validate_decoded_answer(decoded) if decoded else False
+ )
analysis["attempted_decodings"][scheme] = {
"decoded": decoded,
diff --git a/src/local_deep_research/advanced_search_system/candidate_exploration/adaptive_explorer.py b/src/local_deep_research/advanced_search_system/candidate_exploration/adaptive_explorer.py
index 511245e867..9d1790766c 100644
--- a/src/local_deep_research/advanced_search_system/candidate_exploration/adaptive_explorer.py
+++ b/src/local_deep_research/advanced_search_system/candidate_exploration/adaptive_explorer.py
@@ -7,13 +7,17 @@ approaches and the quality of candidates found.
import time
from collections import defaultdict
-from typing import Dict, List, Optional, Tuple
+from typing import List, Optional
from loguru import logger
from ..candidates.base_candidate import Candidate
from ..constraints.base_constraint import Constraint
-from .base_explorer import BaseCandidateExplorer, ExplorationResult, ExplorationStrategy
+from .base_explorer import (
+ BaseCandidateExplorer,
+ ExplorationResult,
+ ExplorationStrategy,
+)
class AdaptiveExplorer(BaseCandidateExplorer):
@@ -75,7 +79,9 @@ class AdaptiveExplorer(BaseCandidateExplorer):
# Track current strategy performance
search_count = 0
- while self._should_continue_exploration(start_time, len(all_candidates)):
+ while self._should_continue_exploration(
+ start_time, len(all_candidates)
+ ):
# Choose strategy based on current performance
strategy = self._choose_strategy(search_count)
@@ -91,9 +97,13 @@ class AdaptiveExplorer(BaseCandidateExplorer):
continue
# Execute search
- logger.info(f"Using strategy '{strategy}' for query: {query[:50]}...")
+ logger.info(
+ f"Using strategy '{strategy}' for query: {query[:50]}..."
+ )
results = self._execute_search(query)
- candidates = self._extract_candidates_from_results(results, entity_type)
+ candidates = self._extract_candidates_from_results(
+ results, entity_type
+ )
# Track strategy performance
self._update_strategy_stats(strategy, candidates)
@@ -198,7 +208,9 @@ class AdaptiveExplorer(BaseCandidateExplorer):
elif strategy == "synonym_expansion":
return self._synonym_expansion_query(base_query)
elif strategy == "category_exploration":
- return self._category_exploration_query(base_query, found_candidates)
+ return self._category_exploration_query(
+ base_query, found_candidates
+ )
elif strategy == "related_terms":
return self._related_terms_query(base_query, found_candidates)
elif strategy == "constraint_focused" and constraints:
@@ -207,7 +219,9 @@ class AdaptiveExplorer(BaseCandidateExplorer):
return self._direct_search_query(base_query)
except Exception as e:
- logger.error(f"Error generating query with strategy {strategy}: {e}")
+ logger.error(
+ f"Error generating query with strategy {strategy}: {e}"
+ )
return None
def _direct_search_query(self, base_query: str) -> str:
@@ -278,7 +292,9 @@ Related search term:
constraint = constraints[0] # Simple selection
return f"{base_query} {constraint.value}"
- def _update_strategy_stats(self, strategy: str, candidates: List[Candidate]):
+ def _update_strategy_stats(
+ self, strategy: str, candidates: List[Candidate]
+ ):
"""Update performance statistics for a strategy."""
self.strategy_stats[strategy]["attempts"] += 1
self.strategy_stats[strategy]["candidates_found"] += len(candidates)
diff --git a/src/local_deep_research/advanced_search_system/candidate_exploration/base_explorer.py b/src/local_deep_research/advanced_search_system/candidate_exploration/base_explorer.py
index a425ee575a..e57c3ae872 100644
--- a/src/local_deep_research/advanced_search_system/candidate_exploration/base_explorer.py
+++ b/src/local_deep_research/advanced_search_system/candidate_exploration/base_explorer.py
@@ -128,12 +128,16 @@ class BaseCandidateExplorer(ABC):
if isinstance(results, list):
# If results is a list, wrap it in the expected format
formatted_results = {"results": results, "query": query}
- logger.info(f"Search '{query[:50]}...' returned {len(results)} results")
+ logger.info(
+ f"Search '{query[:50]}...' returned {len(results)} results"
+ )
return formatted_results
elif isinstance(results, dict):
# If results is already a dict, use it as is
result_count = len(results.get("results", []))
- logger.info(f"Search '{query[:50]}...' returned {result_count} results")
+ logger.info(
+ f"Search '{query[:50]}...' returned {result_count} results"
+ )
return results
else:
# Unknown format, return empty
@@ -166,7 +170,8 @@ class BaseCandidateExplorer(ABC):
# Generate answer candidates using LLM
answer_candidates = self._generate_answer_candidates(
- original_query, "\n\n".join(all_content[:10]) # Limit to first 10 results
+ original_query,
+ "\n\n".join(all_content[:10]), # Limit to first 10 results
)
for answer in answer_candidates:
@@ -281,7 +286,9 @@ Names:
return True
- def _deduplicate_candidates(self, candidates: List[Candidate]) -> List[Candidate]:
+ def _deduplicate_candidates(
+ self, candidates: List[Candidate]
+ ) -> List[Candidate]:
"""Remove duplicate candidates based on name similarity."""
unique_candidates = []
seen_names = set()
@@ -310,13 +317,17 @@ Names:
if "query" in candidate.metadata:
# Simple word overlap scoring
query_words = set(query.lower().split())
- candidate_query_words = set(candidate.metadata["query"].lower().split())
+ candidate_query_words = set(
+ candidate.metadata["query"].lower().split()
+ )
overlap = len(query_words.intersection(candidate_query_words))
score += overlap * 0.1
# Score based on result title relevance
if "result_title" in candidate.metadata:
- title_words = set(candidate.metadata["result_title"].lower().split())
+ title_words = set(
+ candidate.metadata["result_title"].lower().split()
+ )
overlap = len(query_words.intersection(title_words))
score += overlap * 0.2
@@ -324,5 +335,7 @@ Names:
# Sort by relevance
return sorted(
- candidates, key=lambda c: getattr(c, "relevance_score", 0.0), reverse=True
+ candidates,
+ key=lambda c: getattr(c, "relevance_score", 0.0),
+ reverse=True,
)
diff --git a/src/local_deep_research/advanced_search_system/candidate_exploration/constraint_guided_explorer.py b/src/local_deep_research/advanced_search_system/candidate_exploration/constraint_guided_explorer.py
index 254455f767..f18cdfb75e 100644
--- a/src/local_deep_research/advanced_search_system/candidate_exploration/constraint_guided_explorer.py
+++ b/src/local_deep_research/advanced_search_system/candidate_exploration/constraint_guided_explorer.py
@@ -6,13 +6,17 @@ searches that are likely to find candidates satisfying the constraints.
"""
import time
-from typing import Dict, List, Optional
+from typing import List, Optional
from loguru import logger
from ..candidates.base_candidate import Candidate
from ..constraints.base_constraint import Constraint, ConstraintType
-from .base_explorer import BaseCandidateExplorer, ExplorationResult, ExplorationStrategy
+from .base_explorer import (
+ BaseCandidateExplorer,
+ ExplorationResult,
+ ExplorationStrategy,
+)
class ConstraintGuidedExplorer(BaseCandidateExplorer):
@@ -52,11 +56,17 @@ class ConstraintGuidedExplorer(BaseCandidateExplorer):
) -> ExplorationResult:
"""Explore candidates using constraint-guided strategy."""
start_time = time.time()
- logger.info(f"Starting constraint-guided exploration for: {initial_query}")
+ logger.info(
+ f"Starting constraint-guided exploration for: {initial_query}"
+ )
if not constraints:
- logger.warning("No constraints provided - falling back to basic search")
- return self._basic_exploration(initial_query, entity_type, start_time)
+ logger.warning(
+ "No constraints provided - falling back to basic search"
+ )
+ return self._basic_exploration(
+ initial_query, entity_type, start_time
+ )
all_candidates = []
exploration_paths = []
@@ -67,11 +77,13 @@ class ConstraintGuidedExplorer(BaseCandidateExplorer):
# Search for each constraint
for i, constraint in enumerate(prioritized_constraints):
- if not self._should_continue_exploration(start_time, len(all_candidates)):
+ if not self._should_continue_exploration(
+ start_time, len(all_candidates)
+ ):
break
logger.info(
- f"Exploring constraint {i+1}/{len(prioritized_constraints)}: {constraint.value}"
+ f"Exploring constraint {i + 1}/{len(prioritized_constraints)}: {constraint.value}"
)
# Generate constraint-specific queries
@@ -86,7 +98,9 @@ class ConstraintGuidedExplorer(BaseCandidateExplorer):
continue
results = self._execute_search(query)
- candidates = self._extract_candidates_from_results(results, entity_type)
+ candidates = self._extract_candidates_from_results(
+ results, entity_type
+ )
# Early validation if enabled
if self.early_validation:
@@ -197,7 +211,10 @@ class ConstraintGuidedExplorer(BaseCandidateExplorer):
)
def _generate_constraint_queries(
- self, constraint: Constraint, base_query: str, entity_type: Optional[str] = None
+ self,
+ constraint: Constraint,
+ base_query: str,
+ entity_type: Optional[str] = None,
) -> List[str]:
"""Generate search queries specific to a constraint."""
queries = []
@@ -214,16 +231,25 @@ class ConstraintGuidedExplorer(BaseCandidateExplorer):
self._name_pattern_queries(constraint, base_query, entity_type)
)
elif constraint.type == ConstraintType.PROPERTY:
- queries.extend(self._property_queries(constraint, base_query, entity_type))
+ queries.extend(
+ self._property_queries(constraint, base_query, entity_type)
+ )
elif constraint.type == ConstraintType.EVENT:
- queries.extend(self._event_queries(constraint, base_query, entity_type))
+ queries.extend(
+ self._event_queries(constraint, base_query, entity_type)
+ )
elif constraint.type == ConstraintType.LOCATION:
- queries.extend(self._location_queries(constraint, base_query, entity_type))
+ queries.extend(
+ self._location_queries(constraint, base_query, entity_type)
+ )
return queries
def _name_pattern_queries(
- self, constraint: Constraint, base_query: str, entity_type: Optional[str]
+ self,
+ constraint: Constraint,
+ base_query: str,
+ entity_type: Optional[str],
) -> List[str]:
"""Generate queries for name pattern constraints."""
queries = []
@@ -250,7 +276,10 @@ class ConstraintGuidedExplorer(BaseCandidateExplorer):
return queries
def _property_queries(
- self, constraint: Constraint, base_query: str, entity_type: Optional[str]
+ self,
+ constraint: Constraint,
+ base_query: str,
+ entity_type: Optional[str],
) -> List[str]:
"""Generate queries for property constraints."""
base = entity_type or base_query
@@ -261,7 +290,10 @@ class ConstraintGuidedExplorer(BaseCandidateExplorer):
]
def _event_queries(
- self, constraint: Constraint, base_query: str, entity_type: Optional[str]
+ self,
+ constraint: Constraint,
+ base_query: str,
+ entity_type: Optional[str],
) -> List[str]:
"""Generate queries for event constraints."""
base = entity_type or base_query
@@ -272,7 +304,10 @@ class ConstraintGuidedExplorer(BaseCandidateExplorer):
]
def _location_queries(
- self, constraint: Constraint, base_query: str, entity_type: Optional[str]
+ self,
+ constraint: Constraint,
+ base_query: str,
+ entity_type: Optional[str],
) -> List[str]:
"""Generate queries for location constraints."""
return [
@@ -282,16 +317,24 @@ class ConstraintGuidedExplorer(BaseCandidateExplorer):
]
def _cross_constraint_exploration(
- self, constraints: List[Constraint], base_query: str, entity_type: Optional[str]
+ self,
+ constraints: List[Constraint],
+ base_query: str,
+ entity_type: Optional[str],
) -> List[Candidate]:
"""Explore candidates satisfying multiple constraints."""
if len(constraints) < 2:
return []
# Combine top 2 constraints
- combined_query = self._combine_constraints_query(base_query, constraints)
+ combined_query = self._combine_constraints_query(
+ base_query, constraints
+ )
- if combined_query and combined_query.lower() not in self.explored_queries:
+ if (
+ combined_query
+ and combined_query.lower() not in self.explored_queries
+ ):
results = self._execute_search(combined_query)
return self._extract_candidates_from_results(results, entity_type)
@@ -305,7 +348,7 @@ class ConstraintGuidedExplorer(BaseCandidateExplorer):
return None
constraint_values = [c.value for c in constraints[:2]]
- return f'{base_query} {" AND ".join(constraint_values)}'
+ return f"{base_query} {' AND '.join(constraint_values)}"
def _early_validate_candidates(
self, candidates: List[Candidate], constraint: Constraint
diff --git a/src/local_deep_research/advanced_search_system/candidate_exploration/diversity_explorer.py b/src/local_deep_research/advanced_search_system/candidate_exploration/diversity_explorer.py
index cb53519f0d..6b70645536 100644
--- a/src/local_deep_research/advanced_search_system/candidate_exploration/diversity_explorer.py
+++ b/src/local_deep_research/advanced_search_system/candidate_exploration/diversity_explorer.py
@@ -7,13 +7,17 @@ categories, types, and characteristics.
import time
from collections import defaultdict
-from typing import Dict, List, Optional, Set
+from typing import List, Optional
from loguru import logger
from ..candidates.base_candidate import Candidate
from ..constraints.base_constraint import Constraint
-from .base_explorer import BaseCandidateExplorer, ExplorationResult, ExplorationStrategy
+from .base_explorer import (
+ BaseCandidateExplorer,
+ ExplorationResult,
+ ExplorationStrategy,
+)
class DiversityExplorer(BaseCandidateExplorer):
@@ -60,7 +64,9 @@ class DiversityExplorer(BaseCandidateExplorer):
) -> ExplorationResult:
"""Explore candidates using diversity-focused strategy."""
start_time = time.time()
- logger.info(f"Starting diversity-focused exploration for: {initial_query}")
+ logger.info(
+ f"Starting diversity-focused exploration for: {initial_query}"
+ )
all_candidates = []
exploration_paths = []
@@ -81,7 +87,9 @@ class DiversityExplorer(BaseCandidateExplorer):
self._categorize_candidates(initial_candidates)
# Generate diverse exploration paths
- while self._should_continue_exploration(start_time, len(all_candidates)):
+ while self._should_continue_exploration(
+ start_time, len(all_candidates)
+ ):
# Calculate current diversity
diversity_score = self._calculate_diversity_score(all_candidates)
@@ -93,7 +101,9 @@ class DiversityExplorer(BaseCandidateExplorer):
break
# Find underrepresented categories
- underrepresented_categories = self._find_underrepresented_categories()
+ underrepresented_categories = (
+ self._find_underrepresented_categories()
+ )
if not underrepresented_categories:
# Generate new category exploration
@@ -115,7 +125,9 @@ class DiversityExplorer(BaseCandidateExplorer):
continue
results = self._execute_search(query)
- candidates = self._extract_candidates_from_results(results, entity_type)
+ candidates = self._extract_candidates_from_results(
+ results, entity_type
+ )
# Filter for diversity
diverse_candidates = self._filter_for_diversity(
@@ -139,7 +151,9 @@ class DiversityExplorer(BaseCandidateExplorer):
# Final diversity filtering and ranking
diverse_candidates = self._final_diversity_selection(all_candidates)
- ranked_candidates = self._rank_by_diversity(diverse_candidates, initial_query)
+ ranked_candidates = self._rank_by_diversity(
+ diverse_candidates, initial_query
+ )
final_candidates = ranked_candidates[: self.max_candidates]
elapsed_time = time.time() - start_time
@@ -193,17 +207,26 @@ class DiversityExplorer(BaseCandidateExplorer):
# Simple categorization based on common patterns
if any(word in name for word in ["mountain", "peak", "summit", "hill"]):
return "mountain"
- elif any(word in name for word in ["lake", "river", "creek", "stream", "pond"]):
+ elif any(
+ word in name
+ for word in ["lake", "river", "creek", "stream", "pond"]
+ ):
return "water"
- elif any(word in name for word in ["park", "forest", "reserve", "wilderness"]):
+ elif any(
+ word in name for word in ["park", "forest", "reserve", "wilderness"]
+ ):
return "park"
elif any(word in name for word in ["trail", "path", "route", "way"]):
return "trail"
elif any(word in name for word in ["canyon", "gorge", "valley", "gap"]):
return "canyon"
- elif any(word in name for word in ["cliff", "bluff", "overlook", "viewpoint"]):
+ elif any(
+ word in name for word in ["cliff", "bluff", "overlook", "viewpoint"]
+ ):
return "viewpoint"
- elif any(word in name for word in ["island", "beach", "coast", "shore"]):
+ elif any(
+ word in name for word in ["island", "beach", "coast", "shore"]
+ ):
return "coastal"
elif any(word in name for word in ["city", "town", "county", "state"]):
return "place"
@@ -232,7 +255,9 @@ class DiversityExplorer(BaseCandidateExplorer):
# Normalize to 0-1 scale
max_entropy = (
- (len(category_counts).bit_length() - 1) if len(category_counts) > 1 else 1
+ (len(category_counts).bit_length() - 1)
+ if len(category_counts) > 1
+ else 1
)
return entropy / max_entropy if max_entropy > 0 else 0.0
@@ -241,7 +266,9 @@ class DiversityExplorer(BaseCandidateExplorer):
if not self.category_counts:
return []
- avg_count = sum(self.category_counts.values()) / len(self.category_counts)
+ avg_count = sum(self.category_counts.values()) / len(
+ self.category_counts
+ )
threshold = avg_count * 0.5 # Categories with less than 50% of average
underrepresented = [
@@ -264,8 +291,13 @@ class DiversityExplorer(BaseCandidateExplorer):
# Analyze existing categories
existing_categories = set()
for candidate in found_candidates:
- if candidate.metadata and "diversity_category" in candidate.metadata:
- existing_categories.add(candidate.metadata["diversity_category"])
+ if (
+ candidate.metadata
+ and "diversity_category" in candidate.metadata
+ ):
+ existing_categories.add(
+ candidate.metadata["diversity_category"]
+ )
# Generate queries for missing categories
all_categories = [
@@ -318,7 +350,9 @@ class DiversityExplorer(BaseCandidateExplorer):
return queries
def _filter_for_diversity(
- self, new_candidates: List[Candidate], existing_candidates: List[Candidate]
+ self,
+ new_candidates: List[Candidate],
+ existing_candidates: List[Candidate],
) -> List[Candidate]:
"""Filter new candidates to maintain diversity."""
filtered = []
@@ -331,7 +365,9 @@ class DiversityExplorer(BaseCandidateExplorer):
continue
# Check for similarity with existing candidates
- if not self._is_sufficiently_different(candidate, existing_candidates):
+ if not self._is_sufficiently_different(
+ candidate, existing_candidates
+ ):
continue
filtered.append(candidate)
@@ -344,7 +380,9 @@ class DiversityExplorer(BaseCandidateExplorer):
"""Check if candidate is sufficiently different from existing ones."""
candidate_words = set(candidate.name.lower().split())
- for existing in existing_candidates[-10:]: # Check against recent candidates
+ for existing in existing_candidates[
+ -10:
+ ]: # Check against recent candidates
existing_words = set(existing.name.lower().split())
# Calculate Jaccard similarity
@@ -378,7 +416,9 @@ class DiversityExplorer(BaseCandidateExplorer):
for category, group in category_groups.items():
# Sort by relevance score if available
sorted_group = sorted(
- group, key=lambda c: getattr(c, "relevance_score", 0.0), reverse=True
+ group,
+ key=lambda c: getattr(c, "relevance_score", 0.0),
+ reverse=True,
)
selected.extend(sorted_group[:max_per_category])
@@ -389,7 +429,9 @@ class DiversityExplorer(BaseCandidateExplorer):
) -> List[Candidate]:
"""Rank candidates considering both relevance and diversity contribution."""
# First rank by relevance
- relevance_ranked = self._rank_candidates_by_relevance(candidates, base_query)
+ relevance_ranked = self._rank_candidates_by_relevance(
+ candidates, base_query
+ )
# Then adjust based on diversity contribution
for i, candidate in enumerate(relevance_ranked):
@@ -409,5 +451,7 @@ class DiversityExplorer(BaseCandidateExplorer):
candidate.final_score = relevance_score + (diversity_boost * 0.2)
return sorted(
- relevance_ranked, key=lambda c: getattr(c, "final_score", 0.0), reverse=True
+ relevance_ranked,
+ key=lambda c: getattr(c, "final_score", 0.0),
+ reverse=True,
)
diff --git a/src/local_deep_research/advanced_search_system/candidate_exploration/parallel_explorer.py b/src/local_deep_research/advanced_search_system/candidate_exploration/parallel_explorer.py
index 462152832e..bd63bb643b 100644
--- a/src/local_deep_research/advanced_search_system/candidate_exploration/parallel_explorer.py
+++ b/src/local_deep_research/advanced_search_system/candidate_exploration/parallel_explorer.py
@@ -7,13 +7,17 @@ a wide range of candidates.
import concurrent.futures
import time
-from typing import Dict, List, Optional
+from typing import List, Optional
from loguru import logger
from ..candidates.base_candidate import Candidate
from ..constraints.base_constraint import Constraint
-from .base_explorer import BaseCandidateExplorer, ExplorationResult, ExplorationStrategy
+from .base_explorer import (
+ BaseCandidateExplorer,
+ ExplorationResult,
+ ExplorationStrategy,
+)
class ParallelExplorer(BaseCandidateExplorer):
@@ -174,7 +178,9 @@ class ParallelExplorer(BaseCandidateExplorer):
queries.extend(constraint_queries)
# Remove already explored queries
- new_queries = [q for q in queries if q.lower() not in self.explored_queries]
+ new_queries = [
+ q for q in queries if q.lower() not in self.explored_queries
+ ]
return new_queries[: self.queries_per_round]
diff --git a/src/local_deep_research/advanced_search_system/candidate_exploration/progressive_explorer.py b/src/local_deep_research/advanced_search_system/candidate_exploration/progressive_explorer.py
index 4365cb3b9d..0907ab40ff 100644
--- a/src/local_deep_research/advanced_search_system/candidate_exploration/progressive_explorer.py
+++ b/src/local_deep_research/advanced_search_system/candidate_exploration/progressive_explorer.py
@@ -18,7 +18,9 @@ class SearchProgress:
found_candidates: Dict[str, float] = field(
default_factory=dict
) # name -> confidence
- verified_facts: Dict[str, str] = field(default_factory=dict) # fact -> source
+ verified_facts: Dict[str, str] = field(
+ default_factory=dict
+ ) # fact -> source
entity_coverage: Dict[str, Set[str]] = field(
default_factory=dict
) # entity_type -> searched_entities
@@ -37,7 +39,9 @@ class SearchProgress:
uncovered = {}
for entity_type, entity_list in entities.items():
covered = self.entity_coverage.get(entity_type, set())
- uncovered_list = [e for e in entity_list if e.lower() not in covered]
+ uncovered_list = [
+ e for e in entity_list if e.lower() not in covered
+ ]
if uncovered_list:
uncovered[entity_type] = uncovered_list
return uncovered
@@ -91,7 +95,8 @@ class ProgressiveExplorer:
if candidate_name in self.progress.found_candidates:
# Update confidence if higher
self.progress.found_candidates[candidate_name] = max(
- self.progress.found_candidates[candidate_name], confidence
+ self.progress.found_candidates[candidate_name],
+ confidence,
)
else:
self.progress.found_candidates[candidate_name] = confidence
@@ -105,16 +110,19 @@ class ProgressiveExplorer:
return all_results, self.progress
def generate_verification_searches(
- self, candidates: Dict[str, float], constraints: List, max_searches: int = 5
+ self,
+ candidates: Dict[str, float],
+ constraints: List,
+ max_searches: int = 5,
) -> List[str]:
"""Generate targeted searches to verify top candidates."""
if not candidates:
return []
# Get top candidates by confidence
- top_candidates = sorted(candidates.items(), key=lambda x: x[1], reverse=True)[
- :3
- ]
+ top_candidates = sorted(
+ candidates.items(), key=lambda x: x[1], reverse=True
+ )[:3]
verification_searches = []
for candidate_name, confidence in top_candidates:
@@ -146,7 +154,9 @@ class ProgressiveExplorer:
quoted_terms = re.findall(r'"([^"]+)"', combined_text)
for term in quoted_terms:
- if len(term) > 2 and len(term) < 50: # Reasonable length for an answer
+ if (
+ len(term) > 2 and len(term) < 50
+ ): # Reasonable length for an answer
candidates[term] = 0.3 # Base confidence from appearance
# Boost confidence if appears in title
@@ -163,7 +173,9 @@ class ProgressiveExplorer:
return candidates
- def _update_entity_coverage(self, query: str, entities: Dict[str, List[str]]):
+ def _update_entity_coverage(
+ self, query: str, entities: Dict[str, List[str]]
+ ):
"""Track which entities have been covered in searches."""
query_lower = query.lower()
@@ -233,7 +245,9 @@ class ProgressiveExplorer:
return (query, [])
# Run searches in parallel
- with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
+ with concurrent.futures.ThreadPoolExecutor(
+ max_workers=max_workers
+ ) as executor:
futures = [executor.submit(search_query, q) for q in queries]
for future in concurrent.futures.as_completed(futures):
results.append(future.result())
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/__init__.py b/src/local_deep_research/advanced_search_system/constraint_checking/__init__.py
index 5f814f5f07..5ee75dcea1 100644
--- a/src/local_deep_research/advanced_search_system/constraint_checking/__init__.py
+++ b/src/local_deep_research/advanced_search_system/constraint_checking/__init__.py
@@ -5,7 +5,10 @@ This module provides inheritance-based components for checking candidates
against constraints, with different implementations available.
"""
-from .base_constraint_checker import BaseConstraintChecker, ConstraintCheckResult
+from .base_constraint_checker import (
+ BaseConstraintChecker,
+ ConstraintCheckResult,
+)
# Legacy imports for backward compatibility
from .constraint_checker import ConstraintChecker
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/base_constraint_checker.py b/src/local_deep_research/advanced_search_system/constraint_checking/base_constraint_checker.py
index 5247da91f5..edfc0a32d7 100644
--- a/src/local_deep_research/advanced_search_system/constraint_checking/base_constraint_checker.py
+++ b/src/local_deep_research/advanced_search_system/constraint_checking/base_constraint_checker.py
@@ -93,16 +93,22 @@ class BaseConstraintChecker(ABC):
if self.evidence_gatherer:
return self.evidence_gatherer(candidate, constraint)
else:
- logger.warning("No evidence gatherer provided - cannot gather evidence")
+ logger.warning(
+ "No evidence gatherer provided - cannot gather evidence"
+ )
return []
def _log_constraint_result(
- self, candidate: Candidate, constraint: Constraint, score: float, details: Dict
+ self,
+ candidate: Candidate,
+ constraint: Constraint,
+ score: float,
+ details: Dict,
):
"""Log constraint evaluation result."""
symbol = "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
logger.info(
- f"{symbol} {candidate.name} | {constraint.value}: {int(score*100)}%"
+ f"{symbol} {candidate.name} | {constraint.value}: {int(score * 100)}%"
)
def _calculate_weighted_score(
@@ -111,4 +117,6 @@ class BaseConstraintChecker(ABC):
"""Calculate weighted average score."""
if not constraint_scores or not weights:
return 0.0
- return sum(s * w for s, w in zip(constraint_scores, weights)) / sum(weights)
+ return sum(s * w for s, w in zip(constraint_scores, weights)) / sum(
+ weights
+ )
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/constraint_checker.py b/src/local_deep_research/advanced_search_system/constraint_checking/constraint_checker.py
index 2d5c9ba4fa..03bb511bc1 100644
--- a/src/local_deep_research/advanced_search_system/constraint_checking/constraint_checker.py
+++ b/src/local_deep_research/advanced_search_system/constraint_checking/constraint_checker.py
@@ -5,14 +5,14 @@ This module provides the primary interface for checking candidates against const
"""
from dataclasses import dataclass
-from typing import Dict, List, Optional, Tuple
+from typing import Dict, List, Optional
from langchain_core.language_models import BaseChatModel
from loguru import logger
from ..candidates.base_candidate import Candidate
from ..constraints.base_constraint import Constraint
-from .evidence_analyzer import ConstraintEvidence, EvidenceAnalyzer
+from .evidence_analyzer import EvidenceAnalyzer
from .rejection_engine import RejectionEngine, RejectionResult
@@ -63,7 +63,9 @@ class ConstraintChecker:
# Initialize components
self.evidence_analyzer = EvidenceAnalyzer(model)
- self.rejection_engine = RejectionEngine(negative_threshold, positive_threshold)
+ self.rejection_engine = RejectionEngine(
+ negative_threshold, positive_threshold
+ )
# Scoring parameters
self.uncertainty_penalty = uncertainty_penalty
@@ -91,7 +93,9 @@ class ConstraintChecker:
for constraint in constraints:
# Gather evidence for this constraint
- evidence_list = self._gather_evidence_for_constraint(candidate, constraint)
+ evidence_list = self._gather_evidence_for_constraint(
+ candidate, constraint
+ )
if evidence_list:
# Analyze evidence with dual confidence
@@ -105,15 +109,15 @@ class ConstraintChecker:
constraint_results[constraint] = dual_evidence
# Calculate average scores for this constraint
- avg_positive = sum(e.positive_confidence for e in dual_evidence) / len(
- dual_evidence
- )
- avg_negative = sum(e.negative_confidence for e in dual_evidence) / len(
- dual_evidence
- )
- avg_uncertainty = sum(e.uncertainty for e in dual_evidence) / len(
- dual_evidence
- )
+ avg_positive = sum(
+ e.positive_confidence for e in dual_evidence
+ ) / len(dual_evidence)
+ avg_negative = sum(
+ e.negative_confidence for e in dual_evidence
+ ) / len(dual_evidence)
+ avg_uncertainty = sum(
+ e.uncertainty for e in dual_evidence
+ ) / len(dual_evidence)
# Calculate constraint score
score = self.evidence_analyzer.evaluate_evidence_list(
@@ -147,8 +151,8 @@ class ConstraintChecker:
# Log result
symbol = "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
logger.info(
- f"{symbol} {candidate.name} | {constraint.value}: {int(score*100)}% "
- f"(+{int(avg_positive*100)}% -{int(avg_negative*100)}% ?{int(avg_uncertainty*100)}%)"
+ f"{symbol} {candidate.name} | {constraint.value}: {int(score * 100)}% "
+ f"(+{int(avg_positive * 100)}% -{int(avg_negative * 100)}% ?{int(avg_uncertainty * 100)}%)"
)
else:
@@ -192,7 +196,9 @@ class ConstraintChecker:
if detailed_results:
weights = [r["weight"] for r in detailed_results]
scores = [r["score"] for r in detailed_results]
- total_score = sum(s * w for s, w in zip(scores, weights)) / sum(weights)
+ total_score = sum(s * w for s, w in zip(scores, weights)) / sum(
+ weights
+ )
logger.info(f"Final score for {candidate.name}: {total_score:.2%}")
@@ -211,5 +217,7 @@ class ConstraintChecker:
if self.evidence_gatherer:
return self.evidence_gatherer(candidate, constraint)
else:
- logger.warning("No evidence gatherer provided - cannot gather evidence")
+ logger.warning(
+ "No evidence gatherer provided - cannot gather evidence"
+ )
return []
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/constraint_satisfaction_tracker.py b/src/local_deep_research/advanced_search_system/constraint_checking/constraint_satisfaction_tracker.py
index d32e78b758..a9c5b53909 100644
--- a/src/local_deep_research/advanced_search_system/constraint_checking/constraint_satisfaction_tracker.py
+++ b/src/local_deep_research/advanced_search_system/constraint_checking/constraint_satisfaction_tracker.py
@@ -89,7 +89,9 @@ class ConstraintSatisfactionTracker:
satisfaction = self.verify_single_constraint(candidate, constraint)
# Store detailed results
- scores[constraint.id if hasattr(constraint, "id") else str(constraint)] = {
+ scores[
+ constraint.id if hasattr(constraint, "id") else str(constraint)
+ ] = {
"satisfaction": satisfaction,
"weight": weight,
"difficulty": difficulty,
@@ -104,7 +106,8 @@ class ConstraintSatisfactionTracker:
if total_weight > 0:
weighted_score = (
sum(
- score["satisfaction"] * score["weight"] for score in scores.values()
+ score["satisfaction"] * score["weight"]
+ for score in scores.values()
)
/ total_weight
)
@@ -117,7 +120,9 @@ class ConstraintSatisfactionTracker:
)
# Determine if candidate should be accepted
- should_accept = reliability_adjusted_score >= self.satisfaction_threshold
+ should_accept = (
+ reliability_adjusted_score >= self.satisfaction_threshold
+ )
return ConstraintVerificationResult(
total_score=reliability_adjusted_score,
@@ -179,7 +184,9 @@ class ConstraintSatisfactionTracker:
# EASY: Simple property checks
return "EASY"
- def calculate_constraint_weight(self, constraint: object, difficulty: str) -> float:
+ def calculate_constraint_weight(
+ self, constraint: object, difficulty: str
+ ) -> float:
"""
Calculate the weight for a constraint based on type and difficulty.
@@ -207,7 +214,9 @@ class ConstraintSatisfactionTracker:
return final_weight
- def verify_single_constraint(self, candidate: object, constraint: object) -> float:
+ def verify_single_constraint(
+ self, candidate: object, constraint: object
+ ) -> float:
"""
Verify a single constraint against a candidate.
@@ -239,24 +248,34 @@ class ConstraintSatisfactionTracker:
# Try to infer from constraint text
constraint_text = str(constraint).lower()
- if any(word in constraint_text for word in ["name", "called", "known as"]):
+ if any(
+ word in constraint_text
+ for word in ["name", "called", "known as"]
+ ):
return "NAME_PATTERN"
elif any(
- word in constraint_text for word in ["location", "country", "city"]
+ word in constraint_text
+ for word in ["location", "country", "city"]
):
return "LOCATION"
elif any(
- word in constraint_text for word in ["year", "date", "when", "time"]
+ word in constraint_text
+ for word in ["year", "date", "when", "time"]
):
return "TEMPORAL"
- elif any(word in constraint_text for word in ["number", "count", "amount"]):
+ elif any(
+ word in constraint_text
+ for word in ["number", "count", "amount"]
+ ):
return "STATISTIC"
elif any(
- word in constraint_text for word in ["event", "happened", "occurred"]
+ word in constraint_text
+ for word in ["event", "happened", "occurred"]
):
return "EVENT"
elif any(
- word in constraint_text for word in ["than", "more", "less", "compared"]
+ word in constraint_text
+ for word in ["than", "more", "less", "compared"]
):
return "COMPARISON"
else:
@@ -277,7 +296,12 @@ class ConstraintSatisfactionTracker:
low_reliability_count = 0
low_reliability_satisfied = 0
- high_reliability_types = {"NAME_PATTERN", "LOCATION", "EVENT", "TEMPORAL"}
+ high_reliability_types = {
+ "NAME_PATTERN",
+ "LOCATION",
+ "EVENT",
+ "TEMPORAL",
+ }
low_reliability_types = {"COMPARISON", "STATISTIC"}
for constraint_id, score_data in constraint_scores.items():
@@ -298,12 +322,16 @@ class ConstraintSatisfactionTracker:
# Bonus for satisfying high-reliability constraints
if high_reliability_count > 0:
- high_reliability_ratio = high_reliability_satisfied / high_reliability_count
+ high_reliability_ratio = (
+ high_reliability_satisfied / high_reliability_count
+ )
reliability_adjustment += high_reliability_ratio * 0.1
# Small penalty if only low-reliability constraints are satisfied
if low_reliability_count > 0 and high_reliability_satisfied == 0:
- low_reliability_ratio = low_reliability_satisfied / low_reliability_count
+ low_reliability_ratio = (
+ low_reliability_satisfied / low_reliability_count
+ )
if low_reliability_ratio > 0.7: # Many low-reliability matches
reliability_adjustment -= 0.05
@@ -345,7 +373,8 @@ class ConstraintSatisfactionTracker:
# Sort constraints by relaxation priority (lowest first)
relaxable_constraints = sorted(
- constraints, key=lambda c: priorities.get(self._get_constraint_type(c), 5)
+ constraints,
+ key=lambda c: priorities.get(self._get_constraint_type(c), 5),
)
# Generate progressive relaxation sets
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/dual_confidence_checker.py b/src/local_deep_research/advanced_search_system/constraint_checking/dual_confidence_checker.py
index 4269e158d7..7de0faf36c 100644
--- a/src/local_deep_research/advanced_search_system/constraint_checking/dual_confidence_checker.py
+++ b/src/local_deep_research/advanced_search_system/constraint_checking/dual_confidence_checker.py
@@ -11,7 +11,10 @@ from loguru import logger
from ..candidates.base_candidate import Candidate
from ..constraints.base_constraint import Constraint
-from .base_constraint_checker import BaseConstraintChecker, ConstraintCheckResult
+from .base_constraint_checker import (
+ BaseConstraintChecker,
+ ConstraintCheckResult,
+)
from .evidence_analyzer import ConstraintEvidence, EvidenceAnalyzer
@@ -90,7 +93,9 @@ class DualConfidenceChecker(BaseConstraintChecker):
for constraint in constraints:
# Perform initial evaluation with re-evaluation for uncertain constraints
- result = self._evaluate_constraint_with_reevaluation(candidate, constraint)
+ result = self._evaluate_constraint_with_reevaluation(
+ candidate, constraint
+ )
avg_positive = result["positive"]
avg_negative = result["negative"]
@@ -172,7 +177,9 @@ class DualConfidenceChecker(BaseConstraintChecker):
while reevaluation_count <= self.max_reevaluations:
# Gather evidence (fresh each time for re-evaluation)
- evidence_list = self._gather_evidence_for_constraint(candidate, constraint)
+ evidence_list = self._gather_evidence_for_constraint(
+ candidate, constraint
+ )
if not evidence_list:
# No evidence found
@@ -187,17 +194,19 @@ class DualConfidenceChecker(BaseConstraintChecker):
# Analyze with dual confidence
dual_evidence = [
- self.evidence_analyzer.analyze_evidence_dual_confidence(e, constraint)
+ self.evidence_analyzer.analyze_evidence_dual_confidence(
+ e, constraint
+ )
for e in evidence_list
]
# Calculate averages
- avg_positive = sum(e.positive_confidence for e in dual_evidence) / len(
- dual_evidence
- )
- avg_negative = sum(e.negative_confidence for e in dual_evidence) / len(
- dual_evidence
- )
+ avg_positive = sum(
+ e.positive_confidence for e in dual_evidence
+ ) / len(dual_evidence)
+ avg_negative = sum(
+ e.negative_confidence for e in dual_evidence
+ ) / len(dual_evidence)
avg_uncertainty = sum(e.uncertainty for e in dual_evidence) / len(
dual_evidence
)
@@ -216,7 +225,6 @@ class DualConfidenceChecker(BaseConstraintChecker):
and avg_uncertainty > self.uncertainty_threshold
and not self._should_early_reject(avg_positive, avg_negative)
):
-
reevaluation_count += 1
logger.info(
f"🔄 Re-evaluating {candidate.name} | {constraint.value} "
@@ -250,7 +258,9 @@ class DualConfidenceChecker(BaseConstraintChecker):
"reevaluation_count": reevaluation_count,
}
- def _should_early_reject(self, avg_positive: float, avg_negative: float) -> bool:
+ def _should_early_reject(
+ self, avg_positive: float, avg_negative: float
+ ) -> bool:
"""Check if candidate should be rejected early (before re-evaluation)."""
return (
avg_negative > self.negative_threshold
@@ -325,14 +335,18 @@ class DualConfidenceChecker(BaseConstraintChecker):
symbol = "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
# Add re-evaluation indicator
- reeval_indicator = f" [R{reevaluation_count}]" if reevaluation_count > 0 else ""
+ reeval_indicator = (
+ f" [R{reevaluation_count}]" if reevaluation_count > 0 else ""
+ )
logger.info(
f"{symbol} {candidate.name} | {constraint.value}: {int(score * 100)}% "
f"(+{int(positive * 100)}% -{int(negative * 100)}% ?{int(uncertainty * 100)}%){reeval_indicator}"
)
- def _llm_prescreen_candidate(self, candidate, constraints, original_query=None):
+ def _llm_prescreen_candidate(
+ self, candidate, constraints, original_query=None
+ ):
"""Simple quality check for answer candidates."""
if not original_query:
@@ -385,7 +399,8 @@ Just give the number:"""
"detailed_results": [
{
"constraint": "answer_quality",
- "negative_confidence": (100 - quality_score) / 100.0,
+ "negative_confidence": (100 - quality_score)
+ / 100.0,
"source": "answer_quality_check",
}
],
@@ -399,5 +414,11 @@ Just give the number:"""
}
except Exception as e:
- logger.warning(f"Fast LLM pre-screening failed for {candidate.name}: {e}")
- return {"should_reject": False, "reason": "", "detailed_results": []}
+ logger.warning(
+ f"Fast LLM pre-screening failed for {candidate.name}: {e}"
+ )
+ return {
+ "should_reject": False,
+ "reason": "",
+ "detailed_results": [],
+ }
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/evidence_analyzer.py b/src/local_deep_research/advanced_search_system/constraint_checking/evidence_analyzer.py
index 861e52cfc9..1813530b8d 100644
--- a/src/local_deep_research/advanced_search_system/constraint_checking/evidence_analyzer.py
+++ b/src/local_deep_research/advanced_search_system/constraint_checking/evidence_analyzer.py
@@ -20,7 +20,9 @@ class ConstraintEvidence:
"""Evidence for a constraint with dual confidence scores."""
positive_confidence: float # How sure we are the constraint IS satisfied
- negative_confidence: float # How sure we are the constraint is NOT satisfied
+ negative_confidence: (
+ float # How sure we are the constraint is NOT satisfied
+ )
uncertainty: float # How uncertain we are (neither positive nor negative)
evidence_text: str
source: str
@@ -142,7 +144,9 @@ UNCERTAINTY: [score]
# Convert evidence to dual confidence format
constraint_evidence = []
for evidence in evidence_list:
- dual_evidence = self.analyze_evidence_dual_confidence(evidence, constraint)
+ dual_evidence = self.analyze_evidence_dual_confidence(
+ evidence, constraint
+ )
constraint_evidence.append(dual_evidence)
# Calculate overall score
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/intelligent_constraint_relaxer.py b/src/local_deep_research/advanced_search_system/constraint_checking/intelligent_constraint_relaxer.py
index bf938de3bd..5e0b1a7bb9 100644
--- a/src/local_deep_research/advanced_search_system/constraint_checking/intelligent_constraint_relaxer.py
+++ b/src/local_deep_research/advanced_search_system/constraint_checking/intelligent_constraint_relaxer.py
@@ -105,7 +105,8 @@ class IntelligentConstraintRelaxer:
high_priority_constraints = [
c
for c in constraints
- if self.constraint_priorities.get(self._get_constraint_type(c), 5) >= 7
+ if self.constraint_priorities.get(self._get_constraint_type(c), 5)
+ >= 7
]
if len(high_priority_constraints) >= self.min_constraints:
@@ -125,7 +126,9 @@ class IntelligentConstraintRelaxer:
seen_sets.add(set_signature)
unique_sets.append(constraint_set)
- logger.info(f"Generated {len(unique_sets)} unique relaxation strategies")
+ logger.info(
+ f"Generated {len(unique_sets)} unique relaxation strategies"
+ )
return unique_sets
def _create_constraint_variations(
@@ -147,7 +150,9 @@ class IntelligentConstraintRelaxer:
if constraint_type in self.relaxation_strategies:
# Create variations for this constraint
- variations = self.relaxation_strategies[constraint_type](constraint)
+ variations = self.relaxation_strategies[constraint_type](
+ constraint
+ )
if variations:
# Replace original constraint with each variation
@@ -190,7 +195,9 @@ class IntelligentConstraintRelaxer:
)
variations.append(
- self._create_relaxed_constraint(constraint, relaxed_text)
+ self._create_relaxed_constraint(
+ constraint, relaxed_text
+ )
)
# Create "approximately" version
@@ -234,13 +241,20 @@ class IntelligentConstraintRelaxer:
for strict_term, relaxed_term in relaxation_mappings.items():
if strict_term in constraint_text:
- relaxed_text = constraint_text.replace(strict_term, relaxed_term)
+ relaxed_text = constraint_text.replace(
+ strict_term, relaxed_term
+ )
variations.append(
self._create_relaxed_constraint(constraint, relaxed_text)
)
# Remove comparison altogether - focus on the main entity/property
- comparison_indicators = ["more than", "less than", "compared to", "relative to"]
+ comparison_indicators = [
+ "more than",
+ "less than",
+ "compared to",
+ "relative to",
+ ]
for indicator in comparison_indicators:
if indicator in constraint_text:
# Extract the part before the comparison
@@ -276,12 +290,15 @@ class IntelligentConstraintRelaxer:
# Create decade ranges
decade_start = (year // 10) * 10
decade_text = constraint_text.replace(year_str, f"{decade_start}s")
- variations.append(self._create_relaxed_constraint(constraint, decade_text))
+ variations.append(
+ self._create_relaxed_constraint(constraint, decade_text)
+ )
# Create +/- ranges
for range_years in [1, 2, 5]:
range_text = constraint_text.replace(
- year_str, f"between {year - range_years} and {year + range_years}"
+ year_str,
+ f"between {year - range_years} and {year + range_years}",
)
variations.append(
self._create_relaxed_constraint(constraint, range_text)
@@ -395,31 +412,43 @@ class IntelligentConstraintRelaxer:
# Try to infer from constraint text
constraint_text = str(constraint).lower()
- if any(word in constraint_text for word in ["name", "called", "known as"]):
+ if any(
+ word in constraint_text
+ for word in ["name", "called", "known as"]
+ ):
return "NAME_PATTERN"
elif any(
- word in constraint_text for word in ["location", "country", "city"]
+ word in constraint_text
+ for word in ["location", "country", "city"]
):
return "LOCATION"
elif any(
- word in constraint_text for word in ["year", "date", "when", "time"]
+ word in constraint_text
+ for word in ["year", "date", "when", "time"]
):
return "TEMPORAL"
- elif any(word in constraint_text for word in ["number", "count", "amount"]):
+ elif any(
+ word in constraint_text
+ for word in ["number", "count", "amount"]
+ ):
return "STATISTIC"
elif any(
- word in constraint_text for word in ["event", "happened", "occurred"]
+ word in constraint_text
+ for word in ["event", "happened", "occurred"]
):
return "EVENT"
elif any(
- word in constraint_text for word in ["than", "more", "less", "compared"]
+ word in constraint_text
+ for word in ["than", "more", "less", "compared"]
):
return "COMPARISON"
else:
return "PROPERTY"
def analyze_relaxation_impact(
- self, original_constraints: List[object], relaxed_constraints: List[object]
+ self,
+ original_constraints: List[object],
+ relaxed_constraints: List[object],
) -> Dict:
"""
Analyze the impact of constraint relaxation.
@@ -429,15 +458,20 @@ class IntelligentConstraintRelaxer:
analysis = {
"original_count": len(original_constraints),
"relaxed_count": len(relaxed_constraints),
- "constraints_removed": len(original_constraints) - len(relaxed_constraints),
+ "constraints_removed": len(original_constraints)
+ - len(relaxed_constraints),
"constraint_changes": [],
"priority_impact": "low",
"recommendation": "",
}
# Check what types of constraints were removed/modified
- original_types = [self._get_constraint_type(c) for c in original_constraints]
- relaxed_types = [self._get_constraint_type(c) for c in relaxed_constraints]
+ original_types = [
+ self._get_constraint_type(c) for c in original_constraints
+ ]
+ relaxed_types = [
+ self._get_constraint_type(c) for c in relaxed_constraints
+ ]
removed_types = []
for orig_type in original_types:
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/rejection_engine.py b/src/local_deep_research/advanced_search_system/constraint_checking/rejection_engine.py
index f5ae7ac7d3..96958cd5dc 100644
--- a/src/local_deep_research/advanced_search_system/constraint_checking/rejection_engine.py
+++ b/src/local_deep_research/advanced_search_system/constraint_checking/rejection_engine.py
@@ -5,7 +5,7 @@ This module provides logic for rejecting candidates based on constraint violatio
"""
from dataclasses import dataclass
-from typing import Dict, List, Optional, Tuple
+from typing import Dict, List, Optional
from loguru import logger
@@ -128,7 +128,9 @@ class RejectionEngine:
RejectionResult if should reject, None if should accept
"""
for constraint, evidence_list in constraint_results.items():
- result = self.should_reject_candidate(candidate, constraint, evidence_list)
+ result = self.should_reject_candidate(
+ candidate, constraint, evidence_list
+ )
if result.should_reject:
logger.info(
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/strict_checker.py b/src/local_deep_research/advanced_search_system/constraint_checking/strict_checker.py
index f8c5ba1f12..a7bcff4d0b 100644
--- a/src/local_deep_research/advanced_search_system/constraint_checking/strict_checker.py
+++ b/src/local_deep_research/advanced_search_system/constraint_checking/strict_checker.py
@@ -5,13 +5,16 @@ This implementation is very strict about constraint satisfaction,
requiring high confidence for all constraints.
"""
-from typing import Dict, List, Optional, Tuple
+from typing import Dict, List, Tuple
from loguru import logger
from ..candidates.base_candidate import Candidate
from ..constraints.base_constraint import Constraint, ConstraintType
-from .base_constraint_checker import BaseConstraintChecker, ConstraintCheckResult
+from .base_constraint_checker import (
+ BaseConstraintChecker,
+ ConstraintCheckResult,
+)
class StrictChecker(BaseConstraintChecker):
@@ -53,7 +56,9 @@ class StrictChecker(BaseConstraintChecker):
for constraint in constraints:
# Gather evidence
- evidence_list = self._gather_evidence_for_constraint(candidate, constraint)
+ evidence_list = self._gather_evidence_for_constraint(
+ candidate, constraint
+ )
# Calculate score
score = self._evaluate_constraint_strictly(
@@ -110,13 +115,18 @@ class StrictChecker(BaseConstraintChecker):
)
def should_reject_candidate(
- self, candidate: Candidate, constraint: Constraint, evidence_data: List[Dict]
+ self,
+ candidate: Candidate,
+ constraint: Constraint,
+ evidence_data: List[Dict],
) -> Tuple[bool, str]:
"""Strict rejection rules."""
if not evidence_data:
return True, f"No evidence for constraint '{constraint.value}'"
- score = self._evaluate_constraint_strictly(candidate, constraint, evidence_data)
+ score = self._evaluate_constraint_strictly(
+ candidate, constraint, evidence_data
+ )
# Special handling for NAME_PATTERN constraints
if (
@@ -139,7 +149,10 @@ class StrictChecker(BaseConstraintChecker):
return False, ""
def _evaluate_constraint_strictly(
- self, candidate: Candidate, constraint: Constraint, evidence_list: List[Dict]
+ self,
+ candidate: Candidate,
+ constraint: Constraint,
+ evidence_list: List[Dict],
) -> float:
"""Evaluate constraint with strict criteria."""
if not evidence_list:
@@ -147,7 +160,9 @@ class StrictChecker(BaseConstraintChecker):
# For NAME_PATTERN constraints, use direct name checking
if constraint.type == ConstraintType.NAME_PATTERN:
- return self._check_name_pattern_strictly(candidate.name, constraint.value)
+ return self._check_name_pattern_strictly(
+ candidate.name, constraint.value
+ )
# For other constraints, use LLM with strict prompt
combined_evidence = "\n".join(
@@ -214,7 +229,9 @@ Score (0.0-1.0):
name_lower = candidate_name.lower()
for part in body_parts:
if part in name_lower.split() or part in name_lower:
- logger.info(f"✓ Found body part '{part}' in '{candidate_name}'")
+ logger.info(
+ f"✓ Found body part '{part}' in '{candidate_name}'"
+ )
return 1.0
logger.info(f"✗ No body part found in '{candidate_name}'")
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/threshold_checker.py b/src/local_deep_research/advanced_search_system/constraint_checking/threshold_checker.py
index 8b5ba21787..59fc7290b4 100644
--- a/src/local_deep_research/advanced_search_system/constraint_checking/threshold_checker.py
+++ b/src/local_deep_research/advanced_search_system/constraint_checking/threshold_checker.py
@@ -5,13 +5,16 @@ This implementation uses simple yes/no threshold checking for constraints,
making it faster but less nuanced than dual confidence checking.
"""
-from typing import Dict, List, Optional, Tuple
+from typing import Dict, List, Tuple
from loguru import logger
from ..candidates.base_candidate import Candidate
from ..constraints.base_constraint import Constraint
-from .base_constraint_checker import BaseConstraintChecker, ConstraintCheckResult
+from .base_constraint_checker import (
+ BaseConstraintChecker,
+ ConstraintCheckResult,
+)
class ThresholdChecker(BaseConstraintChecker):
@@ -55,7 +58,9 @@ class ThresholdChecker(BaseConstraintChecker):
for constraint in constraints:
# Gather evidence
- evidence_list = self._gather_evidence_for_constraint(candidate, constraint)
+ evidence_list = self._gather_evidence_for_constraint(
+ candidate, constraint
+ )
if evidence_list:
# Simple satisfaction check
@@ -141,11 +146,17 @@ class ThresholdChecker(BaseConstraintChecker):
)
def should_reject_candidate(
- self, candidate: Candidate, constraint: Constraint, evidence_data: List[Dict]
+ self,
+ candidate: Candidate,
+ constraint: Constraint,
+ evidence_data: List[Dict],
) -> Tuple[bool, str]:
"""Simple rejection based on evidence availability and quality."""
if not evidence_data:
- return True, f"No evidence found for constraint '{constraint.value}'"
+ return (
+ True,
+ f"No evidence found for constraint '{constraint.value}'",
+ )
satisfaction_score = self._check_constraint_satisfaction(
candidate, constraint, evidence_data
@@ -160,7 +171,10 @@ class ThresholdChecker(BaseConstraintChecker):
return False, ""
def _check_constraint_satisfaction(
- self, candidate: Candidate, constraint: Constraint, evidence_list: List[Dict]
+ self,
+ candidate: Candidate,
+ constraint: Constraint,
+ evidence_list: List[Dict],
) -> float:
"""Check if constraint is satisfied using simple LLM prompt."""
# Combine evidence texts
diff --git a/src/local_deep_research/advanced_search_system/constraints/constraint_analyzer.py b/src/local_deep_research/advanced_search_system/constraints/constraint_analyzer.py
index 665219cabf..507f61491f 100644
--- a/src/local_deep_research/advanced_search_system/constraints/constraint_analyzer.py
+++ b/src/local_deep_research/advanced_search_system/constraints/constraint_analyzer.py
@@ -68,11 +68,14 @@ Focus on answer verification, not query parsing.
if line.startswith("CONSTRAINT_"):
if current_constraint and all(
- k in current_constraint for k in ["type", "description", "value"]
+ k in current_constraint
+ for k in ["type", "description", "value"]
):
constraint = Constraint(
id=f"c{constraint_id}",
- type=self._parse_constraint_type(current_constraint["type"]),
+ type=self._parse_constraint_type(
+ current_constraint["type"]
+ ),
description=current_constraint["description"],
value=current_constraint["value"],
weight=self._parse_weight(
@@ -98,7 +101,9 @@ Focus on answer verification, not query parsing.
type=self._parse_constraint_type(current_constraint["type"]),
description=current_constraint["description"],
value=current_constraint["value"],
- weight=self._parse_weight(current_constraint.get("weight", 1.0)),
+ weight=self._parse_weight(
+ current_constraint.get("weight", 1.0)
+ ),
)
constraints.append(constraint)
diff --git a/src/local_deep_research/advanced_search_system/evidence/__init__.py b/src/local_deep_research/advanced_search_system/evidence/__init__.py
index 3ddd909a7a..faf8baaf4b 100644
--- a/src/local_deep_research/advanced_search_system/evidence/__init__.py
+++ b/src/local_deep_research/advanced_search_system/evidence/__init__.py
@@ -4,4 +4,9 @@ from .base_evidence import Evidence, EvidenceType
from .evaluator import EvidenceEvaluator
from .requirements import EvidenceRequirements
-__all__ = ["Evidence", "EvidenceType", "EvidenceEvaluator", "EvidenceRequirements"]
+__all__ = [
+ "Evidence",
+ "EvidenceType",
+ "EvidenceEvaluator",
+ "EvidenceRequirements",
+]
diff --git a/src/local_deep_research/advanced_search_system/evidence/base_evidence.py b/src/local_deep_research/advanced_search_system/evidence/base_evidence.py
index 2dbb5d87a7..7fc9d4c5b9 100644
--- a/src/local_deep_research/advanced_search_system/evidence/base_evidence.py
+++ b/src/local_deep_research/advanced_search_system/evidence/base_evidence.py
@@ -46,7 +46,9 @@ class Evidence:
confidence: float = 0.0
reasoning: Optional[str] = None
raw_text: Optional[str] = None
- timestamp: str = field(default_factory=lambda: datetime.utcnow().isoformat())
+ timestamp: str = field(
+ default_factory=lambda: datetime.utcnow().isoformat()
+ )
metadata: Dict[str, Any] = field(default_factory=dict)
def __post_init__(self):
diff --git a/src/local_deep_research/advanced_search_system/evidence/evaluator.py b/src/local_deep_research/advanced_search_system/evidence/evaluator.py
index 5f0183d7ce..e706dccb6f 100644
--- a/src/local_deep_research/advanced_search_system/evidence/evaluator.py
+++ b/src/local_deep_research/advanced_search_system/evidence/evaluator.py
@@ -72,7 +72,9 @@ QUOTE: [relevant text]
# Ensure confidence is between 0 and 1
confidence = max(0.0, min(1.0, confidence))
except ValueError:
- logger.warning(f"Failed to parse confidence value: {confidence_str}")
+ logger.warning(
+ f"Failed to parse confidence value: {confidence_str}"
+ )
confidence = 0.5
evidence = Evidence(
@@ -149,7 +151,8 @@ QUOTE: [relevant text]
if constraint.value.lower() in evidence.claim.lower():
return 1.0
elif any(
- word in evidence.claim.lower() for word in constraint.value.lower().split()
+ word in evidence.claim.lower()
+ for word in constraint.value.lower().split()
):
return 0.8
else:
diff --git a/src/local_deep_research/advanced_search_system/evidence/requirements.py b/src/local_deep_research/advanced_search_system/evidence/requirements.py
index b781ea139a..3981444394 100644
--- a/src/local_deep_research/advanced_search_system/evidence/requirements.py
+++ b/src/local_deep_research/advanced_search_system/evidence/requirements.py
@@ -11,7 +11,9 @@ class EvidenceRequirements:
"""Define evidence requirements for different constraint types."""
@staticmethod
- def get_requirements(constraint_type: ConstraintType) -> Dict[str, List[str]]:
+ def get_requirements(
+ constraint_type: ConstraintType,
+ ) -> Dict[str, List[str]]:
"""Get evidence requirements for a constraint type.
Args:
@@ -24,7 +26,11 @@ class EvidenceRequirements:
ConstraintType.PROPERTY: {
"preferred": ["direct_statement", "official_record"],
"acceptable": ["research_finding", "inference"],
- "sources": ["scientific papers", "official documents", "encyclopedias"],
+ "sources": [
+ "scientific papers",
+ "official documents",
+ "encyclopedias",
+ ],
},
ConstraintType.NAME_PATTERN: {
"preferred": ["direct_statement", "linguistic_analysis"],
@@ -38,7 +44,11 @@ class EvidenceRequirements:
ConstraintType.EVENT: {
"preferred": ["news_report", "official_record"],
"acceptable": ["testimonial", "correlation"],
- "sources": ["news archives", "government reports", "witness accounts"],
+ "sources": [
+ "news archives",
+ "government reports",
+ "witness accounts",
+ ],
},
ConstraintType.STATISTIC: {
"preferred": ["statistical_data", "official_record"],
@@ -57,7 +67,11 @@ class EvidenceRequirements:
ConstraintType.LOCATION: {
"preferred": ["geographical_data", "official_record"],
"acceptable": ["mapping_data", "inference"],
- "sources": ["geographical surveys", "maps", "location databases"],
+ "sources": [
+ "geographical surveys",
+ "maps",
+ "location databases",
+ ],
},
ConstraintType.COMPARISON: {
"preferred": ["statistical_comparison", "research_finding"],
diff --git a/src/local_deep_research/advanced_search_system/filters/base_filter.py b/src/local_deep_research/advanced_search_system/filters/base_filter.py
index 87e9ddf631..b5e8676cda 100644
--- a/src/local_deep_research/advanced_search_system/filters/base_filter.py
+++ b/src/local_deep_research/advanced_search_system/filters/base_filter.py
@@ -22,7 +22,9 @@ class BaseFilter(ABC):
self.model = model
@abstractmethod
- def filter_results(self, results: List[Dict], query: str, **kwargs) -> List[Dict]:
+ def filter_results(
+ self, results: List[Dict], query: str, **kwargs
+ ) -> List[Dict]:
"""
Filter search results by relevance to the query.
diff --git a/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py b/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py
index 1605f33268..57957ec251 100644
--- a/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py
+++ b/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py
@@ -16,7 +16,11 @@ class CrossEngineFilter(BaseFilter):
"""Filter that ranks and filters results from multiple search engines."""
def __init__(
- self, model, max_results=None, default_reorder=True, default_reindex=True
+ self,
+ model,
+ max_results=None,
+ default_reorder=True,
+ default_reindex=True,
):
"""
Initialize the cross-engine filter.
@@ -30,7 +34,9 @@ class CrossEngineFilter(BaseFilter):
super().__init__(model)
# Get max_results from database settings if not provided
if max_results is None:
- max_results = int(get_db_setting("search.cross_engine_max_results", 100))
+ max_results = int(
+ get_db_setting("search.cross_engine_max_results", 100)
+ )
self.max_results = max_results
self.default_reorder = default_reorder
self.default_reindex = default_reindex
diff --git a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
index ac8eaac927..fd0e52e8d2 100644
--- a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
+++ b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
@@ -69,13 +69,17 @@ class JournalReputationFilter(BaseFilter):
self.__exclude_non_published = exclude_non_published
if self.__exclude_non_published is None:
self.__exclude_non_published = bool(
- get_db_setting("search.journal_reputation.exclude_non_published", False)
+ get_db_setting(
+ "search.journal_reputation.exclude_non_published", False
+ )
)
self.__quality_reanalysis_period = quality_reanalysis_period
if self.__quality_reanalysis_period is None:
self.__quality_reanalysis_period = timedelta(
days=int(
- get_db_setting("search.journal_reputation.reanalysis_period", 365)
+ get_db_setting(
+ "search.journal_reputation.reanalysis_period", 365
+ )
)
)
@@ -157,7 +161,9 @@ class JournalReputationFilter(BaseFilter):
f"ranking and peer review status. Be sure to specify the journal "
f"name in any generated questions."
)
- journal_info = "\n".join([f["content"] for f in journal_info["findings"]])
+ journal_info = "\n".join(
+ [f["content"] for f in journal_info["findings"]]
+ )
logger.debug(f"Received raw info about journal: {journal_info}")
# Have the LLM assess the reliability based on this information.
@@ -188,7 +194,9 @@ class JournalReputationFilter(BaseFilter):
reputation_score = int(response.strip())
except ValueError:
logger.error("Failed to parse reputation score from LLM response.")
- raise ValueError("Failed to parse reputation score from LLM response.")
+ raise ValueError(
+ "Failed to parse reputation score from LLM response."
+ )
return max(min(reputation_score, 10), 1)
@@ -268,7 +276,9 @@ class JournalReputationFilter(BaseFilter):
# Check the database first.
with get_db_session() as session:
- journal = session.query(Journal).filter_by(name=journal_name).first()
+ journal = (
+ session.query(Journal).filter_by(name=journal_name).first()
+ )
if (
journal is not None
and (time.time() - journal.quality_analysis_time)
@@ -290,7 +300,9 @@ class JournalReputationFilter(BaseFilter):
# okay.
return True
- def filter_results(self, results: List[Dict], query: str, **kwargs) -> List[Dict]:
+ def filter_results(
+ self, results: List[Dict], query: str, **kwargs
+ ) -> List[Dict]:
try:
return list(filter(self.__check_result, results))
except Exception as e:
diff --git a/src/local_deep_research/advanced_search_system/findings/repository.py b/src/local_deep_research/advanced_search_system/findings/repository.py
index 1a8dcf9077..39e00fe1e6 100644
--- a/src/local_deep_research/advanced_search_system/findings/repository.py
+++ b/src/local_deep_research/advanced_search_system/findings/repository.py
@@ -63,7 +63,10 @@ class FindingsRepository(BaseFindingsRepository):
# Store raw synthesized content if it's the final synthesis
# Only check for phase if it's a dictionary
- if isinstance(finding, dict) and finding.get("phase") == "Final synthesis":
+ if (
+ isinstance(finding, dict)
+ and finding.get("phase") == "Final synthesis"
+ ):
self.findings[query + "_synthesis"] = [
{
"phase": "Synthesis",
@@ -117,7 +120,9 @@ class FindingsRepository(BaseFindingsRepository):
questions_by_iteration: Dictionary mapping iteration numbers to lists of questions
"""
self.questions_by_iteration = questions_by_iteration.copy()
- logger.info(f"Set questions for {len(questions_by_iteration)} iterations")
+ logger.info(
+ f"Set questions for {len(questions_by_iteration)} iterations"
+ )
def format_findings_to_text(
self, findings_list: List[Dict], synthesized_content: str
@@ -142,7 +147,9 @@ class FindingsRepository(BaseFindingsRepository):
f"Questions by iteration keys: {list(self.questions_by_iteration.keys())}"
)
if findings_list:
- logger.debug(f"First finding item keys: {list(findings_list[0].keys())}")
+ logger.debug(
+ f"First finding item keys: {list(findings_list[0].keys())}"
+ )
try:
# Pass the detailed findings list, the synthesized content (as current_knowledge), and the stored questions
@@ -211,14 +218,18 @@ class FindingsRepository(BaseFindingsRepository):
)
elif isinstance(findings[0], str):
logger.info(f"first finding string length: {len(findings[0])}")
- logger.info(f"first finding string preview: {findings[0][:100]}...")
+ logger.info(
+ f"first finding string preview: {findings[0][:100]}..."
+ )
if old_formatting:
# Convert findings list if it contains strings instead of dictionaries
findings_list = []
for i, item in enumerate(findings):
if isinstance(item, str):
- findings_list.append({"phase": f"Finding {i + 1}", "content": item})
+ findings_list.append(
+ {"phase": f"Finding {i + 1}", "content": item}
+ )
elif isinstance(item, dict):
findings_list.append(item)
@@ -237,12 +248,16 @@ class FindingsRepository(BaseFindingsRepository):
finding_texts.append(item)
# Use finding_texts for the prompt
- current_knowledge = "\n\n".join(finding_texts) if finding_texts else ""
+ current_knowledge = (
+ "\n\n".join(finding_texts) if finding_texts else ""
+ )
# Check if knowledge exceeds a reasonable token limit (rough estimate based on characters)
# 1 token ≈ 4 characters in English
estimated_tokens = len(current_knowledge) / 4
- max_safe_tokens = 12000 # Adjust based on your model's context window
+ max_safe_tokens = (
+ 12000 # Adjust based on your model's context window
+ )
if estimated_tokens > max_safe_tokens:
logger.warning(
@@ -251,10 +266,16 @@ class FindingsRepository(BaseFindingsRepository):
# Truncate if needed (keeping the beginning and end which are often most important)
# This is a simple approach - a more sophisticated chunking might be better
if len(current_knowledge) > 24000: # ~6000 tokens
- first_part = current_knowledge[:12000] # ~3000 tokens from start
- last_part = current_knowledge[-12000:] # ~3000 tokens from end
+ first_part = current_knowledge[
+ :12000
+ ] # ~3000 tokens from start
+ last_part = current_knowledge[
+ -12000:
+ ] # ~3000 tokens from end
current_knowledge = f"{first_part}\n\n[...content truncated due to length...]\n\n{last_part}"
- logger.info("Knowledge truncated to fit within token limits")
+ logger.info(
+ "Knowledge truncated to fit within token limits"
+ )
prompt = f"""Use IEEE style citations [1], [2], etc. Never make up your own citations. Synthesize the following accumulated knowledge into a comprehensive answer for the original query.
Format the response with clear sections, citations, and a concise summary.
@@ -280,7 +301,9 @@ Use IEEE style citations [1], [2], etc. Never make up your own citations.
f"Synthesizing final answer. Query: '{query}'. Knowledge length: {len(current_knowledge)}. Prompt length: {len(prompt)}"
)
# Log first 500 chars of prompt for debugging context length issues
- logger.debug(f"Synthesis prompt (first 500 chars): {prompt[:500]}...")
+ logger.debug(
+ f"Synthesis prompt (first 500 chars): {prompt[:500]}..."
+ )
try:
# Add timeout handling
@@ -300,7 +323,9 @@ Use IEEE style citations [1], [2], etc. Never make up your own citations.
timer.daemon = True
return timer
- def invoke_with_timeout(timeout_seconds, func, *args, **kwargs):
+ def invoke_with_timeout(
+ timeout_seconds, func, *args, **kwargs
+ ):
"""
Function for implementing timeouts on Windows
"""
@@ -338,7 +363,9 @@ Use IEEE style citations [1], [2], etc. Never make up your own citations.
logger.info(
"Using Windows-compatible timeout for LLM invocation"
)
- response = invoke_with_timeout(120, self.model.invoke, prompt)
+ response = invoke_with_timeout(
+ 120, self.model.invoke, prompt
+ )
# Handle different response types (string or object with content attribute)
if hasattr(response, "content"):
@@ -376,7 +403,9 @@ Use IEEE style citations [1], [2], etc. Never make up your own citations.
# Try with a timeout (adjust seconds as needed)
try:
- with timeout(120, "LLM invocation timed out after 120 seconds"):
+ with timeout(
+ 120, "LLM invocation timed out after 120 seconds"
+ ):
response = self.model.invoke(prompt)
# Handle different response types (string or object with content attribute)
@@ -417,11 +446,19 @@ Use IEEE style citations [1], [2], etc. Never make up your own citations.
or "token limit" in error_message
):
error_type = "token_limit"
- elif "rate limit" in error_message or "rate_limit" in error_message:
+ elif (
+ "rate limit" in error_message
+ or "rate_limit" in error_message
+ ):
error_type = "rate_limit"
- elif "connection" in error_message or "network" in error_message:
+ elif (
+ "connection" in error_message or "network" in error_message
+ ):
error_type = "connection"
- elif "api key" in error_message or "authentication" in error_message:
+ elif (
+ "api key" in error_message
+ or "authentication" in error_message
+ ):
error_type = "authentication"
# Return more detailed error message based on type
diff --git a/src/local_deep_research/advanced_search_system/knowledge/standard_knowledge.py b/src/local_deep_research/advanced_search_system/knowledge/standard_knowledge.py
index b961dfa50a..3c379eeed4 100644
--- a/src/local_deep_research/advanced_search_system/knowledge/standard_knowledge.py
+++ b/src/local_deep_research/advanced_search_system/knowledge/standard_knowledge.py
@@ -132,7 +132,9 @@ Compressed Knowledge:"""
try:
response = self.model.invoke(prompt)
compressed_knowledge = response.content
- logger.info(f"Compressed knowledge length: {len(compressed_knowledge)}")
+ logger.info(
+ f"Compressed knowledge length: {len(compressed_knowledge)}"
+ )
return compressed_knowledge
except Exception as e:
logger.error(f"Error compressing knowledge: {str(e)}")
diff --git a/src/local_deep_research/advanced_search_system/query_generation/adaptive_query_generator.py b/src/local_deep_research/advanced_search_system/query_generation/adaptive_query_generator.py
index 1b098f0a7a..25a935a9a1 100644
--- a/src/local_deep_research/advanced_search_system/query_generation/adaptive_query_generator.py
+++ b/src/local_deep_research/advanced_search_system/query_generation/adaptive_query_generator.py
@@ -2,13 +2,11 @@
Adaptive query generation system for improved search performance.
"""
-import re
from collections import defaultdict
from dataclasses import dataclass
from typing import Dict, List, Optional, Set, Tuple
from langchain_core.language_models import BaseChatModel
-from loguru import logger
from ...utilities.search_utilities import remove_think_tags
from ..constraints.base_constraint import Constraint, ConstraintType
@@ -42,9 +40,9 @@ class AdaptiveQueryGenerator:
self.successful_patterns: List[QueryPattern] = []
self.failed_queries: Set[str] = set()
self.semantic_expansions: Dict[str, List[str]] = {}
- self.constraint_combinations: Dict[Tuple[ConstraintType, ...], float] = (
- defaultdict(float)
- )
+ self.constraint_combinations: Dict[
+ Tuple[ConstraintType, ...], float
+ ] = defaultdict(float)
# Initialize default patterns
self._initialize_default_patterns()
@@ -104,7 +102,9 @@ class AdaptiveQueryGenerator:
# Fall back to LLM-based generation
return self._generate_with_llm(constraints, context)
- def _generate_from_patterns(self, constraints: List[Constraint]) -> Optional[str]:
+ def _generate_from_patterns(
+ self, constraints: List[Constraint]
+ ) -> Optional[str]:
"""Generate query using learned patterns."""
constraint_types = [c.type for c in constraints]
@@ -146,7 +146,9 @@ class AdaptiveQueryGenerator:
except KeyError:
return None
- def _generate_with_expansion(self, constraints: List[Constraint]) -> Optional[str]:
+ def _generate_with_expansion(
+ self, constraints: List[Constraint]
+ ) -> Optional[str]:
"""Generate query with semantic expansion."""
expanded_terms = []
@@ -154,13 +156,17 @@ class AdaptiveQueryGenerator:
# Get expansions for this value
if constraint.value not in self.semantic_expansions:
self.semantic_expansions[constraint.value] = (
- self._get_semantic_expansions(constraint.value, constraint.type)
+ self._get_semantic_expansions(
+ constraint.value, constraint.type
+ )
)
expansions = self.semantic_expansions[constraint.value]
if expansions:
# Use OR to include expansions
- expanded = f'({constraint.value} OR {" OR ".join(expansions[:2])})'
+ expanded = (
+ f"({constraint.value} OR {' OR '.join(expansions[:2])})"
+ )
expanded_terms.append(expanded)
else:
expanded_terms.append(f'"{constraint.value}"')
@@ -200,11 +206,11 @@ Return only the terms, one per line.
context_info = ""
if context:
if "failed_queries" in context:
- context_info += f"\nFailed queries to avoid:\n" + "\n".join(
+ context_info += "\nFailed queries to avoid:\n" + "\n".join(
context["failed_queries"][:3]
)
if "successful_queries" in context:
- context_info += f"\nSuccessful query patterns:\n" + "\n".join(
+ context_info += "\nSuccessful query patterns:\n" + "\n".join(
context["successful_queries"][:3]
)
@@ -290,7 +296,9 @@ Return only the search query.
"""Format constraints for prompts."""
formatted = []
for c in constraints:
- formatted.append(f"- {c.type.value}: {c.description} [value: {c.value}]")
+ formatted.append(
+ f"- {c.type.value}: {c.description} [value: {c.value}]"
+ )
return "\n".join(formatted)
def generate_fallback_queries(
@@ -368,7 +376,9 @@ Return only the queries, one per line.
# Sort constraint combinations by success rate
sorted_combos = sorted(
- self.constraint_combinations.items(), key=lambda x: x[1], reverse=True
+ self.constraint_combinations.items(),
+ key=lambda x: x[1],
+ reverse=True,
)
# Try successful combinations first
diff --git a/src/local_deep_research/advanced_search_system/questions/atomic_fact_question.py b/src/local_deep_research/advanced_search_system/questions/atomic_fact_question.py
index b0f5aba9de..b4bdc7ffda 100644
--- a/src/local_deep_research/advanced_search_system/questions/atomic_fact_question.py
+++ b/src/local_deep_research/advanced_search_system/questions/atomic_fact_question.py
@@ -47,7 +47,10 @@ class AtomicFactQuestionGenerator(BaseQuestionGenerator):
# On subsequent iterations, fill knowledge gaps or explore connections
return self._generate_gap_filling_questions(
- query, current_knowledge, questions_by_iteration, questions_per_iteration
+ query,
+ current_knowledge,
+ questions_by_iteration,
+ questions_per_iteration,
)
def _decompose_to_atomic_facts(self, query: str) -> List[str]:
diff --git a/src/local_deep_research/advanced_search_system/questions/browsecomp_question.py b/src/local_deep_research/advanced_search_system/questions/browsecomp_question.py
index 3c9dfae393..c97797f2f1 100644
--- a/src/local_deep_research/advanced_search_system/questions/browsecomp_question.py
+++ b/src/local_deep_research/advanced_search_system/questions/browsecomp_question.py
@@ -79,7 +79,9 @@ DESCRIPTORS: [entity1], [entity2], ...
"""
response = self.model.invoke(prompt)
- content = response.content if hasattr(response, "content") else str(response)
+ content = (
+ response.content if hasattr(response, "content") else str(response)
+ )
entities = {
"temporal": [],
@@ -101,17 +103,23 @@ DESCRIPTORS: [entity1], [entity2], ...
entities[category].extend(values)
# Expand temporal ranges
- entities["temporal"] = self._expand_temporal_ranges(entities["temporal"])
+ entities["temporal"] = self._expand_temporal_ranges(
+ entities["temporal"]
+ )
logger.info(f"Extracted entities: {entities}")
return entities
- def _expand_temporal_ranges(self, temporal_entities: List[str]) -> List[str]:
+ def _expand_temporal_ranges(
+ self, temporal_entities: List[str]
+ ) -> List[str]:
"""Expand year ranges into individual years."""
expanded = []
for entity in temporal_entities:
# Check for range patterns like "2018-2023" or "between 1995 and 2006"
- range_match = re.search(r"(\d{4})[-\s]+(?:to|and)?\s*(\d{4})", entity)
+ range_match = re.search(
+ r"(\d{4})[-\s]+(?:to|and)?\s*(\d{4})", entity
+ )
if range_match:
start_year = int(range_match.group(1))
end_year = int(range_match.group(2))
@@ -149,7 +157,9 @@ DESCRIPTORS: [entity1], [entity2], ...
key_term = (
entities["names"][0]
if entities["names"]
- else entities["descriptors"][0] if entities["descriptors"] else ""
+ else entities["descriptors"][0]
+ if entities["descriptors"]
+ else ""
)
for year in entities["temporal"][:5]: # Limit to 5 years initially
if key_term:
@@ -189,10 +199,10 @@ DESCRIPTORS: [entity1], [entity2], ...
Original Query: {query}
Entities Found:
-- Names/Terms: {', '.join(entities['names'][:5])}
-- Years: {', '.join(entities['temporal'][:5])}
-- Locations: {', '.join(entities['locations'][:3])}
-- Key Features: {', '.join(entities['descriptors'][:3])}
+- Names/Terms: {", ".join(entities["names"][:5])}
+- Years: {", ".join(entities["temporal"][:5])}
+- Locations: {", ".join(entities["locations"][:3])}
+- Key Features: {", ".join(entities["descriptors"][:3])}
Current Knowledge Summary:
{current_knowledge[:1500]}
@@ -212,7 +222,9 @@ Format: One search per line
"""
response = self.model.invoke(prompt)
- content = response.content if hasattr(response, "content") else str(response)
+ content = (
+ response.content if hasattr(response, "content") else str(response)
+ )
# Extract searches from response
searches = []
@@ -233,7 +245,9 @@ Format: One search per line
# Continue with year-based searches
for year in entities["temporal"]:
if not self._was_searched(year, questions_by_iteration):
- base_term = entities["names"][0] if entities["names"] else ""
+ base_term = (
+ entities["names"][0] if entities["names"] else ""
+ )
searches.append(f"{base_term} {year}".strip())
if len(searches) >= num_questions:
break
@@ -243,7 +257,9 @@ Format: One search per line
for name in entities["names"]:
for desc in entities["descriptors"]:
combo = f"{name} {desc}"
- if not self._was_searched(combo, questions_by_iteration):
+ if not self._was_searched(
+ combo, questions_by_iteration
+ ):
searches.append(combo)
if len(searches) >= num_questions:
break
@@ -255,7 +271,9 @@ Format: One search per line
formatted = []
for iteration, questions in questions_by_iteration.items():
if isinstance(questions, list):
- formatted.extend([f"Iteration {iteration}: {q}" for q in questions[:3]])
+ formatted.extend(
+ [f"Iteration {iteration}: {q}" for q in questions[:3]]
+ )
return "\n".join(formatted[-10:]) # Last 10 searches
def _was_searched(self, term: str, questions_by_iteration: dict) -> bool:
diff --git a/src/local_deep_research/advanced_search_system/questions/decomposition_question.py b/src/local_deep_research/advanced_search_system/questions/decomposition_question.py
index 3510f88e8e..9634662c35 100644
--- a/src/local_deep_research/advanced_search_system/questions/decomposition_question.py
+++ b/src/local_deep_research/advanced_search_system/questions/decomposition_question.py
@@ -101,7 +101,9 @@ class DecompositionQuestionGenerator(BaseQuestionGenerator):
if subject.lower().startswith(article):
subject = subject[len(article) :].strip()
- logger.info(f"Original query: '{query}', Extracted subject: '{subject}'")
+ logger.info(
+ f"Original query: '{query}', Extracted subject: '{subject}'"
+ )
# Create a prompt to decompose the query into sub-questions
prompt = f"""Decompose the main research topic into 3-5 specific sub-queries that can be answered independently.
@@ -223,7 +225,9 @@ What are the security implications of X?
for conjunction in conjunctions:
if conjunction in topic_text.lower():
# Take only the part before the conjunction
- topic_text = topic_text.split(conjunction)[0].strip()
+ topic_text = topic_text.split(conjunction)[
+ 0
+ ].strip()
logger.info(
f"Simplified prompt: Split compound query at '{conjunction}', extracted: '{topic_text}'"
)
@@ -288,7 +292,9 @@ Sub-questions:
)
return self._generate_default_questions(query)
- logger.info(f"Generated {len(sub_queries)} sub-questions: {sub_queries}")
+ logger.info(
+ f"Generated {len(sub_queries)} sub-questions: {sub_queries}"
+ )
return sub_queries[: self.max_subqueries] # Limit to max_subqueries
except Exception as e:
@@ -380,7 +386,10 @@ Sub-questions:
)
# Special case for CSRF - if we've extracted just "csrf" from a longer query
- if subject.lower() == "csrf" or subject.lower() == "cross-site request forgery":
+ if (
+ subject.lower() == "csrf"
+ or subject.lower() == "cross-site request forgery"
+ ):
# CSRF-specific questions
default_questions = [
"What is Cross-Site Request Forgery (CSRF)?",
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 be46205215..45d5ed7ea2 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
@@ -49,7 +49,9 @@ class EntityAwareQuestionGenerator(BaseQuestionGenerator):
"movie",
]
- is_entity_query = any(keyword in query.lower() for keyword in entity_keywords)
+ is_entity_query = any(
+ keyword in query.lower() for keyword in entity_keywords
+ )
if is_entity_query:
# Use more direct entity-focused prompt
@@ -113,7 +115,9 @@ Q: question2
return questions
- def generate_sub_questions(self, query: str, context: str = "") -> List[str]:
+ def generate_sub_questions(
+ self, query: str, context: str = ""
+ ) -> List[str]:
"""Generate sub-questions with entity focus when appropriate."""
# Check if this is an entity identification query
entity_keywords = [
@@ -129,7 +133,9 @@ Q: question2
"company",
]
- is_entity_query = any(keyword in query.lower() for keyword in entity_keywords)
+ is_entity_query = any(
+ keyword in query.lower() for keyword in entity_keywords
+ )
if is_entity_query:
prompt = f"""Break down this entity identification query into targeted sub-questions.
diff --git a/src/local_deep_research/advanced_search_system/questions/standard_question.py b/src/local_deep_research/advanced_search_system/questions/standard_question.py
index a8e2476107..86684fc902 100644
--- a/src/local_deep_research/advanced_search_system/questions/standard_question.py
+++ b/src/local_deep_research/advanced_search_system/questions/standard_question.py
@@ -59,7 +59,9 @@ class StandardQuestionGenerator(BaseQuestionGenerator):
return questions
- def generate_sub_questions(self, query: str, context: str = "") -> List[str]:
+ def generate_sub_questions(
+ self, query: str, context: str = ""
+ ) -> List[str]:
"""
Generate sub-questions from a main query.
@@ -107,7 +109,11 @@ Only provide the numbered sub-questions, nothing else."""
line = line.strip()
if line and (line[0].isdigit() or line.startswith("-")):
# Extract sub-question from numbered or bulleted list
- parts = line.split(".", 1) if "." in line else line.split(" ", 1)
+ parts = (
+ line.split(".", 1)
+ if "." in line
+ else line.split(" ", 1)
+ )
if len(parts) > 1:
sub_question = parts[1].strip()
sub_questions.append(sub_question)
diff --git a/src/local_deep_research/advanced_search_system/search_optimization/cross_constraint_manager.py b/src/local_deep_research/advanced_search_system/search_optimization/cross_constraint_manager.py
index 08fe2fc25b..7201b32223 100644
--- a/src/local_deep_research/advanced_search_system/search_optimization/cross_constraint_manager.py
+++ b/src/local_deep_research/advanced_search_system/search_optimization/cross_constraint_manager.py
@@ -8,11 +8,10 @@ from dataclasses import dataclass, field
from typing import Dict, List, Optional, Set, Tuple
from langchain_core.language_models import BaseChatModel
-from loguru import logger
from ...utilities.search_utilities import remove_think_tags
from ..candidates.base_candidate import Candidate
-from ..constraints.base_constraint import Constraint, ConstraintType
+from ..constraints.base_constraint import Constraint
@dataclass
@@ -52,7 +51,9 @@ class CrossConstraintManager:
self.model = model
self.relationships: Dict[Tuple[str, str], ConstraintRelationship] = {}
self.clusters: List[ConstraintCluster] = []
- self.cross_validation_patterns: Dict[str, List[Dict]] = defaultdict(list)
+ self.cross_validation_patterns: Dict[str, List[Dict]] = defaultdict(
+ list
+ )
self.constraint_graph: Dict[str, Set[str]] = defaultdict(set)
def analyze_constraint_relationships(
@@ -64,7 +65,9 @@ class CrossConstraintManager:
# Analyze each pair of constraints
for c1, c2 in itertools.combinations(constraints, 2):
relationship = self._analyze_pair(c1, c2)
- if relationship.strength > 0.3: # Only keep meaningful relationships
+ if (
+ relationship.strength > 0.3
+ ): # Only keep meaningful relationships
key = (c1.id, c2.id)
relationships[key] = relationship
@@ -75,7 +78,9 @@ class CrossConstraintManager:
self.relationships.update(relationships)
return relationships
- def _analyze_pair(self, c1: Constraint, c2: Constraint) -> ConstraintRelationship:
+ def _analyze_pair(
+ self, c1: Constraint, c2: Constraint
+ ) -> ConstraintRelationship:
"""Analyze the relationship between two constraints."""
prompt = f"""
Analyze the relationship between these two constraints:
@@ -140,7 +145,9 @@ Evidence: [explanation]
for ctype, group in type_groups.items():
if len(group) > 1:
cluster = ConstraintCluster(
- constraints=group, cluster_type="type_based", coherence_score=0.7
+ constraints=group,
+ cluster_type="type_based",
+ coherence_score=0.7,
)
clusters.append(cluster)
@@ -165,7 +172,9 @@ Evidence: [explanation]
return unique_clusters
def _create_relationship_clusters(
- self, constraints: List[Constraint], relationships: List[ConstraintRelationship]
+ self,
+ constraints: List[Constraint],
+ relationships: List[ConstraintRelationship],
) -> List[ConstraintCluster]:
"""Create clusters based on strong relationships."""
clusters = []
@@ -189,7 +198,9 @@ Evidence: [explanation]
while queue:
current_id = queue.pop(0)
- current = next((c for c in constraints if c.id == current_id), None)
+ current = next(
+ (c for c in constraints if c.id == current_id), None
+ )
if current:
component.append(current)
processed.add(current_id)
@@ -203,7 +214,9 @@ Evidence: [explanation]
cluster = ConstraintCluster(
constraints=component,
cluster_type="relationship_based",
- coherence_score=self._calculate_cluster_coherence(component),
+ coherence_score=self._calculate_cluster_coherence(
+ component
+ ),
)
clusters.append(cluster)
@@ -272,20 +285,26 @@ Coherence: [0.0-1.0]
elif line.startswith("Coherence:"):
try:
- current_cluster["coherence"] = float(line.split(":", 1)[1].strip())
+ current_cluster["coherence"] = float(
+ line.split(":", 1)[1].strip()
+ )
except ValueError:
current_cluster["coherence"] = 0.5
# Don't forget the last cluster
if current_cluster and "constraints" in current_cluster:
constraint_ids = current_cluster["constraints"]
- cluster_constraints = [c for c in constraints if c.id in constraint_ids]
+ cluster_constraints = [
+ c for c in constraints if c.id in constraint_ids
+ ]
if len(cluster_constraints) > 1:
cluster = ConstraintCluster(
constraints=cluster_constraints,
cluster_type="semantic",
- coherence_score=float(current_cluster.get("coherence", 0.5)),
+ coherence_score=float(
+ current_cluster.get("coherence", 0.5)
+ ),
)
clusters.append(cluster)
@@ -302,16 +321,22 @@ Coherence: [0.0-1.0]
queries.append(combined_query)
# 2. Progressive queries (build up constraints)
- progressive_queries = self._generate_progressive_queries(cluster.constraints)
+ progressive_queries = self._generate_progressive_queries(
+ cluster.constraints
+ )
queries.extend(progressive_queries)
# 3. Intersection queries (shared aspects)
- intersection_query = self._generate_intersection_query(cluster.constraints)
+ intersection_query = self._generate_intersection_query(
+ cluster.constraints
+ )
if intersection_query:
queries.append(intersection_query)
# 4. Validation queries (cross-check)
- validation_queries = self._generate_validation_queries(cluster.constraints)
+ validation_queries = self._generate_validation_queries(
+ cluster.constraints
+ )
queries.extend(validation_queries)
# Store queries in cluster
@@ -338,12 +363,16 @@ Return only the search query.
response = self.model.invoke(prompt)
return remove_think_tags(response.content).strip()
- def _generate_progressive_queries(self, constraints: List[Constraint]) -> List[str]:
+ def _generate_progressive_queries(
+ self, constraints: List[Constraint]
+ ) -> List[str]:
"""Generate queries that progressively add constraints."""
queries = []
# Sort by weight/importance
- sorted_constraints = sorted(constraints, key=lambda c: c.weight, reverse=True)
+ sorted_constraints = sorted(
+ constraints, key=lambda c: c.weight, reverse=True
+ )
# Build up constraints
for i in range(2, min(len(sorted_constraints) + 1, 4)):
@@ -377,7 +406,9 @@ Return only the search query, or 'NONE' if no clear intersection exists.
return query
- def _generate_validation_queries(self, constraints: List[Constraint]) -> List[str]:
+ def _generate_validation_queries(
+ self, constraints: List[Constraint]
+ ) -> List[str]:
"""Generate queries for cross-validation."""
queries = []
@@ -442,7 +473,9 @@ Return only the search query.
) -> float:
"""Validate candidate using cluster-based approach."""
if not cluster.search_queries:
- cluster.search_queries = self.generate_cross_constraint_queries(cluster)
+ cluster.search_queries = self.generate_cross_constraint_queries(
+ cluster
+ )
# Use the most comprehensive query
validation_query = cluster.search_queries[0]
@@ -509,7 +542,9 @@ Score: [0.0-1.0]
return score
- def _calculate_cluster_coherence(self, constraints: List[Constraint]) -> float:
+ def _calculate_cluster_coherence(
+ self, constraints: List[Constraint]
+ ) -> float:
"""Calculate coherence score for a constraint cluster."""
if len(constraints) < 2:
return 0.0
@@ -557,7 +592,9 @@ Score: [0.0-1.0]
return unique_clusters
- def _format_constraints_for_clustering(self, constraints: List[Constraint]) -> str:
+ def _format_constraints_for_clustering(
+ self, constraints: List[Constraint]
+ ) -> str:
"""Format constraints for clustering prompt."""
formatted = []
for c in constraints:
@@ -566,7 +603,9 @@ Score: [0.0-1.0]
)
return "\n".join(formatted)
- def _format_constraints_for_query(self, constraints: List[Constraint]) -> str:
+ def _format_constraints_for_query(
+ self, constraints: List[Constraint]
+ ) -> str:
"""Format constraints for query generation."""
formatted = []
for c in constraints:
diff --git a/src/local_deep_research/advanced_search_system/source_management/diversity_manager.py b/src/local_deep_research/advanced_search_system/source_management/diversity_manager.py
index db8b69776b..1b065df732 100644
--- a/src/local_deep_research/advanced_search_system/source_management/diversity_manager.py
+++ b/src/local_deep_research/advanced_search_system/source_management/diversity_manager.py
@@ -6,14 +6,11 @@ import re
from collections import defaultdict
from dataclasses import dataclass, field
from datetime import datetime
-from typing import Dict, List, Optional, Set, Tuple
+from typing import Dict, List, Optional, Set, Tuple, Any
from langchain_core.language_models import BaseChatModel
-from loguru import logger
-from ..candidates.base_candidate import Candidate
from ..constraints.base_constraint import Constraint, ConstraintType
-from ..evidence.base_evidence import Evidence, EvidenceType
@dataclass
@@ -71,7 +68,9 @@ class SourceDiversityManager:
self.minimum_source_types: int = 3
self.credibility_threshold: float = 0.6
- def analyze_source(self, url: str, content: Optional[str] = None) -> SourceProfile:
+ def analyze_source(
+ self, url: str, content: Optional[str] = None
+ ) -> SourceProfile:
"""Analyze a source and create its profile."""
if url in self.source_profiles:
profile = self.source_profiles[url]
@@ -86,7 +85,9 @@ class SourceDiversityManager:
source_type = self._determine_source_type(url, domain, content)
# Calculate credibility
- credibility = self._calculate_credibility(url, domain, source_type, content)
+ credibility = self._calculate_credibility(
+ url, domain, source_type, content
+ )
# Extract specialties
specialties = self._extract_specialties(url, content)
@@ -127,9 +128,24 @@ class SourceDiversityManager:
) -> str:
"""Determine the type of source."""
# Check known patterns
- academic_domains = [".edu", ".ac.", "scholar", "pubmed", "arxiv", "jstor"]
+ academic_domains = [
+ ".edu",
+ ".ac.",
+ "scholar",
+ "pubmed",
+ "arxiv",
+ "jstor",
+ ]
government_domains = [".gov", ".mil"]
- news_domains = ["news", "times", "post", "guardian", "bbc", "cnn", "reuters"]
+ news_domains = [
+ "news",
+ "times",
+ "post",
+ "guardian",
+ "bbc",
+ "cnn",
+ "reuters",
+ ]
wiki_domains = ["wikipedia", "wiki"]
lower_domain = domain.lower()
@@ -199,12 +215,16 @@ Return only the source type.
base_score = min(base_score + 0.1, 1.0)
# Check for author information
- if re.search(r"[Aa]uthor:|[Bb]y\s+[A-Z][a-z]+\s+[A-Z][a-z]+", content):
+ if re.search(
+ r"[Aa]uthor:|[Bb]y\s+[A-Z][a-z]+\s+[A-Z][a-z]+", content
+ ):
base_score = min(base_score + 0.05, 1.0)
return base_score
- def _extract_specialties(self, url: str, content: Optional[str]) -> List[str]:
+ def _extract_specialties(
+ self, url: str, content: Optional[str]
+ ) -> List[str]:
"""Extract topic specialties from source."""
specialties = []
@@ -289,7 +309,9 @@ Return up to 3 topic areas, one per line.
return None
- def calculate_diversity_metrics(self, sources: List[str]) -> DiversityMetrics:
+ def calculate_diversity_metrics(
+ self, sources: List[str]
+ ) -> DiversityMetrics:
"""Calculate diversity metrics for a set of sources."""
if not sources:
return DiversityMetrics(
@@ -303,7 +325,8 @@ Return up to 3 topic areas, one per line.
# Get profiles
profiles = [
- self.source_profiles.get(url) or self.analyze_source(url) for url in sources
+ self.source_profiles.get(url) or self.analyze_source(url)
+ for url in sources
]
# Type diversity
@@ -312,11 +335,15 @@ Return up to 3 topic areas, one per line.
type_diversity = min(unique_types / self.minimum_source_types, 1.0)
# Temporal diversity
- temporal_ranges = [p.temporal_coverage for p in profiles if p.temporal_coverage]
+ temporal_ranges = [
+ p.temporal_coverage for p in profiles if p.temporal_coverage
+ ]
temporal_diversity = self._calculate_temporal_diversity(temporal_ranges)
# Geographic diversity
- geo_focuses = [p.geographic_focus for p in profiles if p.geographic_focus]
+ geo_focuses = [
+ p.geographic_focus for p in profiles if p.geographic_focus
+ ]
unique_geos = len(set(geo_focuses))
geographic_diversity = min(unique_geos / 3, 1.0) if geo_focuses else 0.0
@@ -326,15 +353,21 @@ Return up to 3 topic areas, one per line.
level = (
"high"
if p.credibility_score >= 0.8
- else "medium" if p.credibility_score >= 0.6 else "low"
+ else "medium"
+ if p.credibility_score >= 0.6
+ else "low"
+ )
+ credibility_distribution[level] = (
+ credibility_distribution.get(level, 0) + 1
)
- credibility_distribution[level] = credibility_distribution.get(level, 0) + 1
# Specialty coverage
specialty_coverage = {}
for p in profiles:
for specialty in p.specialties:
- specialty_coverage[specialty] = specialty_coverage.get(specialty, 0) + 1
+ specialty_coverage[specialty] = (
+ specialty_coverage.get(specialty, 0) + 1
+ )
# Overall score
overall_score = (
@@ -391,7 +424,9 @@ Return up to 3 topic areas, one per line.
rec = {
"type": "source_type",
"target": missing_type,
- "query_modifier": self._get_source_type_modifier(missing_type),
+ "query_modifier": self._get_source_type_modifier(
+ missing_type
+ ),
"reason": f"Add {missing_type} sources for better perspective",
}
recommendations.append(rec)
@@ -437,7 +472,9 @@ Return up to 3 topic areas, one per line.
# Source type gaps
if metrics.type_diversity < 0.7:
- current_types = set(p.source_type for p in self.source_profiles.values())
+ current_types = set(
+ p.source_type for p in self.source_profiles.values()
+ )
desired_types = {"academic", "government", "news", "wiki"}
missing_types = desired_types - current_types
if missing_types:
@@ -508,7 +545,9 @@ Return up to 3 topic areas, one per line.
source_scores = []
for source in available_sources:
- profile = self.source_profiles.get(source) or self.analyze_source(source)
+ profile = self.source_profiles.get(source) or self.analyze_source(
+ source
+ )
# Calculate diversity score
score = (
@@ -557,7 +596,9 @@ Return up to 3 topic areas, one per line.
# Update profile based on effectiveness
if constraint_satisfied:
# Boost credibility slightly
- profile.credibility_score = min(profile.credibility_score * 1.05, 1.0)
+ profile.credibility_score = min(
+ profile.credibility_score * 1.05, 1.0
+ )
# Track in metadata
if "effectiveness" not in profile.__dict__:
diff --git a/src/local_deep_research/advanced_search_system/strategies/adaptive_decomposition_strategy.py b/src/local_deep_research/advanced_search_system/strategies/adaptive_decomposition_strategy.py
index 39e9c185f1..5ebd201bc6 100644
--- a/src/local_deep_research/advanced_search_system/strategies/adaptive_decomposition_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/adaptive_decomposition_strategy.py
@@ -161,7 +161,9 @@ class AdaptiveDecompositionStrategy(BaseSearchStrategy):
return final_result
- def _decide_next_step(self, query: str, step_count: int) -> Optional[StepResult]:
+ def _decide_next_step(
+ self, query: str, step_count: int
+ ) -> Optional[StepResult]:
"""Decide the next step based on current knowledge.
Args:
@@ -176,10 +178,10 @@ class AdaptiveDecompositionStrategy(BaseSearchStrategy):
Original Query: {query}
Current Knowledge:
-- Extracted Constraints: {self.working_knowledge.get('constraints', [])}
-- Candidate Locations: {self.working_knowledge.get('candidates', [])}
-- Verified Facts: {self.working_knowledge.get('verified_facts', [])}
-- Uncertainties: {self.working_knowledge.get('uncertainties', [])}
+- Extracted Constraints: {self.working_knowledge.get("constraints", [])}
+- Candidate Locations: {self.working_knowledge.get("candidates", [])}
+- Verified Facts: {self.working_knowledge.get("verified_facts", [])}
+- Uncertainties: {self.working_knowledge.get("uncertainties", [])}
Previous Steps: {[s.step_type.value for s in self.step_results]}
"""
@@ -401,9 +403,9 @@ List each constraint/clue separately and explain why it's important:
knowledge_summary = f"""
Original Query: {query}
-Constraints: {self.working_knowledge['constraints']}
-Candidates: {self.working_knowledge['candidates']}
-Verified Facts: {self.working_knowledge['verified_facts']}
+Constraints: {self.working_knowledge["constraints"]}
+Candidates: {self.working_knowledge["candidates"]}
+Verified Facts: {self.working_knowledge["verified_facts"]}
"""
prompt = f"""Based on all the information gathered, provide the answer:
@@ -456,12 +458,17 @@ Provide:
if "all_links_of_system" in raw:
all_links.extend(raw["all_links_of_system"])
if "questions_by_iteration" in raw:
- all_questions.extend(raw.get("questions_by_iteration", {}).values())
+ all_questions.extend(
+ raw.get("questions_by_iteration", {}).values()
+ )
# Get final answer
final_answer = "No confident answer found."
for step in reversed(self.step_results):
- if step.step_type == StepType.SYNTHESIS and "answer" in step.findings:
+ if (
+ step.step_type == StepType.SYNTHESIS
+ and "answer" in step.findings
+ ):
final_answer = step.findings["answer"]
break
@@ -471,7 +478,9 @@ Provide:
if isinstance(questions, list):
questions_dict[i + 1] = questions
- formatted_findings = format_findings(all_findings, final_answer, questions_dict)
+ formatted_findings = format_findings(
+ all_findings, final_answer, questions_dict
+ )
return {
"current_knowledge": final_answer,
@@ -497,7 +506,7 @@ Provide:
# Use LLM to extract location names
prompt = f"""Extract any location names mentioned in this text:
-{results['current_knowledge'][:1000]}
+{results["current_knowledge"][:1000]}
List only location names, one per line:"""
@@ -517,7 +526,7 @@ List only location names, one per line:"""
# Use LLM to extract verified facts
prompt = f"""Extract specific verified facts from this text:
-{results['current_knowledge'][:1000]}
+{results["current_knowledge"][:1000]}
List only confirmed facts, one per line:"""
diff --git a/src/local_deep_research/advanced_search_system/strategies/base_strategy.py b/src/local_deep_research/advanced_search_system/strategies/base_strategy.py
index e8f41180f8..6a27a72b36 100644
--- a/src/local_deep_research/advanced_search_system/strategies/base_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/base_strategy.py
@@ -21,7 +21,9 @@ class BaseSearchStrategy(ABC):
all_links_of_system if all_links_of_system is not None else []
)
- def set_progress_callback(self, callback: Callable[[str, int, dict], None]) -> None:
+ def set_progress_callback(
+ self, callback: Callable[[str, int, dict], None]
+ ) -> None:
"""Set a callback function to receive progress updates."""
self.progress_callback = callback
@@ -62,9 +64,7 @@ class BaseSearchStrategy(ABC):
bool: True if search engine is available, False otherwise
"""
if not hasattr(self, "search") or self.search is None:
- error_msg = (
- "Error: No search engine available. Please check your configuration."
- )
+ error_msg = "Error: No search engine available. Please check your configuration."
self._update_progress(
error_msg,
100,
diff --git a/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py b/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py
index d647be19c7..0ce3bfec6a 100644
--- a/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py
@@ -52,7 +52,9 @@ class EntityKnowledgeGraph:
def __init__(self):
self.entities = {} # name -> EntityCandidate
- self.constraint_evidence = defaultdict(dict) # constraint -> entity -> evidence
+ self.constraint_evidence = defaultdict(
+ dict
+ ) # constraint -> entity -> evidence
self.search_cache = {} # query -> results
def add_entity(self, entity: EntityCandidate):
@@ -103,7 +105,9 @@ class BrowseCompEntityStrategy(BaseSearchStrategy):
5. Uses caching to avoid redundant searches
"""
- def __init__(self, model=None, search=None, all_links_of_system=None, **kwargs):
+ def __init__(
+ self, model=None, search=None, all_links_of_system=None, **kwargs
+ ):
super().__init__(all_links_of_system=all_links_of_system)
# Store model and search engine
@@ -154,7 +158,14 @@ class BrowseCompEntityStrategy(BaseSearchStrategy):
"match",
"competition",
],
- "location": ["place", "location", "city", "country", "region", "area"],
+ "location": [
+ "place",
+ "location",
+ "city",
+ "country",
+ "region",
+ "area",
+ ],
"product": ["product", "item", "device", "software", "app", "tool"],
}
@@ -228,7 +239,9 @@ class BrowseCompEntityStrategy(BaseSearchStrategy):
)
# Search for evidence
- new_entities = await self._search_with_questions(questions, entity_type)
+ new_entities = await self._search_with_questions(
+ questions, entity_type
+ )
# Add to knowledge graph
for entity in new_entities:
@@ -248,7 +261,9 @@ class BrowseCompEntityStrategy(BaseSearchStrategy):
# Early stopping if no progress
if iteration > 3 and not self.knowledge_graph.entities:
- logger.warning("No entities found after 3 iterations, stopping")
+ logger.warning(
+ "No entities found after 3 iterations, stopping"
+ )
break
# Phase 4: Generate final answer
@@ -276,8 +291,12 @@ class BrowseCompEntityStrategy(BaseSearchStrategy):
"entity_type": entity_type,
"entities_discovered": len(self.knowledge_graph.entities),
"iterations": iteration,
- "best_candidate": best_candidate.name if best_candidate else None,
- "confidence": best_candidate.confidence if best_candidate else 0.0,
+ "best_candidate": best_candidate.name
+ if best_candidate
+ else None,
+ "confidence": best_candidate.confidence
+ if best_candidate
+ else 0.0,
"constraint_count": len(constraints),
"cached_searches": len(self.knowledge_graph.search_cache),
}
@@ -285,7 +304,9 @@ class BrowseCompEntityStrategy(BaseSearchStrategy):
return answer, metadata
except Exception as e:
- logger.error(f"Error in BrowseComp entity search: {e}", exc_info=True)
+ logger.error(
+ f"Error in BrowseComp entity search: {e}", exc_info=True
+ )
return f"Search failed: {str(e)}", {"error": str(e)}
def _identify_entity_type(self, query: str) -> str:
@@ -307,7 +328,10 @@ class BrowseCompEntityStrategy(BaseSearchStrategy):
return "entity"
async def _discover_entities(
- self, query: str, entity_type: str, initial_constraints: List[Constraint]
+ self,
+ query: str,
+ entity_type: str,
+ initial_constraints: List[Constraint],
) -> List[EntityCandidate]:
"""Discover initial entity candidates."""
entities = []
@@ -485,7 +509,9 @@ Return only entities that are clearly {entity_type} entities."""
if constraint.value in self.knowledge_graph.constraint_evidence:
if (
entity_name
- in self.knowledge_graph.constraint_evidence[constraint.value]
+ in self.knowledge_graph.constraint_evidence[
+ constraint.value
+ ]
):
evidence = self.knowledge_graph.constraint_evidence[
constraint.value
@@ -493,9 +519,13 @@ Return only entities that are clearly {entity_type} entities."""
score = evidence.get("score", 0.0)
else:
# Gather new evidence
- score = await self._verify_entity_constraint(entity, constraint)
+ score = await self._verify_entity_constraint(
+ entity, constraint
+ )
else:
- score = await self._verify_entity_constraint(entity, constraint)
+ score = await self._verify_entity_constraint(
+ entity, constraint
+ )
constraint_scores[constraint.value] = score
total_score += score * constraint.weight
@@ -527,7 +557,9 @@ Return only entities that are clearly {entity_type} entities."""
if results:
# Quick verification with LLM
- evidence_text = " ".join([r.get("snippet", "") for r in results[:3]])
+ evidence_text = " ".join(
+ [r.get("snippet", "") for r in results[:3]]
+ )
prompt = f"""Does {entity.name} satisfy this constraint?
@@ -550,7 +582,11 @@ Format: SCORE: X.X | REASON: explanation"""
self.knowledge_graph.add_constraint_evidence(
constraint.value,
entity.name,
- {"score": score, "evidence": evidence_text, "reason": content},
+ {
+ "score": score,
+ "evidence": evidence_text,
+ "reason": content,
+ },
)
return best_score
@@ -575,7 +611,9 @@ Format: SCORE: X.X | REASON: explanation"""
terms.extend(re.findall(r"\b\d+\b", value))
elif constraint.type.value == "LOCATION":
# Extract proper nouns
- terms.extend(re.findall(r"\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*\b", value))
+ terms.extend(
+ re.findall(r"\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*\b", value)
+ )
# Add key descriptive words
words = value.split()
@@ -590,7 +628,9 @@ Format: SCORE: X.X | REASON: explanation"""
return terms[:5] # Limit to avoid overly long queries
- def extract_entity_candidates(self, constraints: List[Constraint]) -> List[str]:
+ def extract_entity_candidates(
+ self, constraints: List[Constraint]
+ ) -> List[str]:
"""
Extract potential entity names using constraint analysis.
Implements progressive entity discovery from improvement strategy.
@@ -617,7 +657,9 @@ Format: SCORE: X.X | REASON: explanation"""
# Remove duplicates and sort by specificity
unique_candidates = list(set(candidates))
- return sorted(unique_candidates, key=self.entity_specificity, reverse=True)
+ return sorted(
+ unique_candidates, key=self.entity_specificity, reverse=True
+ )
def entity_specificity(self, entity: str) -> float:
"""
@@ -661,7 +703,9 @@ Format: SCORE: X.X | REASON: explanation"""
# Convert to EntityCandidate if needed
if not isinstance(candidate, EntityCandidate):
entity = EntityCandidate(
- name=candidate.name if hasattr(candidate, "name") else str(candidate),
+ name=candidate.name
+ if hasattr(candidate, "name")
+ else str(candidate),
entity_type="unknown",
)
else:
@@ -690,7 +734,9 @@ Format: SCORE: X.X | REASON: explanation"""
# Search
results = (
- self.search_engine.run(query) if hasattr(self.search_engine, "run") else []
+ self.search_engine.run(query)
+ if hasattr(self.search_engine, "run")
+ else []
)
# Convert to evidence format
@@ -725,7 +771,8 @@ Format: SCORE: X.X | REASON: explanation"""
)
if entity.properties:
props = ", ".join(
- f"{k}={v}" for k, v in list(entity.properties.items())[:3]
+ f"{k}={v}"
+ for k, v in list(entity.properties.items())[:3]
)
summary_parts.append(f" Properties: {props}")
@@ -785,7 +832,10 @@ Format: SCORE: X.X | REASON: explanation"""
return []
async def _generate_entity_answer(
- self, query: str, best_entity: EntityCandidate, constraints: List[Constraint]
+ self,
+ query: str,
+ best_entity: EntityCandidate,
+ constraints: List[Constraint],
) -> str:
"""Generate answer for the best matching entity."""
constraint_details = []
@@ -800,10 +850,10 @@ Format: SCORE: X.X | REASON: explanation"""
Best matching {best_entity.entity_type}: {best_entity.name}
Overall confidence: {best_entity.confidence:.2%}
-Aliases/Other names: {', '.join(best_entity.aliases[:3]) if best_entity.aliases else 'None found'}
+Aliases/Other names: {", ".join(best_entity.aliases[:3]) if best_entity.aliases else "None found"}
Properties:
-{json.dumps(best_entity.properties, indent=2) if best_entity.properties else 'No properties found'}
+{json.dumps(best_entity.properties, indent=2) if best_entity.properties else "No properties found"}
Constraint satisfaction:
{chr(10).join(constraint_details)}
@@ -864,7 +914,9 @@ Provide a helpful response explaining what was found and why no definitive answe
)
return future.result()
else:
- return loop.run_until_complete(self._analyze_topic_async(query))
+ return loop.run_until_complete(
+ self._analyze_topic_async(query)
+ )
except RuntimeError:
# No event loop running, create new one
return asyncio.run(self._analyze_topic_async(query))
@@ -888,7 +940,9 @@ Provide a helpful response explaining what was found and why no definitive answe
constraint_analyzer = ConstraintAnalyzer()
constraints = constraint_analyzer.analyze_query(query)
- self._update_progress(f"Identified {len(constraints)} constraints", 10)
+ self._update_progress(
+ f"Identified {len(constraints)} constraints", 10
+ )
# Generate initial search questions
question_generator = BrowseCompQuestionGenerator()
@@ -924,14 +978,18 @@ Provide a helpful response explaining what was found and why no definitive answe
iteration += 1
- self._update_progress("Evaluating entities against constraints...", 80)
+ self._update_progress(
+ "Evaluating entities against constraints...", 80
+ )
# Evaluate entities
evaluated_entities = await self._evaluate_entities(constraints)
# Generate final answer
if evaluated_entities:
- best_entity = max(evaluated_entities, key=lambda e: e.confidence)
+ best_entity = max(
+ evaluated_entities, key=lambda e: e.confidence
+ )
if best_entity.confidence > 0.6:
answer = await self._generate_entity_answer(
query, best_entity, constraints
@@ -941,7 +999,9 @@ Provide a helpful response explaining what was found and why no definitive answe
query, evaluated_entities[:3]
)
else:
- answer = "No entities were found matching the specified constraints."
+ answer = (
+ "No entities were found matching the specified constraints."
+ )
self._update_progress("Analysis complete", 100)
@@ -950,10 +1010,13 @@ Provide a helpful response explaining what was found and why no definitive answe
"findings": [answer],
"iterations": iteration + 1,
"questions": {
- f"iteration_{i}": initial_questions for i in range(iteration + 1)
+ f"iteration_{i}": initial_questions
+ for i in range(iteration + 1)
},
"entities_found": len(evaluated_entities),
- "confidence": best_entity.confidence if evaluated_entities else 0.0,
+ "confidence": best_entity.confidence
+ if evaluated_entities
+ else 0.0,
"strategy": "browsecomp_entity",
}
diff --git a/src/local_deep_research/advanced_search_system/strategies/browsecomp_optimized_strategy.py b/src/local_deep_research/advanced_search_system/strategies/browsecomp_optimized_strategy.py
index 50e603cdac..75165f8949 100644
--- a/src/local_deep_research/advanced_search_system/strategies/browsecomp_optimized_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/browsecomp_optimized_strategy.py
@@ -129,7 +129,8 @@ class BrowseCompOptimizedStrategy(BaseSearchStrategy):
# Progress update
if self.progress_callback:
progress = (
- int((self.iteration / self.max_browsecomp_iterations) * 80) + 10
+ int((self.iteration / self.max_browsecomp_iterations) * 80)
+ + 10
)
self.progress_callback(
f"Iteration {self.iteration}: {len(self.candidates)} candidates, {len(self.confirmed_info)} confirmed facts",
@@ -150,7 +151,9 @@ class BrowseCompOptimizedStrategy(BaseSearchStrategy):
break
# Execute search
- logger.info(f"Iteration {self.iteration}: Searching for '{search_query}'")
+ logger.info(
+ f"Iteration {self.iteration}: Searching for '{search_query}'"
+ )
search_results = self._execute_search(search_query)
# Process results
@@ -289,9 +292,7 @@ ALL_CLUES_SUMMARY:
+ clues.name_clues
+ clues.incident_clues
+ clues.comparison_clues
- )[
- :5
- ] # Top 5 most important
+ )[:5] # Top 5 most important
return clues
@@ -307,16 +308,17 @@ ALL_CLUES_SUMMARY:
if unverified_clues:
# Pick the most specific unverified clue
if any(
- "fell" in clue or "accident" in clue for clue in unverified_clues
+ "fell" in clue or "accident" in clue
+ for clue in unverified_clues
):
- return f'{top_candidate["name"]} accident fall death {" ".join(self.query_clues.temporal_clues[:1])}'
+ return f"{top_candidate['name']} accident fall death {' '.join(self.query_clues.temporal_clues[:1])}"
elif any(
"search and rescue" in clue.lower() or "sar" in clue.lower()
for clue in unverified_clues
):
- return f'{top_candidate["name"]} search and rescue incidents 2014 statistics'
+ return f"{top_candidate['name']} search and rescue incidents 2014 statistics"
elif any("84.5" in clue for clue in unverified_clues):
- return f'{top_candidate["name"]} 2014 search rescue statistics Grand Canyon 2022 comparison'
+ return f"{top_candidate['name']} 2014 search rescue statistics Grand Canyon 2022 comparison"
# Initial searches - combine multiple clues
if self.iteration <= 3:
@@ -347,8 +349,14 @@ ALL_CLUES_SUMMARY:
# Try different clue combinations
combinations = [
(self.query_clues.location_clues, self.query_clues.name_clues),
- (self.query_clues.temporal_clues, self.query_clues.incident_clues),
- (self.query_clues.numerical_clues, self.query_clues.location_clues),
+ (
+ self.query_clues.temporal_clues,
+ self.query_clues.incident_clues,
+ ),
+ (
+ self.query_clues.numerical_clues,
+ self.query_clues.location_clues,
+ ),
(self.query_clues.name_clues, self.query_clues.incident_clues),
]
@@ -377,7 +385,9 @@ ALL_CLUES_SUMMARY:
# Default - use remaining clues
all_unused = [
- c for c in self.query_clues.all_clues if c not in self.search_history
+ c
+ for c in self.query_clues.all_clues
+ if c not in self.search_history
]
if all_unused:
return all_unused[0]
@@ -400,7 +410,9 @@ ALL_CLUES_SUMMARY:
)
source_strategy.max_iterations = self.source_max_iterations
- source_strategy.questions_per_iteration = self.source_questions_per_iteration
+ source_strategy.questions_per_iteration = (
+ self.source_questions_per_iteration
+ )
if self.progress_callback:
@@ -416,7 +428,9 @@ ALL_CLUES_SUMMARY:
results = source_strategy.analyze_topic(search_query)
if "questions_by_iteration" in results:
- self.questions_by_iteration.extend(results["questions_by_iteration"])
+ self.questions_by_iteration.extend(
+ results["questions_by_iteration"]
+ )
return results
@@ -480,7 +494,8 @@ ELIMINATED_CANDIDATES:
if current_section == "specific_names":
# Add as potential candidate if not already present
if not any(
- c["name"].lower() == item.lower() for c in self.candidates
+ c["name"].lower() == item.lower()
+ for c in self.candidates
):
self.candidates.append(
{
@@ -539,12 +554,16 @@ ELIMINATED_CANDIDATES:
# Update matched clues for candidates
for candidate in self.candidates:
- candidate["matched_clues"] = self._get_matched_clues(candidate["name"])
+ candidate["matched_clues"] = self._get_matched_clues(
+ candidate["name"]
+ )
# Update confidence based on matched clues
clue_confidence = len(candidate["matched_clues"]) / len(
self.query_clues.all_clues
)
- candidate["confidence"] = (candidate["confidence"] + clue_confidence) / 2
+ candidate["confidence"] = (
+ candidate["confidence"] + clue_confidence
+ ) / 2
# Sort candidates by confidence
self.candidates.sort(key=lambda x: x["confidence"], reverse=True)
@@ -558,12 +577,17 @@ ELIMINATED_CANDIDATES:
# Check name clues
for clue in self.query_clues.name_clues:
- if any(word.lower() in candidate_name.lower() for word in clue.split()):
+ if any(
+ word.lower() in candidate_name.lower() for word in clue.split()
+ ):
matched.append(f"name: {clue}")
# Check location clues
for clue in self.query_clues.location_clues:
- if candidate_name.lower() in self.confirmed_info.get(clue, "").lower():
+ if (
+ candidate_name.lower()
+ in self.confirmed_info.get(clue, "").lower()
+ ):
matched.append(f"location: {clue}")
# Check confirmed facts
@@ -602,12 +626,15 @@ ELIMINATED_CANDIDATES:
matched_clues = candidate.get("matched_clues", [])
matched_clue_texts = [
- clue.split(": ", 1)[1] if ": " in clue else clue for clue in matched_clues
+ clue.split(": ", 1)[1] if ": " in clue else clue
+ for clue in matched_clues
]
unverified = []
for clue in all_clues:
- if not any(clue in matched_text for matched_text in matched_clue_texts):
+ if not any(
+ clue in matched_text for matched_text in matched_clue_texts
+ ):
unverified.append(clue)
return unverified
@@ -644,7 +671,8 @@ ELIMINATED_CANDIDATES:
if self.iteration >= 8:
if len(self.candidates) > 1:
confidence_gap = (
- top_candidate["confidence"] - self.candidates[1]["confidence"]
+ top_candidate["confidence"]
+ - self.candidates[1]["confidence"]
)
if confidence_gap > 0.3: # 30% gap to second place
return True
@@ -694,13 +722,13 @@ Confidence: {{confidence}}%
- Final confidence: {confidence}%
**Top Candidates**:
-{chr(10).join(f"{i+1}. {c['name']} ({c['confidence']:.0%})" for i, c in enumerate(self.candidates[:3]))}
+{chr(10).join(f"{i + 1}. {c['name']} ({c['confidence']:.0%})" for i, c in enumerate(self.candidates[:3]))}
**Confirmed Facts**:
{chr(10).join(f"- {k}: {v}" for k, v in self.confirmed_info.items())}
**Search History**:
-{chr(10).join(f"{i+1}. {q}" for i, q in enumerate(self.search_history))}
+{chr(10).join(f"{i + 1}. {q}" for i, q in enumerate(self.search_history))}
"""
self.findings.append(
diff --git a/src/local_deep_research/advanced_search_system/strategies/concurrent_dual_confidence_strategy.py b/src/local_deep_research/advanced_search_system/strategies/concurrent_dual_confidence_strategy.py
index 82efd2c616..5472fbbcf0 100644
--- a/src/local_deep_research/advanced_search_system/strategies/concurrent_dual_confidence_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/concurrent_dual_confidence_strategy.py
@@ -13,7 +13,7 @@ import concurrent.futures
import threading
import time
from dataclasses import dataclass, field
-from typing import Dict, List, Optional, Set, Tuple
+from typing import List, Optional, Tuple
from loguru import logger
@@ -32,7 +32,9 @@ class SearchState:
remaining_constraints: List[Constraint] = field(default_factory=list)
candidates_lock: threading.Lock = field(default_factory=threading.Lock)
stop_search: threading.Event = field(default_factory=threading.Event)
- evaluation_futures: List[concurrent.futures.Future] = field(default_factory=list)
+ evaluation_futures: List[concurrent.futures.Future] = field(
+ default_factory=list
+ )
class ConcurrentDualConfidenceStrategy(DualConfidenceWithRejectionStrategy):
@@ -89,7 +91,8 @@ class ConcurrentDualConfidenceStrategy(DualConfidenceWithRejectionStrategy):
"""Override to use concurrent search and evaluation."""
# Initialize state
self.state = SearchState(
- remaining_constraints=self.constraint_ranking.copy(), start_time=time.time()
+ remaining_constraints=self.constraint_ranking.copy(),
+ start_time=time.time(),
)
# Classify constraints by difficulty
@@ -110,7 +113,9 @@ class ConcurrentDualConfidenceStrategy(DualConfidenceWithRejectionStrategy):
)[: self.max_candidates]
]
- logger.info(f"Found {len(self.candidates)} candidates after concurrent search")
+ logger.info(
+ f"Found {len(self.candidates)} candidates after concurrent search"
+ )
def _classify_constraint_difficulty(self):
"""Rate constraints by how difficult they are to search for."""
@@ -175,7 +180,10 @@ class ConcurrentDualConfidenceStrategy(DualConfidenceWithRejectionStrategy):
"""Main search loop with concurrent evaluation."""
iteration = 0
- while not self.state.stop_search.is_set() and self.state.remaining_constraints:
+ while (
+ not self.state.stop_search.is_set()
+ and self.state.remaining_constraints
+ ):
iteration += 1
# Build query from current constraints
@@ -246,7 +254,9 @@ class ConcurrentDualConfidenceStrategy(DualConfidenceWithRejectionStrategy):
# Drop hardest constraint if we haven't found enough
if len(self.state.good_candidates) < self.min_good_candidates:
if len(self.state.remaining_constraints) > 1:
- dropped = self.state.remaining_constraints.pop(0) # Remove hardest
+ dropped = self.state.remaining_constraints.pop(
+ 0
+ ) # Remove hardest
logger.info(
f"Dropping constraint: {dropped.value} (difficulty: {getattr(dropped, 'search_difficulty', 0.5):.2f})"
)
@@ -270,7 +280,9 @@ class ConcurrentDualConfidenceStrategy(DualConfidenceWithRejectionStrategy):
terms.append(value)
- return " ".join(terms) # Use space instead of AND for more natural queries
+ return " ".join(
+ terms
+ ) # Use space instead of AND for more natural queries
def _evaluate_candidate_thread(
self, candidate: Candidate
@@ -278,7 +290,9 @@ class ConcurrentDualConfidenceStrategy(DualConfidenceWithRejectionStrategy):
"""Evaluate a candidate in a separate thread."""
try:
thread_name = threading.current_thread().name
- logger.info(f"[{thread_name}] Starting evaluation of {candidate.name}")
+ logger.info(
+ f"[{thread_name}] Starting evaluation of {candidate.name}"
+ )
# Use parent's evaluation with early rejection
score = self._evaluate_candidate_immediately(candidate)
@@ -305,7 +319,9 @@ class ConcurrentDualConfidenceStrategy(DualConfidenceWithRejectionStrategy):
return (candidate, score)
except Exception as e:
- logger.error(f"Error evaluating {candidate.name}: {e}", exc_info=True)
+ logger.error(
+ f"Error evaluating {candidate.name}: {e}", exc_info=True
+ )
return (candidate, 0.0)
def _check_evaluation_results(self):
@@ -316,7 +332,7 @@ class ConcurrentDualConfidenceStrategy(DualConfidenceWithRejectionStrategy):
if future.done():
completed.append(future)
try:
- result = future.result()
+ future.result()
# Result is already processed in the thread
except Exception as e:
logger.error(f"Failed to get future result: {e}")
@@ -342,14 +358,18 @@ class ConcurrentDualConfidenceStrategy(DualConfidenceWithRejectionStrategy):
if num_good >= self.target_candidates:
avg_score = sum(s for _, s in self.state.good_candidates) / num_good
if avg_score >= 0.8:
- logger.info(f"Target reached with high quality (avg: {avg_score:.3f})")
+ logger.info(
+ f"Target reached with high quality (avg: {avg_score:.3f})"
+ )
return True
# 3. Minimum satisfied with exceptional candidates
if num_good >= self.min_good_candidates:
top_score = max(s for _, s in self.state.good_candidates)
if top_score >= self.exceptional_score:
- logger.info(f"Exceptional candidate found (score: {top_score:.3f})")
+ logger.info(
+ f"Exceptional candidate found (score: {top_score:.3f})"
+ )
return True
# 4. Time limit reached
@@ -376,7 +396,9 @@ class ConcurrentDualConfidenceStrategy(DualConfidenceWithRejectionStrategy):
recent_scores = [s for _, s in self.state.good_candidates[-5:]]
score_range = max(recent_scores) - min(recent_scores)
if score_range < self.quality_plateau_threshold:
- logger.info(f"Quality plateau detected (range: {score_range:.3f})")
+ logger.info(
+ f"Quality plateau detected (range: {score_range:.3f})"
+ )
return True
return False
@@ -384,7 +406,9 @@ class ConcurrentDualConfidenceStrategy(DualConfidenceWithRejectionStrategy):
def _is_candidate_evaluated(self, candidate: Candidate) -> bool:
"""Check if we already evaluated this candidate."""
with self.state.candidates_lock:
- return any(c.name == candidate.name for c, _ in self.state.good_candidates)
+ return any(
+ c.name == candidate.name for c, _ in self.state.good_candidates
+ )
def _finalize_evaluations(self):
"""Wait for or cancel remaining evaluations."""
@@ -395,7 +419,8 @@ class ConcurrentDualConfidenceStrategy(DualConfidenceWithRejectionStrategy):
# Give them a short time to complete
wait_time = min(
- 5.0, self.max_search_time - (time.time() - self.state.start_time)
+ 5.0,
+ self.max_search_time - (time.time() - self.state.start_time),
)
if wait_time > 0:
concurrent.futures.wait(
diff --git a/src/local_deep_research/advanced_search_system/strategies/constrained_search_strategy.py b/src/local_deep_research/advanced_search_system/strategies/constrained_search_strategy.py
index 4ce41d4aad..ebe004fc26 100644
--- a/src/local_deep_research/advanced_search_system/strategies/constrained_search_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/constrained_search_strategy.py
@@ -8,24 +8,17 @@ This strategy mimics human problem-solving by:
4. Narrowing down the candidate pool step by step
"""
-import math
-from dataclasses import dataclass, field
from datetime import datetime
-from typing import Any, Dict, List, Optional, Set, Tuple
+from typing import Any, Dict, List
from langchain_core.language_models import BaseChatModel
from loguru import logger
-from ...utilities.search_utilities import format_findings, remove_think_tags
+from ...utilities.search_utilities import remove_think_tags
from ..candidates.base_candidate import Candidate
from ..constraints.base_constraint import Constraint, ConstraintType
-from ..constraints.constraint_analyzer import ConstraintAnalyzer
from ..evidence.base_evidence import Evidence, EvidenceType
-from ..evidence.evaluator import EvidenceEvaluator
-from ..findings.repository import FindingsRepository
-from .base_strategy import BaseSearchStrategy
from .evidence_based_strategy import EvidenceBasedStrategy
-from .source_based_strategy import SourceBasedSearchStrategy
class ConstrainedSearchStrategy(EvidenceBasedStrategy):
@@ -99,7 +92,7 @@ class ConstrainedSearchStrategy(EvidenceBasedStrategy):
if self.progress_callback:
ranking_summary = ", ".join(
[
- f"{i+1}. {c.description[:30]}..."
+ f"{i + 1}. {c.description[:30]}..."
for i, c in enumerate(self.constraint_ranking[:3])
]
)
@@ -110,7 +103,8 @@ class ConstrainedSearchStrategy(EvidenceBasedStrategy):
"phase": "constraint_ranking",
"constraint_count": len(self.constraints),
"ranking": [
- (c.description, c.type.value) for c in self.constraint_ranking
+ (c.description, c.type.value)
+ for c in self.constraint_ranking
],
},
)
@@ -152,7 +146,9 @@ class ConstrainedSearchStrategy(EvidenceBasedStrategy):
"timestamp": self._get_timestamp(),
"metadata": {
"total_searches": (
- len(self.search_history) if hasattr(self, "search_history") else 0
+ len(self.search_history)
+ if hasattr(self, "search_history")
+ else 0
),
"final_candidates": len(self.candidates),
"constraints_used": len(self.constraints),
@@ -198,7 +194,9 @@ class ConstrainedSearchStrategy(EvidenceBasedStrategy):
restrictiveness_scores.append((constraint, score))
# Sort by score (highest first)
- ranked = sorted(restrictiveness_scores, key=lambda x: x[1], reverse=True)
+ ranked = sorted(
+ restrictiveness_scores, key=lambda x: x[1], reverse=True
+ )
return [constraint for constraint, _ in ranked]
def _progressive_constraint_search(self):
@@ -226,7 +224,9 @@ class ConstrainedSearchStrategy(EvidenceBasedStrategy):
if stage == 0:
# First stage - find initial candidates
- current_candidates = self._search_with_single_constraint(constraint)
+ current_candidates = self._search_with_single_constraint(
+ constraint
+ )
else:
# Subsequent stages - filter existing candidates
current_candidates = self._filter_candidates_with_constraint(
@@ -237,13 +237,14 @@ class ConstrainedSearchStrategy(EvidenceBasedStrategy):
self.stage_candidates[stage] = current_candidates.copy()
if self.progress_callback:
- candidate_names = ", ".join([c.name for c in current_candidates[:3]])
+ candidate_names = ", ".join(
+ [c.name for c in current_candidates[:3]]
+ )
more = (
- f" (+{len(current_candidates)-3})"
+ f" (+{len(current_candidates) - 3})"
if len(current_candidates) > 3
else ""
)
- status = "found" if current_candidates else "no matches"
change = len(current_candidates) - len(
self.stage_candidates.get(stage - 1, [])
)
@@ -293,7 +294,9 @@ class ConstrainedSearchStrategy(EvidenceBasedStrategy):
self.candidates = current_candidates[: self.candidate_limit]
- def _search_with_single_constraint(self, constraint: Constraint) -> List[Candidate]:
+ def _search_with_single_constraint(
+ self, constraint: Constraint
+ ) -> List[Candidate]:
"""Search for candidates using a single constraint."""
candidates = []
@@ -313,7 +316,7 @@ class ConstrainedSearchStrategy(EvidenceBasedStrategy):
if self.progress_callback:
# Show query and what we're looking for
self.progress_callback(
- f"Q{i+1}/{min(20, len(queries))}: '{query}' | Found: {len(candidates)} candidates",
+ f"Q{i + 1}/{min(20, len(queries))}: '{query}' | Found: {len(candidates)} candidates",
None,
{
"phase": "constraint_search",
@@ -323,7 +326,7 @@ class ConstrainedSearchStrategy(EvidenceBasedStrategy):
"constraint_type": constraint.type.value,
"constraint_value": constraint.value,
"candidates_so_far": len(candidates),
- "search_context": f"Stage {getattr(self, 'current_stage', 0)+1}: {constraint.value}",
+ "search_context": f"Stage {getattr(self, 'current_stage', 0) + 1}: {constraint.value}",
},
)
@@ -331,12 +334,16 @@ class ConstrainedSearchStrategy(EvidenceBasedStrategy):
# Validate search results before extraction
if self._validate_search_results(results, constraint):
- extracted = self._extract_relevant_candidates(results, constraint)
+ extracted = self._extract_relevant_candidates(
+ results, constraint
+ )
candidates.extend(extracted)
# Track stage information in search history
if self.search_history:
- self.search_history[-1]["stage"] = getattr(self, "current_stage", 0)
+ self.search_history[-1]["stage"] = getattr(
+ self, "current_stage", 0
+ )
self.search_history[-1]["results_count"] = len(extracted)
self.search_history[-1]["results_preview"] = results.get(
"current_knowledge", ""
@@ -503,7 +510,9 @@ class ConstrainedSearchStrategy(EvidenceBasedStrategy):
results = self._execute_search(query)
# Quick evidence check
- evidence = self._quick_evidence_check(results, candidate, constraint)
+ evidence = self._quick_evidence_check(
+ results, candidate, constraint
+ )
if evidence.confidence >= 0.5: # Lower threshold for filtering
candidate.add_evidence(constraint.id, evidence)
@@ -597,7 +606,9 @@ Return one {entity_type} name per line. Only include names that could satisfy th
]
# Check if it's meta-commentary
- is_meta = any(pattern in name.lower() for pattern in exclude_patterns)
+ is_meta = any(
+ pattern in name.lower() for pattern in exclude_patterns
+ )
is_too_long = (
len(name.split()) > 10
) # Very long strings are usually explanations
@@ -610,11 +621,11 @@ Return one {entity_type} name per line. Only include names that could satisfy th
or any(c.isupper() for c in name) # Has capitals
or any(c.isdigit() for c in name) # Contains numbers
or any(
- c in name for c in ["-", "&", "/", ":", "(", ")", '"', "'"]
+ c in name
+ for c in ["-", "&", "/", ":", "(", ")", '"', "'"]
) # Special chars
or len(name.split()) <= 6
): # Reasonable length phrases
-
candidate = Candidate(name=name)
candidates.append(candidate)
seen_names.add(normalized_name)
@@ -624,7 +635,9 @@ Return one {entity_type} name per line. Only include names that could satisfy th
f"Extracted {len(candidates)} candidates for constraint: {constraint.description}"
)
if candidates:
- logger.debug(f"Sample candidates: {[c.name for c in candidates[:5]]}")
+ logger.debug(
+ f"Sample candidates: {[c.name for c in candidates[:5]]}"
+ )
return candidates[:50] # Limit per search
@@ -708,16 +721,19 @@ Return one {entity_type} name per line. Only include names that could satisfy th
title = result.get("title", "").lower()
snippet = result.get("snippet", "").lower()
- if (candidate_lower in title or candidate_lower in snippet) and (
- value_lower in title or value_lower in snippet
- ):
+ if (
+ candidate_lower in title or candidate_lower in snippet
+ ) and (value_lower in title or value_lower in snippet):
relevant_results += 1
context_quality = min(relevant_results * 0.05, 0.2)
# Calculate final confidence
confidence = (
- name_presence + constraint_presence + co_occurrence + context_quality
+ name_presence
+ + constraint_presence
+ + co_occurrence
+ + context_quality
)
# Apply constraint type weight
@@ -766,7 +782,9 @@ Return one {entity_type} name per line. Only include names that could satisfy th
results = self._execute_search(query)
evidence = self.evidence_evaluator.extract_evidence(
- results.get("current_knowledge", ""), candidate.name, constraint
+ results.get("current_knowledge", ""),
+ candidate.name,
+ constraint,
)
candidate.add_evidence(constraint.id, evidence)
@@ -775,7 +793,9 @@ Return one {entity_type} name per line. Only include names that could satisfy th
self.progress_callback and i < 5
): # Report progress for top candidates
conf_emoji = (
- "✓" if evidence.confidence >= self.evidence_threshold else "○"
+ "✓"
+ if evidence.confidence >= self.evidence_threshold
+ else "○"
)
self.progress_callback(
f"{conf_emoji} {candidate.name} | {constraint.type.value}: {evidence.confidence:.0%}",
@@ -799,7 +819,9 @@ Return one {entity_type} name per line. Only include names that could satisfy th
# Sort by score
self.candidates.sort(key=lambda c: c.score, reverse=True)
- def _deduplicate_candidates(self, candidates: List[Candidate]) -> List[Candidate]:
+ def _deduplicate_candidates(
+ self, candidates: List[Candidate]
+ ) -> List[Candidate]:
"""Remove duplicate candidates."""
seen = {}
unique = []
@@ -814,13 +836,15 @@ Return one {entity_type} name per line. Only include names that could satisfy th
def _format_constraint_analysis(self) -> str:
"""Format initial constraint analysis."""
- analysis = f"**Query Constraint Analysis**\n\n"
+ analysis = "**Query Constraint Analysis**\n\n"
analysis += f"Total constraints identified: {len(self.constraints)}\n\n"
analysis += "**Constraint Ranking (by restrictiveness):**\n"
for i, constraint in enumerate(self.constraint_ranking):
score = self._calculate_restrictiveness_score(constraint)
- analysis += f"{i+1}. [{constraint.type.value}] {constraint.description}\n"
+ analysis += (
+ f"{i + 1}. [{constraint.type.value}] {constraint.description}\n"
+ )
analysis += f" Restrictiveness score: {score}\n"
analysis += f" Value: {constraint.value}\n\n"
@@ -834,13 +858,13 @@ Return one {entity_type} name per line. Only include names that could satisfy th
summary += "**Constraint Processing:**\n"
for i, constraint in enumerate(self.constraint_ranking):
score = self._calculate_restrictiveness_score(constraint)
- summary += f"{i+1}. [{constraint.type.value}] {constraint.value} (score: {score})\n"
+ summary += f"{i + 1}. [{constraint.type.value}] {constraint.value} (score: {score})\n"
# Search progression
summary += "\n**Search Progression:**\n"
if hasattr(self, "stage_candidates"):
for stage, candidates in self.stage_candidates.items():
- summary += f"Stage {stage+1}: {len(candidates)} candidates\n"
+ summary += f"Stage {stage + 1}: {len(candidates)} candidates\n"
# Evidence coverage
summary += "\n**Evidence Coverage:**\n"
@@ -851,14 +875,15 @@ Return one {entity_type} name per line. Only include names that could satisfy th
1
for c in self.constraints
if c.id in candidate.evidence
- and candidate.evidence[c.id].confidence >= self.evidence_threshold
+ and candidate.evidence[c.id].confidence
+ >= self.evidence_threshold
)
- summary += f"{i+1}. {candidate.name}: {evidence_count} evidence, "
+ summary += f"{i + 1}. {candidate.name}: {evidence_count} evidence, "
summary += f"{satisfied}/{len(self.constraints)} constraints\n"
# Search statistics
- summary += f"\n**Search Statistics:**\n"
+ summary += "\n**Search Statistics:**\n"
total_discovered = (
sum(len(c) for c in self.stage_candidates.values())
if hasattr(self, "stage_candidates")
@@ -927,9 +952,9 @@ Return one {entity_type} name per line. Only include names that could satisfy th
for group_name, group_items in grouped.items():
result += f"\n{group_name} ({len(group_items)} items):\n"
for i, candidate in enumerate(group_items[:5]):
- result += f" {i+1}. {candidate.name}\n"
+ result += f" {i + 1}. {candidate.name}\n"
if len(group_items) > 5:
- result += f" ... and {len(group_items)-5} more\n"
+ result += f" ... and {len(group_items) - 5} more\n"
else:
result += "No candidates found for this constraint.\n"
@@ -937,12 +962,16 @@ Return one {entity_type} name per line. Only include names that could satisfy th
if hasattr(self, "search_history") and candidates:
result += "\n**Sample Search Results:**\n"
recent_searches = [
- s for s in self.search_history[-3:] if s.get("stage", -1) == stage
+ s
+ for s in self.search_history[-3:]
+ if s.get("stage", -1) == stage
]
for search in recent_searches[:2]:
result += f"- Query: '{search.get('query', '')}'\n"
if "results_preview" in search:
- result += f" Preview: {search['results_preview'][:100]}...\n"
+ result += (
+ f" Preview: {search['results_preview'][:100]}...\n"
+ )
return result
@@ -976,11 +1005,15 @@ Return one {entity_type} name per line. Only include names that could satisfy th
for item in group_items[:3]:
summary += f" • {item.name}\n"
if len(group_items) > 3:
- summary += f" ... and {len(group_items)-3} more\n"
+ summary += (
+ f" ... and {len(group_items) - 3} more\n"
+ )
prev_count = count
- summary += f"\n**Final Result: {len(self.candidates)} candidates selected**\n"
+ summary += (
+ f"\n**Final Result: {len(self.candidates)} candidates selected**\n"
+ )
return summary
@@ -989,15 +1022,19 @@ Return one {entity_type} name per line. Only include names that could satisfy th
summary = "**Evidence Gathering Summary**\n\n"
for i, candidate in enumerate(self.candidates[:5]):
- summary += f"**{i+1}. {candidate.name}**\n"
+ summary += f"**{i + 1}. {candidate.name}**\n"
for constraint in self.constraints:
evidence = candidate.evidence.get(constraint.id)
if evidence:
conf_str = f"{evidence.confidence:.0%}"
- summary += f" • {constraint.description[:40]}...: {conf_str}\n"
+ summary += (
+ f" • {constraint.description[:40]}...: {conf_str}\n"
+ )
else:
- summary += f" • {constraint.description[:40]}...: No evidence\n"
+ summary += (
+ f" • {constraint.description[:40]}...: No evidence\n"
+ )
summary += f" Overall Score: {candidate.score:.2f}\n\n"
@@ -1144,13 +1181,15 @@ Return one {entity_type} name per line. Only include names that could satisfy th
content = result.get("content", "")
url = result.get("link", result.get("url", ""))
- content_parts.append(f"Result {i+1}: {title}")
+ content_parts.append(f"Result {i + 1}: {title}")
if url:
content_parts.append(f"URL: {url}")
if snippet:
content_parts.append(f"Snippet: {snippet}")
if content and content != snippet:
- content_parts.append(f"Content preview: {content[:300]}...")
+ content_parts.append(
+ f"Content preview: {content[:300]}..."
+ )
content_parts.append("") # Empty line between results
current_knowledge = "\n".join(content_parts)
@@ -1172,7 +1211,9 @@ Return one {entity_type} name per line. Only include names that could satisfy th
"search_results": [],
}
- def _validate_search_results(self, results: Dict, constraint: Constraint) -> bool:
+ def _validate_search_results(
+ self, results: Dict, constraint: Constraint
+ ) -> bool:
"""Validate that search results contain relevant information."""
if not results:
return False
@@ -1210,7 +1251,9 @@ Return one {entity_type} name per line. Only include names that could satisfy th
term_found = any(term in content_lower for term in relevant_terms)
if not term_found:
- logger.debug("No relevant TV/show terms found for statistic constraint")
+ logger.debug(
+ "No relevant TV/show terms found for statistic constraint"
+ )
return False
else:
# Check for relevance to constraint using key terms
@@ -1218,7 +1261,8 @@ Return one {entity_type} name per line. Only include names that could satisfy th
term
for term in constraint.value.lower().split()
if len(term) > 2
- and term not in ["the", "and", "with", "for", "had", "his", "her"]
+ and term
+ not in ["the", "and", "with", "for", "had", "his", "her"]
]
content_lower = content.lower()
@@ -1231,7 +1275,9 @@ Return one {entity_type} name per line. Only include names that could satisfy th
# Require at least one term match
if relevance_ratio < 0.2:
- logger.debug(f"Low relevance: {relevance_ratio:.0%} term matches")
+ logger.debug(
+ f"Low relevance: {relevance_ratio:.0%} term matches"
+ )
return False
# Check search results quality
@@ -1271,12 +1317,17 @@ Return one {entity_type} name per line. Only include names that could satisfy th
for keyword in ["country", "nation", "republic", "kingdom"]
):
group = "Countries"
- elif any(keyword in name for keyword in ["city", "town", "village"]):
+ elif any(
+ keyword in name for keyword in ["city", "town", "village"]
+ ):
group = "Cities"
- elif any(keyword in name for keyword in ["year", "century", "decade"]):
+ elif any(
+ keyword in name for keyword in ["year", "century", "decade"]
+ ):
group = "Time Periods"
elif any(
- keyword in name for keyword in ["person", "mr", "ms", "dr", "prof"]
+ keyword in name
+ for keyword in ["person", "mr", "ms", "dr", "prof"]
):
group = "People"
elif any(c.isdigit() for c in name):
@@ -1284,7 +1335,9 @@ Return one {entity_type} name per line. Only include names that could satisfy th
else:
# Default grouping based on first word
first_word = (
- candidate.name.split()[0] if candidate.name.split() else "Other"
+ candidate.name.split()[0]
+ if candidate.name.split()
+ else "Other"
)
group = f"{first_word} Items"
diff --git a/src/local_deep_research/advanced_search_system/strategies/constraint_parallel_strategy.py b/src/local_deep_research/advanced_search_system/strategies/constraint_parallel_strategy.py
index 18df60e984..855a7a2742 100644
--- a/src/local_deep_research/advanced_search_system/strategies/constraint_parallel_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/constraint_parallel_strategy.py
@@ -10,16 +10,15 @@ Key features:
"""
import concurrent.futures
-import re
import threading
import time
from dataclasses import dataclass, field
-from typing import Any, Dict, List, Optional, Set, Tuple, Union
+from typing import Dict, List, Optional, Tuple
from loguru import logger
from ..candidates.base_candidate import Candidate
-from ..constraints.base_constraint import Constraint, ConstraintType
+from ..constraints.base_constraint import Constraint
from .dual_confidence_with_rejection import DualConfidenceWithRejectionStrategy
@@ -28,13 +27,19 @@ class ConstraintSearchState:
"""Tracks the state of parallel constraint-specific searches."""
all_candidates: List[Candidate] = field(default_factory=list)
- evaluated_candidates: List[Tuple[Candidate, float]] = field(default_factory=list)
+ evaluated_candidates: List[Tuple[Candidate, float]] = field(
+ default_factory=list
+ )
total_evaluated: int = 0
start_time: float = field(default_factory=time.time)
- constraint_searches: Dict[str, List[Candidate]] = field(default_factory=dict)
+ constraint_searches: Dict[str, List[Candidate]] = field(
+ default_factory=dict
+ )
candidates_lock: threading.Lock = field(default_factory=threading.Lock)
stop_search: threading.Event = field(default_factory=threading.Event)
- evaluation_futures: List[concurrent.futures.Future] = field(default_factory=list)
+ evaluation_futures: List[concurrent.futures.Future] = field(
+ default_factory=list
+ )
entity_type: str = "unknown entity"
@@ -111,7 +116,10 @@ class ConstraintParallelStrategy(DualConfidenceWithRejectionStrategy):
self.progress_callback(
f"Starting parallel searches for {self.state.entity_type}",
10,
- {"phase": "entity_detection", "entity_type": self.state.entity_type},
+ {
+ "phase": "entity_detection",
+ "entity_type": self.state.entity_type,
+ },
)
# Start parallel constraint searches with concurrent evaluation
@@ -126,7 +134,9 @@ class ConstraintParallelStrategy(DualConfidenceWithRejectionStrategy):
self.candidates = [
c
for c, _ in sorted(
- self.state.evaluated_candidates, key=lambda x: x[1], reverse=True
+ self.state.evaluated_candidates,
+ key=lambda x: x[1],
+ reverse=True,
)[: self.max_candidates]
]
@@ -137,7 +147,9 @@ class ConstraintParallelStrategy(DualConfidenceWithRejectionStrategy):
def _detect_entity_type(self) -> str:
"""Use LLM to detect what type of entity we're searching for."""
# Build context from constraints
- constraint_text = "\n".join([f"- {c.value}" for c in self.constraint_ranking])
+ constraint_text = "\n".join(
+ [f"- {c.value}" for c in self.constraint_ranking]
+ )
prompt = f"""
Analyze these search constraints and determine what type of entity is being searched for:
@@ -179,12 +191,15 @@ class ConstraintParallelStrategy(DualConfidenceWithRejectionStrategy):
break
logger.info(
- f"Scheduling search for constraint {i+1}/{len(self.constraint_ranking)}: {constraint.value}"
+ f"Scheduling search for constraint {i + 1}/{len(self.constraint_ranking)}: {constraint.value}"
)
# Submit search task
future = self.search_executor.submit(
- self._run_constraint_search, constraint, i, len(self.constraint_ranking)
+ self._run_constraint_search,
+ constraint,
+ i,
+ len(self.constraint_ranking),
)
search_futures[future] = constraint
@@ -211,7 +226,9 @@ class ConstraintParallelStrategy(DualConfidenceWithRejectionStrategy):
self._submit_candidates_for_evaluation(candidates)
except Exception as e:
- logger.error(f"Search failed for constraint {constraint.value}: {e}")
+ logger.error(
+ f"Search failed for constraint {constraint.value}: {e}"
+ )
# Wait for evaluations to complete
self._finalize_evaluations()
@@ -226,7 +243,7 @@ class ConstraintParallelStrategy(DualConfidenceWithRejectionStrategy):
if self.progress_callback:
self.progress_callback(
- f"Searching for constraint {index+1}/{total}: {constraint.value[:30]}...",
+ f"Searching for constraint {index + 1}/{total}: {constraint.value[:30]}...",
20 + int(30 * (index / total)),
{
"phase": "constraint_search",
@@ -240,7 +257,9 @@ class ConstraintParallelStrategy(DualConfidenceWithRejectionStrategy):
search_results = self._execute_search(query)
# Extract candidates
- candidates = self._extract_relevant_candidates(search_results, constraint)
+ candidates = self._extract_relevant_candidates(
+ search_results, constraint
+ )
logger.info(
f"Found {len(candidates)} candidates for constraint: {constraint.value[:30]}..."
@@ -307,7 +326,9 @@ class ConstraintParallelStrategy(DualConfidenceWithRejectionStrategy):
"""Evaluate a candidate in a separate thread."""
try:
thread_name = threading.current_thread().name
- logger.info(f"[{thread_name}] Starting evaluation of {candidate.name}")
+ logger.info(
+ f"[{thread_name}] Starting evaluation of {candidate.name}"
+ )
# FIRST CHECK: Verify that candidate matches the expected entity type
entity_match_score = self._verify_entity_type_match(candidate)
@@ -342,7 +363,9 @@ class ConstraintParallelStrategy(DualConfidenceWithRejectionStrategy):
return (candidate, score)
except Exception as e:
- logger.error(f"Error evaluating {candidate.name}: {e}", exc_info=True)
+ logger.error(
+ f"Error evaluating {candidate.name}: {e}", exc_info=True
+ )
return (candidate, 0.0)
def _verify_entity_type_match(self, candidate: Candidate) -> float:
@@ -388,18 +411,23 @@ class ConstraintParallelStrategy(DualConfidenceWithRejectionStrategy):
)
return score
except (ValueError, IndexError):
- logger.warning(f"Could not parse entity type score from: {response}")
+ logger.warning(
+ f"Could not parse entity type score from: {response}"
+ )
return 0.5 # Default to middle value on parsing error
except Exception as e:
- logger.error(f"Error verifying entity type for {candidate_name}: {e}")
+ logger.error(
+ f"Error verifying entity type for {candidate_name}: {e}"
+ )
return 0.5 # Default to middle value on error
def _is_candidate_evaluated(self, candidate: Candidate) -> bool:
"""Check if we already evaluated this candidate."""
with self.state.candidates_lock:
return any(
- c.name == candidate.name for c, _ in self.state.evaluated_candidates
+ c.name == candidate.name
+ for c, _ in self.state.evaluated_candidates
)
def _should_stop_search(self) -> bool:
@@ -417,16 +445,22 @@ class ConstraintParallelStrategy(DualConfidenceWithRejectionStrategy):
# 2. Target reached with good quality
if num_good >= self.target_candidates:
- avg_score = sum(s for _, s in self.state.evaluated_candidates) / num_good
+ avg_score = (
+ sum(s for _, s in self.state.evaluated_candidates) / num_good
+ )
if avg_score >= 0.8:
- logger.info(f"Target reached with high quality (avg: {avg_score:.3f})")
+ logger.info(
+ f"Target reached with high quality (avg: {avg_score:.3f})"
+ )
return True
# 3. Minimum satisfied with exceptional candidates
if num_good >= self.min_good_candidates:
top_score = max(s for _, s in self.state.evaluated_candidates)
if top_score >= self.exceptional_score:
- logger.info(f"Exceptional candidate found (score: {top_score:.3f})")
+ logger.info(
+ f"Exceptional candidate found (score: {top_score:.3f})"
+ )
return True
# 4. Time limit reached
@@ -445,7 +479,9 @@ class ConstraintParallelStrategy(DualConfidenceWithRejectionStrategy):
recent_scores = [s for _, s in self.state.evaluated_candidates[-5:]]
score_range = max(recent_scores) - min(recent_scores)
if score_range < self.quality_plateau_threshold:
- logger.info(f"Quality plateau detected (range: {score_range:.3f})")
+ logger.info(
+ f"Quality plateau detected (range: {score_range:.3f})"
+ )
return True
return False
@@ -459,7 +495,8 @@ class ConstraintParallelStrategy(DualConfidenceWithRejectionStrategy):
# Give them a short time to complete
wait_time = min(
- 5.0, self.max_search_time - (time.time() - self.state.start_time)
+ 5.0,
+ self.max_search_time - (time.time() - self.state.start_time),
)
if wait_time > 0:
concurrent.futures.wait(
diff --git a/src/local_deep_research/advanced_search_system/strategies/direct_search_strategy.py b/src/local_deep_research/advanced_search_system/strategies/direct_search_strategy.py
index 4db09e923c..b79186ef66 100644
--- a/src/local_deep_research/advanced_search_system/strategies/direct_search_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/direct_search_strategy.py
@@ -13,7 +13,6 @@ from typing import Dict
from ...citation_handler import CitationHandler
from ...config.llm_config import get_llm
from ...config.search_config import get_search
-from ...utilities.db_utils import get_db_setting
from ..filters.cross_engine_filter import CrossEngineFilter
from ..findings.repository import FindingsRepository
from .base_strategy import BaseSearchStrategy
@@ -183,8 +182,10 @@ class DirectSearchStrategy(BaseSearchStrategy):
self.findings_repository.add_documents(documents)
# Format findings
- formatted_findings = self.findings_repository.format_findings_to_text(
- findings, synthesized_content
+ formatted_findings = (
+ self.findings_repository.format_findings_to_text(
+ findings, synthesized_content
+ )
)
except Exception as e:
diff --git a/src/local_deep_research/advanced_search_system/strategies/dual_confidence_strategy.py b/src/local_deep_research/advanced_search_system/strategies/dual_confidence_strategy.py
index 32fa93c816..190b37d859 100644
--- a/src/local_deep_research/advanced_search_system/strategies/dual_confidence_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/dual_confidence_strategy.py
@@ -4,7 +4,7 @@ Enhanced strategy with dual confidence scoring (positive/negative) for better ac
import re
from dataclasses import dataclass
-from typing import Dict, List, Optional, Tuple
+from typing import Dict, List
from loguru import logger
@@ -18,7 +18,9 @@ class ConstraintEvidence:
"""Evidence for a constraint with dual confidence scores."""
positive_confidence: float # How sure we are the constraint IS satisfied
- negative_confidence: float # How sure we are the constraint is NOT satisfied
+ negative_confidence: (
+ float # How sure we are the constraint is NOT satisfied
+ )
uncertainty: float # How uncertain we are (neither positive nor negative)
evidence_text: str
source: str
@@ -56,7 +58,9 @@ class DualConfidenceStrategy(SmartQueryStrategy):
# Convert evidence to dual confidence format
constraint_evidence = []
for evidence in evidence_list:
- dual_evidence = self._analyze_evidence_dual_confidence(evidence, constraint)
+ dual_evidence = self._analyze_evidence_dual_confidence(
+ evidence, constraint
+ )
constraint_evidence.append(dual_evidence)
# Calculate overall score
@@ -201,7 +205,9 @@ UNCERTAINTY: [score]
def _evaluate_candidate_immediately(self, candidate: Candidate) -> float:
"""Enhanced evaluation with detailed constraint scoring."""
try:
- logger.info(f"Evaluating candidate: {candidate.name} with dual confidence")
+ logger.info(
+ f"Evaluating candidate: {candidate.name} with dual confidence"
+ )
total_score = 0.0
constraint_scores = []
@@ -209,7 +215,9 @@ UNCERTAINTY: [score]
for i, constraint in enumerate(self.constraint_ranking):
# Gather evidence
- evidence = self._gather_evidence_for_constraint(candidate, constraint)
+ evidence = self._gather_evidence_for_constraint(
+ candidate, constraint
+ )
# Evaluate with dual confidence
score = self._evaluate_evidence(evidence, constraint)
@@ -227,9 +235,9 @@ UNCERTAINTY: [score]
avg_negative = sum(
e.negative_confidence for e in dual_evidence
) / len(dual_evidence)
- avg_uncertainty = sum(e.uncertainty for e in dual_evidence) / len(
- dual_evidence
- )
+ avg_uncertainty = sum(
+ e.uncertainty for e in dual_evidence
+ ) / len(dual_evidence)
detailed_results.append(
{
@@ -241,10 +249,12 @@ UNCERTAINTY: [score]
}
)
- symbol = "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
+ symbol = (
+ "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
+ )
logger.info(
- f"{symbol} {candidate.name} | {constraint.value}: {int(score*100)}% "
- f"(+{int(avg_positive*100)}% -{int(avg_negative*100)}% ?{int(avg_uncertainty*100)}%)"
+ f"{symbol} {candidate.name} | {constraint.value}: {int(score * 100)}% "
+ f"(+{int(avg_positive * 100)}% -{int(avg_negative * 100)}% ?{int(avg_uncertainty * 100)}%)"
)
# Early exit for critical failures with high negative confidence
@@ -257,7 +267,8 @@ UNCERTAINTY: [score]
# Calculate weighted average
if constraint_scores:
weights = [
- c.weight for c in self.constraint_ranking[: len(constraint_scores)]
+ c.weight
+ for c in self.constraint_ranking[: len(constraint_scores)]
]
total_score = sum(
s * w for s, w in zip(constraint_scores, weights)
@@ -279,7 +290,9 @@ UNCERTAINTY: [score]
self.best_score = total_score
self.best_candidate = candidate.name
- logger.info(f"New best: {candidate.name} with {total_score:.2%}")
+ logger.info(
+ f"New best: {candidate.name} with {total_score:.2%}"
+ )
# Check for early stop
if total_score >= self.early_stop_threshold:
@@ -290,7 +303,7 @@ UNCERTAINTY: [score]
if self.progress_callback:
self.progress_callback(
- f"Found answer: {candidate.name} ({int(total_score*100)}% confidence)",
+ f"Found answer: {candidate.name} ({int(total_score * 100)}% confidence)",
95,
{
"phase": "early_stop",
diff --git a/src/local_deep_research/advanced_search_system/strategies/dual_confidence_with_rejection.py b/src/local_deep_research/advanced_search_system/strategies/dual_confidence_with_rejection.py
index a1a6bfdb82..4ac99ffe05 100644
--- a/src/local_deep_research/advanced_search_system/strategies/dual_confidence_with_rejection.py
+++ b/src/local_deep_research/advanced_search_system/strategies/dual_confidence_with_rejection.py
@@ -2,14 +2,10 @@
Enhanced dual confidence strategy with early rejection of candidates.
"""
-import re
-from dataclasses import dataclass
-from typing import Dict, List, Optional, Tuple
-
from loguru import logger
from ..constraint_checking import DualConfidenceChecker
-from .dual_confidence_strategy import ConstraintEvidence, DualConfidenceStrategy
+from .dual_confidence_strategy import DualConfidenceStrategy
class DualConfidenceWithRejectionStrategy(DualConfidenceStrategy):
@@ -44,7 +40,9 @@ class DualConfidenceWithRejectionStrategy(DualConfidenceStrategy):
def _evaluate_candidate_immediately(self, candidate) -> float:
"""Enhanced evaluation with early rejection based on negative evidence."""
try:
- logger.info(f"Evaluating candidate: {candidate.name} with early rejection")
+ logger.info(
+ f"Evaluating candidate: {candidate.name} with early rejection"
+ )
total_score = 0.0
constraint_scores = []
@@ -52,7 +50,9 @@ class DualConfidenceWithRejectionStrategy(DualConfidenceStrategy):
for i, constraint in enumerate(self.constraint_ranking):
# Gather evidence for this constraint
- evidence = self._gather_evidence_for_constraint(candidate, constraint)
+ evidence = self._gather_evidence_for_constraint(
+ candidate, constraint
+ )
if evidence:
# Analyze evidence with dual confidence
@@ -68,9 +68,9 @@ class DualConfidenceWithRejectionStrategy(DualConfidenceStrategy):
avg_negative = sum(
e.negative_confidence for e in dual_evidence
) / len(dual_evidence)
- avg_uncertainty = sum(e.uncertainty for e in dual_evidence) / len(
- dual_evidence
- )
+ avg_uncertainty = sum(
+ e.uncertainty for e in dual_evidence
+ ) / len(dual_evidence)
# EARLY REJECTION LOGIC
# Reject if negative evidence is above 25% - simplified approach
@@ -107,16 +107,18 @@ class DualConfidenceWithRejectionStrategy(DualConfidenceStrategy):
)
# Visual feedback
- symbol = "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
+ symbol = (
+ "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
+ )
logger.info(
- f"{symbol} {candidate.name} | {constraint.value}: {int(score*100)}% "
- f"(+{int(avg_positive*100)}% -{int(avg_negative*100)}% ?{int(avg_uncertainty*100)}%)"
+ f"{symbol} {candidate.name} | {constraint.value}: {int(score * 100)}% "
+ f"(+{int(avg_positive * 100)}% -{int(avg_negative * 100)}% ?{int(avg_uncertainty * 100)}%)"
)
# Skip remaining constraints if this one failed badly
if score < 0.2 and constraint.weight > 0.5:
logger.info(
- f"⚠️ Skipping remaining constraints due to poor score on important constraint"
+ "⚠️ Skipping remaining constraints due to poor score on important constraint"
)
break
else:
@@ -130,7 +132,8 @@ class DualConfidenceWithRejectionStrategy(DualConfidenceStrategy):
# Calculate weighted average
if constraint_scores:
weights = [
- c.weight for c in self.constraint_ranking[: len(constraint_scores)]
+ c.weight
+ for c in self.constraint_ranking[: len(constraint_scores)]
]
total_score = sum(
s * w for s, w in zip(constraint_scores, weights)
@@ -158,7 +161,9 @@ class DualConfidenceWithRejectionStrategy(DualConfidenceStrategy):
if total_score > self.best_score:
self.best_score = total_score
self.best_candidate = candidate
- logger.info(f"New best: {candidate.name} with {total_score:.2%}")
+ logger.info(
+ f"New best: {candidate.name} with {total_score:.2%}"
+ )
# Check for early stop
if total_score >= self.early_stop_threshold:
diff --git a/src/local_deep_research/advanced_search_system/strategies/early_stop_constrained_strategy.py b/src/local_deep_research/advanced_search_system/strategies/early_stop_constrained_strategy.py
index e3ca97347b..304c0bfac4 100644
--- a/src/local_deep_research/advanced_search_system/strategies/early_stop_constrained_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/early_stop_constrained_strategy.py
@@ -5,9 +5,7 @@ and stops when finding a very high confidence match.
import concurrent.futures
import threading
-import time
-from dataclasses import dataclass
-from typing import Dict, List, Optional
+from typing import Dict, List
from loguru import logger
@@ -79,7 +77,8 @@ class EarlyStopConstrainedStrategy(ParallelConstrainedStrategy):
if candidate.name not in self.evaluating_candidates:
self.evaluating_candidates.add(candidate.name)
eval_future = executor.submit(
- self._evaluate_candidate_immediately, candidate
+ self._evaluate_candidate_immediately,
+ candidate,
)
evaluation_futures.append(eval_future)
@@ -118,7 +117,9 @@ class EarlyStopConstrainedStrategy(ParallelConstrainedStrategy):
for constraint in self.constraint_ranking:
# Get evidence for this constraint
- evidence = self._gather_evidence_for_constraint(candidate, constraint)
+ evidence = self._gather_evidence_for_constraint(
+ candidate, constraint
+ )
score = self._evaluate_evidence(evidence, constraint)
constraint_scores.append(score)
@@ -126,7 +127,7 @@ class EarlyStopConstrainedStrategy(ParallelConstrainedStrategy):
if self.progress_callback:
symbol = "✓" if score >= 0.8 else "○"
self.progress_callback(
- f"{symbol} {candidate.name} | {constraint.type.value}: {int(score*100)}%",
+ f"{symbol} {candidate.name} | {constraint.type.value}: {int(score * 100)}%",
None,
{
"phase": "immediate_evaluation",
@@ -168,7 +169,7 @@ class EarlyStopConstrainedStrategy(ParallelConstrainedStrategy):
if self.progress_callback:
self.progress_callback(
- f"Found answer: {candidate.name} ({int(total_score*100)}% confidence)",
+ f"Found answer: {candidate.name} ({int(total_score * 100)}% confidence)",
95,
{
"phase": "early_stop",
@@ -194,7 +195,8 @@ class EarlyStopConstrainedStrategy(ParallelConstrainedStrategy):
logger.info(f"Detected entity type: {self.entity_type}")
while (
- search_iterations < max_search_iterations and not self.found_answer.is_set()
+ search_iterations < max_search_iterations
+ and not self.found_answer.is_set()
):
search_iterations += 1
@@ -309,7 +311,9 @@ class EarlyStopConstrainedStrategy(ParallelConstrainedStrategy):
{
"text": response,
"source": "search_results",
- "confidence": self._extract_confidence_from_response(response),
+ "confidence": self._extract_confidence_from_response(
+ response
+ ),
}
)
except Exception as e:
@@ -338,17 +342,24 @@ class EarlyStopConstrainedStrategy(ParallelConstrainedStrategy):
):
return 0.9
elif any(
- word in response.lower() for word in ["likely", "probably", "appears"]
+ word in response.lower()
+ for word in ["likely", "probably", "appears"]
):
return 0.7
- elif any(word in response.lower() for word in ["possibly", "maybe", "might"]):
+ elif any(
+ word in response.lower() for word in ["possibly", "maybe", "might"]
+ ):
return 0.5
- elif any(word in response.lower() for word in ["unlikely", "doubtful", "not"]):
+ elif any(
+ word in response.lower() for word in ["unlikely", "doubtful", "not"]
+ ):
return 0.3
return 0.5
- def _evaluate_evidence(self, evidence: List, constraint: Constraint) -> float:
+ def _evaluate_evidence(
+ self, evidence: List, constraint: Constraint
+ ) -> float:
"""Evaluate evidence to determine constraint satisfaction score."""
if not evidence:
return 0.0
diff --git a/src/local_deep_research/advanced_search_system/strategies/entity_aware_source_strategy.py b/src/local_deep_research/advanced_search_system/strategies/entity_aware_source_strategy.py
index cab3d0490b..fce3c60fec 100644
--- a/src/local_deep_research/advanced_search_system/strategies/entity_aware_source_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/entity_aware_source_strategy.py
@@ -2,16 +2,9 @@
Entity-aware source-based search strategy for improved entity identification.
"""
-import concurrent.futures
import logging
from typing import Dict
-from ...citation_handler import CitationHandler
-from ...config.llm_config import get_llm
-from ...config.search_config import get_search
-from ...utilities.db_utils import get_db_setting
-from ..filters.cross_engine_filter import CrossEngineFilter
-from ..findings.repository import FindingsRepository
from ..questions.entity_aware_question import EntityAwareQuestionGenerator
from .source_based_strategy import SourceBasedSearchStrategy
@@ -83,14 +76,16 @@ class EntityAwareSourceStrategy(SourceBasedSearchStrategy):
# Get some context around the word
context_start = max(0, j - 2)
context_end = min(len(words), j + 3)
- entity_context = " ".join(words[context_start:context_end])
+ entity_context = " ".join(
+ words[context_start:context_end]
+ )
if entity_context not in entity_mentions:
entity_mentions.append(entity_context)
# Add entity mentions to context if found
if entity_mentions:
context_snippets.append(
- f"\nPotential Entity Mentions:\n"
+ "\nPotential Entity Mentions:\n"
+ "\n".join(f"- {mention}" for mention in entity_mentions[:10])
)
@@ -98,7 +93,9 @@ class EntityAwareSourceStrategy(SourceBasedSearchStrategy):
def analyze_topic(self, query: str) -> Dict:
"""Analyze topic with enhanced entity identification."""
- logger.info(f"Starting entity-aware source-based research on topic: {query}")
+ logger.info(
+ f"Starting entity-aware source-based research on topic: {query}"
+ )
# Detect if this is an entity identification query
entity_keywords = [
@@ -121,7 +118,9 @@ class EntityAwareSourceStrategy(SourceBasedSearchStrategy):
"movie",
]
- is_entity_query = any(keyword in query.lower() for keyword in entity_keywords)
+ is_entity_query = any(
+ keyword in query.lower() for keyword in entity_keywords
+ )
if is_entity_query:
logger.info(
diff --git a/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy.py b/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy.py
index 168036639a..c231b5df81 100644
--- a/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy.py
@@ -5,9 +5,8 @@ This strategy decomposes queries into constraints, finds candidates,
and systematically gathers evidence to score each candidate.
"""
-from dataclasses import dataclass, field
from datetime import datetime
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List
from langchain_core.language_models import BaseChatModel
from loguru import logger
@@ -16,7 +15,6 @@ from ...utilities.search_utilities import format_findings, remove_think_tags
from ..candidates.base_candidate import Candidate
from ..constraints.base_constraint import Constraint, ConstraintType
from ..constraints.constraint_analyzer import ConstraintAnalyzer
-from ..evidence.base_evidence import Evidence, EvidenceType
from ..evidence.evaluator import EvidenceEvaluator
from ..findings.repository import FindingsRepository
from .base_strategy import BaseSearchStrategy
@@ -131,7 +129,8 @@ class EvidenceBasedStrategy(BaseSearchStrategy):
# Step 3: Main evidence-gathering loop
while (
- self.iteration < self.max_iterations and not self._has_sufficient_answer()
+ self.iteration < self.max_iterations
+ and not self._has_sufficient_answer()
):
self.iteration += 1
@@ -159,7 +158,9 @@ class EvidenceBasedStrategy(BaseSearchStrategy):
confidence_level = (
"HIGH"
if top_score >= self.confidence_threshold
- else "MEDIUM" if top_score >= 0.6 else "LOW"
+ else "MEDIUM"
+ if top_score >= 0.6
+ else "LOW"
)
self.progress_callback(
f"Iteration {self.iteration}/{self.max_iterations} - {self._get_iteration_status()} [{confidence_level}]",
@@ -191,8 +192,12 @@ class EvidenceBasedStrategy(BaseSearchStrategy):
"timestamp": self._get_timestamp(),
"metadata": {
"candidates": len(self.candidates),
- "evidence_collected": sum(len(c.evidence) for c in self.candidates),
- "top_score": self.candidates[0].score if self.candidates else 0,
+ "evidence_collected": sum(
+ len(c.evidence) for c in self.candidates
+ ),
+ "top_score": self.candidates[0].score
+ if self.candidates
+ else 0,
},
}
self.findings.append(iteration_finding)
@@ -249,7 +254,9 @@ class EvidenceBasedStrategy(BaseSearchStrategy):
)
# Try first query with distinctive constraints
- search_query = self._create_candidate_search_query(distinctive_constraints)
+ search_query = self._create_candidate_search_query(
+ distinctive_constraints
+ )
if self.progress_callback:
self.progress_callback(
@@ -281,7 +288,9 @@ class EvidenceBasedStrategy(BaseSearchStrategy):
)
results = self._execute_search(search_query)
- candidates = self._extract_candidates_from_results(results, search_query)
+ candidates = self._extract_candidates_from_results(
+ results, search_query
+ )
all_candidates.extend(candidates)
# If no candidates found, try a different approach
@@ -295,15 +304,21 @@ class EvidenceBasedStrategy(BaseSearchStrategy):
# Strategy 2: Focus on name pattern constraints if available
pattern_constraints = [
- c for c in self.constraints if c.type == ConstraintType.NAME_PATTERN
+ c
+ for c in self.constraints
+ if c.type == ConstraintType.NAME_PATTERN
]
location_constraints = [
c for c in self.constraints if c.type == ConstraintType.LOCATION
]
if pattern_constraints or location_constraints:
- combined_constraints = (pattern_constraints + location_constraints)[:3]
- search_query = self._create_candidate_search_query(combined_constraints)
+ combined_constraints = (
+ pattern_constraints + location_constraints
+ )[:3]
+ search_query = self._create_candidate_search_query(
+ combined_constraints
+ )
results = self._execute_search(search_query)
candidates = self._extract_candidates_from_results(
results, search_query
@@ -354,7 +369,9 @@ class EvidenceBasedStrategy(BaseSearchStrategy):
if self.progress_callback:
evidence_msg = f"Gathering evidence for {total_candidates} candidates x {len(self.constraints)} constraints"
if total_candidates == 0:
- evidence_msg = "No candidates to process - skipping evidence gathering"
+ evidence_msg = (
+ "No candidates to process - skipping evidence gathering"
+ )
self.progress_callback(
evidence_msg,
None,
@@ -362,11 +379,14 @@ class EvidenceBasedStrategy(BaseSearchStrategy):
"phase": "evidence_round_start",
"candidates_to_process": total_candidates,
"iteration": self.iteration,
- "total_evidence_needed": total_candidates * len(self.constraints),
+ "total_evidence_needed": total_candidates
+ * len(self.constraints),
},
)
- for i, candidate in enumerate(self.candidates[:5]): # Focus on top candidates
+ for i, candidate in enumerate(
+ self.candidates[:5]
+ ): # Focus on top candidates
unverified = candidate.get_unverified_constraints(self.constraints)
if not unverified:
@@ -397,7 +417,7 @@ class EvidenceBasedStrategy(BaseSearchStrategy):
)
self.progress_callback(
- f"Processing {candidate.name} [{i+1}/{total_candidates}] - verifying {constraint.type.value}",
+ f"Processing {candidate.name} [{i + 1}/{total_candidates}] - verifying {constraint.type.value}",
None,
{
"phase": "evidence_search",
@@ -424,7 +444,9 @@ Return only the search query, no explanation."""
# Fallback to simple query if needed
if not search_query or len(search_query) < 5:
- search_query = f"{candidate.name} {constraint.to_search_terms()}"
+ search_query = (
+ f"{candidate.name} {constraint.to_search_terms()}"
+ )
results = self._execute_search(search_query)
@@ -477,7 +499,10 @@ Return only the search query, no explanation."""
self.progress_callback(
"Scoring candidates based on evidence",
None,
- {"phase": "scoring_start", "candidate_count": len(self.candidates)},
+ {
+ "phase": "scoring_start",
+ "candidate_count": len(self.candidates),
+ },
)
for i, candidate in enumerate(self.candidates):
@@ -495,7 +520,11 @@ Return only the search query, no explanation."""
"new_score": candidate.score,
"evidence_count": len(candidate.evidence),
"satisfied_constraints": len(
- [c for c in self.constraints if c.id in candidate.evidence]
+ [
+ c
+ for c in self.constraints
+ if c.id in candidate.evidence
+ ]
),
"score_change": candidate.score - old_score,
},
@@ -506,7 +535,9 @@ Return only the search query, no explanation."""
# Prune low-scoring candidates
old_count = len(self.candidates)
- min_score = max(0.2, self.candidates[0].score * 0.3) if self.candidates else 0.2
+ min_score = (
+ max(0.2, self.candidates[0].score * 0.3) if self.candidates else 0.2
+ )
self.candidates = [c for c in self.candidates if c.score >= min_score]
# Keep only top candidates
@@ -521,7 +552,9 @@ Return only the search query, no explanation."""
"phase": "pruning_complete",
"candidates_removed": removed,
"min_score_threshold": min_score,
- "top_score": self.candidates[0].score if self.candidates else 0,
+ "top_score": self.candidates[0].score
+ if self.candidates
+ else 0,
"remaining_candidates": [
{"name": c.name, "score": c.score, "rank": i + 1}
for i, c in enumerate(self.candidates[:5])
@@ -539,12 +572,15 @@ Return only the search query, no explanation."""
# Check if top candidate has high score
if top_candidate.score >= self.confidence_threshold:
# Verify it has evidence for all critical constraints
- critical_constraints = [c for c in self.constraints if c.weight >= 0.8]
+ critical_constraints = [
+ c for c in self.constraints if c.weight >= 0.8
+ ]
critical_evidence = [
c.id
for c in critical_constraints
if c.id in top_candidate.evidence
- and top_candidate.evidence[c.id].confidence >= self.evidence_threshold
+ and top_candidate.evidence[c.id].confidence
+ >= self.evidence_threshold
]
if len(critical_evidence) == len(critical_constraints):
@@ -587,13 +623,13 @@ Return only the search query, no explanation."""
(c for c in self.constraints if c.id == constraint_id), None
)
if constraint:
- search_query = (
- f"{candidate.name} {constraint.value} exact verification"
- )
+ search_query = f"{candidate.name} {constraint.value} exact verification"
results = self._execute_search(search_query)
evidence = self.evidence_evaluator.extract_evidence(
- results.get("current_knowledge", ""), candidate.name, constraint
+ results.get("current_knowledge", ""),
+ candidate.name,
+ constraint,
)
# Update if better evidence
@@ -630,7 +666,7 @@ Return only the search query, no explanation."""
if search_results:
content = "\n\n".join(
[
- f"Result {i+1}:\n{result.get('snippet', '')}"
+ f"Result {i + 1}:\n{result.get('snippet', '')}"
for i, result in enumerate(search_results[:10])
]
)
@@ -709,11 +745,15 @@ Return only the search query, no explanation."""
results = source_strategy.analyze_topic(search_query)
if "questions_by_iteration" in results:
- self.questions_by_iteration.extend(results["questions_by_iteration"])
+ self.questions_by_iteration.extend(
+ results["questions_by_iteration"]
+ )
return results
- def _create_candidate_search_query(self, constraints: List[Constraint]) -> str:
+ def _create_candidate_search_query(
+ self, constraints: List[Constraint]
+ ) -> str:
"""Create a search query to find candidates."""
# Use an LLM to create effective search queries from constraints
constraint_descriptions = []
@@ -748,7 +788,9 @@ Return only the search query, no explanation."""
if len(search_query.split()) < 3:
# Combine the most important constraint values
key_terms = []
- for c in sorted(constraints, key=lambda x: x.weight, reverse=True)[:3]:
+ for c in sorted(constraints, key=lambda x: x.weight, reverse=True)[
+ :3
+ ]:
key_terms.append(f'"{c.value}"')
search_query = " AND ".join(key_terms)
@@ -770,7 +812,8 @@ Return only the search query, no explanation."""
# Sort constraints by priority and weight
sorted_constraints = sorted(
- self.constraints, key=lambda c: (priority_order.index(c.type), -c.weight)
+ self.constraints,
+ key=lambda c: (priority_order.index(c.type), -c.weight),
)
# Take top 3 constraints, ensuring we have at least one name/location constraint if available
@@ -783,7 +826,10 @@ Return only the search query, no explanation."""
)
if not has_naming:
for c in sorted_constraints[3:]:
- if c.type in [ConstraintType.NAME_PATTERN, ConstraintType.LOCATION]:
+ if c.type in [
+ ConstraintType.NAME_PATTERN,
+ ConstraintType.LOCATION,
+ ]:
distinctive[-1] = c # Replace the least important
break
@@ -859,7 +905,12 @@ Limit to the 10 most relevant candidates."""
# Basic validation - must be non-empty and reasonable length
if name and 2 < len(name) < 100:
# Additional validation based on entity type
- if entity_type in ["location", "place", "person", "organization"]:
+ if entity_type in [
+ "location",
+ "place",
+ "person",
+ "organization",
+ ]:
# Should start with capital letter for these types
if name[0].isupper():
candidate = Candidate(name=name)
@@ -881,7 +932,9 @@ Limit to the 10 most relevant candidates."""
]
if unused_constraints:
- search_query = self._create_candidate_search_query(unused_constraints[:3])
+ search_query = self._create_candidate_search_query(
+ unused_constraints[:3]
+ )
results = self._execute_search(search_query)
new_candidates = self._extract_candidates_from_results(
results, search_query
@@ -936,7 +989,9 @@ Limit to the 10 most relevant candidates."""
# Calculate overall progress
total_evidence_needed = (
- len(self.candidates[:5]) * len(self.constraints) if self.candidates else 0
+ len(self.candidates[:5]) * len(self.constraints)
+ if self.candidates
+ else 0
)
evidence_collected = sum(len(c.evidence) for c in self.candidates[:5])
evidence_progress = (
@@ -949,7 +1004,7 @@ Limit to the 10 most relevant candidates."""
**Iteration {self.iteration}**
**Top Candidates**:
-{chr(10).join(f"{i+1}. {c.name} (score: {c.score:.0%})" for i, c in enumerate(top_candidates)) if top_candidates else "No candidates found yet"}
+{chr(10).join(f"{i + 1}. {c.name} (score: {c.score:.0%})" for i, c in enumerate(top_candidates)) if top_candidates else "No candidates found yet"}
**Evidence Collection Progress**:
- Total candidates: {len(self.candidates)}
@@ -977,20 +1032,24 @@ Limit to the 10 most relevant candidates."""
if evidence:
summary += f" ✓ {constraint.description}: {evidence.confidence:.0%} confidence\n"
else:
- summary += f" ? {constraint.description}: Searching...\n"
+ summary += (
+ f" ? {constraint.description}: Searching...\n"
+ )
else:
summary += "\nSearching for initial candidates..."
summary += "\nFocus: " + ", ".join(
[c.type.value for c in self.constraints[:3]]
)
- summary += f"\n**Overall Progress**: {self.iteration}/{self.max_iterations} iterations ({self.iteration/self.max_iterations:.0%})"
+ summary += f"\n**Overall Progress**: {self.iteration}/{self.max_iterations} iterations ({self.iteration / self.max_iterations:.0%})"
# Add recent searches
if self.search_history:
recent_searches = self.search_history[-3:]
- summary += f"\n\n**Recent Searches**:\n"
- summary += chr(10).join(f"- {s['query'][:60]}..." for s in recent_searches)
+ summary += "\n\n**Recent Searches**:\n"
+ summary += chr(10).join(
+ f"- {s['query'][:60]}..." for s in recent_searches
+ )
return summary.strip()
@@ -1089,7 +1148,9 @@ Include which constraints were satisfied and which weren't.
for constraint in self.constraints:
evidence = candidate.evidence.get(constraint.id)
if evidence:
- summary += f" - {constraint.description}: {evidence.claim} "
+ summary += (
+ f" - {constraint.description}: {evidence.claim} "
+ )
summary += f"(confidence: {evidence.confidence:.2f}, type: {evidence.type.value})\n"
else:
summary += f" - {constraint.description}: No evidence\n"
@@ -1140,7 +1201,7 @@ Include which constraints were satisfied and which weren't.
- {evidence_summary}
**Top Candidates**:
-{chr(10).join(f"{i+1}. {c.name} (score: {c.score:.0%})" for i, c in enumerate(self.candidates[:3]))}
+{chr(10).join(f"{i + 1}. {c.name} (score: {c.score:.0%})" for i, c in enumerate(self.candidates[:3]))}
{constraint_breakdown}
@@ -1149,11 +1210,11 @@ Include which constraints were satisfied and which weren't.
**Search Strategy**:
- Total searches performed: {len(self.search_history)}
-- Constraint-focused searches: {len([s for s in self.search_history if any(c.description in s['query'] for c in self.constraints)])}
-- Candidate verification searches: {len([s for s in self.search_history if any(c.name in s['query'] for c in self.candidates)])}
+- Constraint-focused searches: {len([s for s in self.search_history if any(c.description in s["query"] for c in self.constraints)])}
+- Candidate verification searches: {len([s for s in self.search_history if any(c.name in s["query"] for c in self.candidates)])}
**Recent Search Queries**:
-{chr(10).join(f"{i+1}. {s['query'][:80]}..." for i, s in enumerate(self.search_history[-5:]))}
+{chr(10).join(f"{i + 1}. {s['query'][:80]}..." for i, s in enumerate(self.search_history[-5:]))}
""".strip()
def _get_timestamp(self) -> str:
diff --git a/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy_v2.py b/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy_v2.py
index 9d41f4cb4a..64bf3005d3 100644
--- a/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy_v2.py
+++ b/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy_v2.py
@@ -8,25 +8,18 @@ This strategy addresses common issues with candidate discovery and evidence gath
4. Source diversity management
"""
-import json
import math
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, Dict, List, Optional, Set, Tuple
from langchain_core.language_models import BaseChatModel
-from loguru import logger
-from ...utilities.search_utilities import format_findings, remove_think_tags
+from ...utilities.search_utilities import remove_think_tags
from ..candidates.base_candidate import Candidate
from ..constraints.base_constraint import Constraint, ConstraintType
-from ..constraints.constraint_analyzer import ConstraintAnalyzer
-from ..evidence.base_evidence import Evidence, EvidenceType
-from ..evidence.evaluator import EvidenceEvaluator
-from ..findings.repository import FindingsRepository
-from .base_strategy import BaseSearchStrategy
+from ..evidence.base_evidence import Evidence
from .evidence_based_strategy import EvidenceBasedStrategy
-from .source_based_strategy import SourceBasedSearchStrategy
@dataclass
@@ -94,8 +87,12 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
self.enable_pattern_learning = enable_pattern_learning
# Pattern learning
- self.query_patterns: Dict[str, QueryPattern] = self._initialize_patterns()
- self.source_profiles: Dict[str, SourceProfile] = self._initialize_sources()
+ self.query_patterns: Dict[str, QueryPattern] = (
+ self._initialize_patterns()
+ )
+ self.source_profiles: Dict[str, SourceProfile] = (
+ self._initialize_sources()
+ )
# Failure tracking
self.failed_queries: Set[str] = set()
@@ -113,7 +110,8 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
constraint_types=[ConstraintType.PROPERTY],
),
"event_show": QueryPattern(
- pattern="TV show {value}", constraint_types=[ConstraintType.EVENT]
+ pattern="TV show {value}",
+ constraint_types=[ConstraintType.EVENT],
),
"statistic_episodes": QueryPattern(
pattern="{value} episodes series",
@@ -123,7 +121,8 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
pattern="{value1} AND {value2}", constraint_types=[]
),
"semantic_expansion": QueryPattern(
- pattern='"{value}" OR "{synonym1}" OR "{synonym2}"', constraint_types=[]
+ pattern='"{value}" OR "{synonym1}" OR "{synonym2}"',
+ constraint_types=[],
),
}
return patterns
@@ -136,7 +135,8 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
specialties=["characters", "properties", "general"],
),
"imdb": SourceProfile(
- source_name="imdb", specialties=["tv_shows", "episodes", "statistics"]
+ source_name="imdb",
+ specialties=["tv_shows", "episodes", "statistics"],
),
"fandom": SourceProfile(
source_name="fandom",
@@ -162,7 +162,10 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
self.progress_callback(
"Enhanced Evidence-Based Strategy initialized - beginning analysis",
1,
- {"phase": "initialization", "strategy": "enhanced_evidence_based"},
+ {
+ "phase": "initialization",
+ "strategy": "enhanced_evidence_based",
+ },
)
# Extract constraints
@@ -203,7 +206,8 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
# Main evidence-gathering loop
while (
- self.iteration < self.max_iterations and not self._has_sufficient_answer()
+ self.iteration < self.max_iterations
+ and not self._has_sufficient_answer()
):
self.iteration += 1
@@ -223,7 +227,9 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
"max_iterations": self.max_iterations,
"candidates_count": len(self.candidates),
"top_candidate": (
- self.candidates[0].name if self.candidates else "None"
+ self.candidates[0].name
+ if self.candidates
+ else "None"
),
},
)
@@ -236,7 +242,10 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
self.progress_callback(
f"Scoring {len(self.candidates)} candidates based on evidence",
None,
- {"phase": "scoring_start", "candidate_count": len(self.candidates)},
+ {
+ "phase": "scoring_start",
+ "candidate_count": len(self.candidates),
+ },
)
self._score_and_prune_adaptive()
@@ -289,7 +298,9 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
{
"phase": "synthesis_start",
"candidates_evaluated": len(self.candidates),
- "evidence_pieces": sum(len(c.evidence) for c in self.candidates),
+ "evidence_pieces": sum(
+ len(c.evidence) for c in self.candidates
+ ),
},
)
@@ -303,11 +314,15 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
{
"phase": "complete",
"final_answer": (
- top_candidate.name if top_candidate else "Unable to determine"
+ top_candidate.name
+ if top_candidate
+ else "Unable to determine"
),
"confidence": top_candidate.score if top_candidate else 0,
"candidates_evaluated": len(self.candidates),
- "evidence_pieces": sum(len(c.evidence) for c in self.candidates),
+ "evidence_pieces": sum(
+ len(c.evidence) for c in self.candidates
+ ),
"iterations_used": self.iteration,
},
)
@@ -323,18 +338,24 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
("cross", "Cross-constraint", self._cross_constraint_search),
("semantic", "Semantic expansion", self._semantic_expansion_search),
("temporal", "Temporal search", self._temporal_search),
- ("character_db", "Character databases", self._character_database_search),
+ (
+ "character_db",
+ "Character databases",
+ self._character_database_search,
+ ),
("fallback", "Fallback search", self._fallback_search),
]
stage_progress_base = 10
stage_progress_increment = 5
- for i, (stage_name, stage_desc, stage_func) in enumerate(discovery_stages):
+ for i, (stage_name, stage_desc, stage_func) in enumerate(
+ discovery_stages
+ ):
if self.progress_callback:
progress = stage_progress_base + (i * stage_progress_increment)
self.progress_callback(
- f"{stage_desc} search - looking for candidates [{i+1}/5]",
+ f"{stage_desc} search - looking for candidates [{i + 1}/5]",
progress,
{
"phase": f"discovery_{stage_name}",
@@ -377,7 +398,10 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
self._add_unique_candidates(all_candidates)
# If still not enough candidates, try more aggressive discovery
- if len(self.candidates) < self.min_candidates_threshold and all_candidates:
+ if (
+ len(self.candidates) < self.min_candidates_threshold
+ and all_candidates
+ ):
if self.progress_callback:
self.progress_callback(
f"Only {len(self.candidates)} candidates - trying more aggressive search",
@@ -430,8 +454,10 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
)
results = self._execute_adaptive_search(query)
- extracted = self._extract_candidates_with_enhanced_validation(
- results, query
+ extracted = (
+ self._extract_candidates_with_enhanced_validation(
+ results, query
+ )
)
candidates.extend(extracted)
@@ -455,7 +481,7 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
if self.progress_callback:
self.progress_callback(
- f"Focused search: {constraint.description[:40]}... [{i+1}/{len(high_weight_constraints)}]",
+ f"Focused search: {constraint.description[:40]}... [{i + 1}/{len(high_weight_constraints)}]",
None,
{
"phase": "focused_constraint",
@@ -468,12 +494,16 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
for query in queries[:3]: # Limit queries per constraint
if query not in self.failed_queries:
results = self._execute_adaptive_search(query)
- extracted = self._extract_candidates_from_results(results, query)
+ extracted = self._extract_candidates_from_results(
+ results, query
+ )
if extracted:
candidates.extend(extracted)
# Learn from successful query
- self._learn_query_pattern(query, constraint, success=True)
+ self._learn_query_pattern(
+ query, constraint, success=True
+ )
else:
self.failed_queries.add(query)
@@ -515,7 +545,9 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
if query not in self.failed_queries:
results = self._execute_adaptive_search(query)
- extracted = self._extract_candidates_from_results(results, query)
+ extracted = self._extract_candidates_from_results(
+ results, query
+ )
if extracted:
candidates.extend(extracted)
@@ -539,8 +571,10 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
for variation in variations[:3]: # Limit variations
if variation not in self.failed_queries:
results = self._execute_adaptive_search(variation)
- extracted = self._extract_candidates_with_enhanced_validation(
- results, variation
+ extracted = (
+ self._extract_candidates_with_enhanced_validation(
+ results, variation
+ )
)
if extracted:
@@ -560,7 +594,9 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
for query in relaxed_queries[:3]:
if query not in self.failed_queries:
results = self._execute_adaptive_search(query)
- extracted = self._extract_candidates_from_results(results, query)
+ extracted = self._extract_candidates_from_results(
+ results, query
+ )
candidates.extend(extracted)
return candidates
@@ -589,7 +625,7 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
if self.progress_callback:
self.progress_callback(
- f"Processing {candidate.name} [{i+1}/{min(5, len(self.candidates))}]",
+ f"Processing {candidate.name} [{i + 1}/{min(5, len(self.candidates))}]",
None,
{
"phase": "candidate_evidence",
@@ -599,9 +635,13 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
},
)
- for j, constraint in enumerate(unverified[:2]): # Limit per candidate
+ for j, constraint in enumerate(
+ unverified[:2]
+ ): # Limit per candidate
# Select diverse source
- source = self._select_diverse_source(source_usage, constraint.type)
+ source = self._select_diverse_source(
+ source_usage, constraint.type
+ )
# Generate evidence query
query = self._generate_evidence_query(candidate, constraint)
@@ -624,7 +664,9 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
# Extract and evaluate evidence
evidence = self.evidence_evaluator.extract_evidence(
- results.get("current_knowledge", ""), candidate.name, constraint
+ results.get("current_knowledge", ""),
+ candidate.name,
+ constraint,
)
candidate.add_evidence(constraint.id, evidence)
@@ -655,7 +697,9 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
"phase": "evidence_complete",
"evidence_count": evidence_gathered,
"source_diversity": self._calculate_source_diversity(),
- "sources_used": len([s for s in source_usage.values() if s > 0]),
+ "sources_used": len(
+ [s for s in source_usage.values() if s > 0]
+ ),
},
)
@@ -668,7 +712,8 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
[
p
for p in self.query_patterns.values()
- if constraint.type in p.constraint_types and p.success_rate > 0.3
+ if constraint.type in p.constraint_types
+ and p.success_rate > 0.3
],
key=lambda p: p.success_rate,
reverse=True,
@@ -754,7 +799,9 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
source_usage[selected] = source_usage.get(selected, 0) + 1
return selected
- def _get_specialized_sources(self, constraint_type: ConstraintType) -> List[str]:
+ def _get_specialized_sources(
+ self, constraint_type: ConstraintType
+ ) -> List[str]:
"""Get specialized sources for constraint type."""
specialization_map = {
ConstraintType.PROPERTY: ["fandom", "wikipedia"],
@@ -770,7 +817,9 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
if success:
# Exponential moving average
alpha = 0.3
- pattern.success_rate = alpha * 1.0 + (1 - alpha) * pattern.success_rate
+ pattern.success_rate = (
+ alpha * 1.0 + (1 - alpha) * pattern.success_rate
+ )
else:
pattern.success_rate = (1 - 0.3) * pattern.success_rate
@@ -784,7 +833,9 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
# Update success rate based on confidence
alpha = 0.3
success = 1.0 if confidence >= self.evidence_threshold else 0.0
- profile.success_rate = alpha * success + (1 - alpha) * profile.success_rate
+ profile.success_rate = (
+ alpha * success + (1 - alpha) * profile.success_rate
+ )
def _analyze_constraint_relationships(self):
"""Analyze relationships between constraints."""
@@ -802,7 +853,9 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
+ [constraint1.id]
)
- def _find_related_constraint_pairs(self) -> List[Tuple[Constraint, Constraint]]:
+ def _find_related_constraint_pairs(
+ self,
+ ) -> List[Tuple[Constraint, Constraint]]:
"""Find constraint pairs that might work well together."""
pairs = []
@@ -814,7 +867,8 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
if constraint:
for related_id in related_ids:
related = next(
- (c for c in self.constraints if c.id == related_id), None
+ (c for c in self.constraints if c.id == related_id),
+ None,
)
if related and (constraint, related) not in pairs:
pairs.append((constraint, related))
@@ -839,7 +893,9 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
if not self.source_profiles:
return 0.0
- used_sources = [s for s in self.source_profiles.values() if s.usage_count > 0]
+ used_sources = [
+ s for s in self.source_profiles.values() if s.usage_count > 0
+ ]
if not used_sources:
return 0.0
@@ -873,7 +929,9 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
prompt = f"List 3 synonyms or similar terms for '{term}'. Return only the synonyms, one per line."
response = self.model.invoke(prompt)
content = remove_think_tags(response.content)
- synonyms = [line.strip() for line in content.split("\n") if line.strip()]
+ synonyms = [
+ line.strip() for line in content.split("\n") if line.strip()
+ ]
return synonyms[:3]
except:
return [] # Return empty list on error
@@ -886,13 +944,17 @@ class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
terms2 = set(constraint2.value.lower().split())
return list(terms1.intersection(terms2))
- def _generate_semantic_variations(self, constraint: Constraint) -> List[str]:
+ def _generate_semantic_variations(
+ self, constraint: Constraint
+ ) -> List[str]:
"""Generate semantically similar queries"""
variations = []
# Basic variations based on constraint type
base_value = (
- constraint.value if hasattr(constraint, "value") else constraint.description
+ constraint.value
+ if hasattr(constraint, "value")
+ else constraint.description
)
# Add contextual variations based on type
@@ -1005,7 +1067,9 @@ Return only the search query, no explanation."""
return queries
- def _learn_query_pattern(self, query: str, constraint: Constraint, success: bool):
+ def _learn_query_pattern(
+ self, query: str, constraint: Constraint, success: bool
+ ):
"""Learn from query success/failure."""
if not self.enable_pattern_learning:
return
@@ -1029,13 +1093,23 @@ Return only the search query, no explanation."""
# Strengthen the relationship
if constraint1.id not in self.constraint_relationships:
self.constraint_relationships[constraint1.id] = []
- if constraint2.id not in self.constraint_relationships[constraint1.id]:
- self.constraint_relationships[constraint1.id].append(constraint2.id)
+ if (
+ constraint2.id
+ not in self.constraint_relationships[constraint1.id]
+ ):
+ self.constraint_relationships[constraint1.id].append(
+ constraint2.id
+ )
if constraint2.id not in self.constraint_relationships:
self.constraint_relationships[constraint2.id] = []
- if constraint1.id not in self.constraint_relationships[constraint2.id]:
- self.constraint_relationships[constraint2.id].append(constraint1.id)
+ if (
+ constraint1.id
+ not in self.constraint_relationships[constraint2.id]
+ ):
+ self.constraint_relationships[constraint2.id].append(
+ constraint1.id
+ )
def _wikipedia_search(self) -> List[Candidate]:
"""Search Wikipedia for general information."""
@@ -1052,8 +1126,10 @@ Return only the search query, no explanation."""
for query in queries:
if query not in self.failed_queries:
results = self._execute_adaptive_search(query)
- extracted = self._extract_candidates_with_enhanced_validation(
- results, query
+ extracted = (
+ self._extract_candidates_with_enhanced_validation(
+ results, query
+ )
)
candidates.extend(extracted)
@@ -1082,8 +1158,10 @@ Return only the search query, no explanation."""
if query not in self.failed_queries:
results = self._execute_adaptive_search(query)
- extracted = self._extract_candidates_with_enhanced_validation(
- results, query
+ extracted = (
+ self._extract_candidates_with_enhanced_validation(
+ results, query
+ )
)
candidates.extend(extracted)
@@ -1112,8 +1190,10 @@ Return only the search query, no explanation."""
if query not in self.failed_queries:
results = self._execute_adaptive_search(query)
- extracted = self._extract_candidates_with_enhanced_validation(
- results, query
+ extracted = (
+ self._extract_candidates_with_enhanced_validation(
+ results, query
+ )
)
additional_candidates.extend(extracted)
@@ -1135,7 +1215,9 @@ Return only the search query, no explanation."""
validated = []
for candidate in candidates:
# Basic validation - not too short, not a common word
- if len(candidate.name) > 2 and not self._is_common_word(candidate.name):
+ if len(candidate.name) > 2 and not self._is_common_word(
+ candidate.name
+ ):
validated.append(candidate)
return validated[:15] # Limit per search
@@ -1177,9 +1259,13 @@ Return only the search query, no explanation."""
if self.iteration > self.max_iterations / 2:
# Be more aggressive in later iterations
min_score = (
- max(0.3, self.candidates[0].score * 0.4) if self.candidates else 0.3
+ max(0.3, self.candidates[0].score * 0.4)
+ if self.candidates
+ else 0.3
)
- self.candidates = [c for c in self.candidates if c.score >= min_score]
+ self.candidates = [
+ c for c in self.candidates if c.score >= min_score
+ ]
if self.progress_callback:
pruned = old_count - len(self.candidates)
@@ -1190,7 +1276,9 @@ Return only the search query, no explanation."""
"phase": "scoring_complete",
"candidates_kept": len(self.candidates),
"candidates_pruned": pruned,
- "top_score": self.candidates[0].score if self.candidates else 0,
+ "top_score": self.candidates[0].score
+ if self.candidates
+ else 0,
"min_score_threshold": (
min_score
if self.iteration > self.max_iterations / 2
@@ -1218,12 +1306,15 @@ Return only the search query, no explanation."""
c
for c in self.constraints
if c.id not in top_candidate.evidence
- or top_candidate.evidence[c.id].confidence < self.evidence_threshold
+ or top_candidate.evidence[c.id].confidence
+ < self.evidence_threshold
]
if weak_constraints:
constraint = weak_constraints[0]
- query = self._generate_evidence_query(top_candidate, constraint)
+ query = self._generate_evidence_query(
+ top_candidate, constraint
+ )
# Use specific source
results = self._execute_search_with_source(
diff --git a/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py b/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py
index 097a441b35..99259de824 100644
--- a/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py
@@ -80,7 +80,9 @@ class FocusedIterationStrategy(BaseSearchStrategy):
self.explorer = None
# Use forced answer handler for BrowseComp optimization
- handler_type = "forced_answer" if use_browsecomp_optimization else "standard"
+ handler_type = (
+ "forced_answer" if use_browsecomp_optimization else "standard"
+ )
self.citation_handler = citation_handler or CitationHandler(
self.model, handler_type=handler_type
)
@@ -119,7 +121,9 @@ class FocusedIterationStrategy(BaseSearchStrategy):
try:
# Main iteration loop
for iteration in range(1, self.max_iterations + 1):
- iteration_progress = 10 + (iteration - 1) * (80 / self.max_iterations)
+ iteration_progress = 10 + (iteration - 1) * (
+ 80 / self.max_iterations
+ )
self._update_progress(
f"Iteration {iteration}/{self.max_iterations}",
@@ -142,7 +146,9 @@ class FocusedIterationStrategy(BaseSearchStrategy):
if iteration == 1 and hasattr(
self.question_generator, "extracted_entities"
):
- extracted_entities = self.question_generator.extracted_entities
+ extracted_entities = (
+ self.question_generator.extracted_entities
+ )
else:
# Standard question generation
questions = self.question_generator.generate_questions(
@@ -183,7 +189,9 @@ class FocusedIterationStrategy(BaseSearchStrategy):
# Convert sets to lists for JSON serialization
serializable_entity_coverage = {
k: list(v)
- for k, v in list(search_progress.entity_coverage.items())[:3]
+ for k, v in list(
+ search_progress.entity_coverage.items()
+ )[:3]
}
self._update_progress(
@@ -191,9 +199,12 @@ class FocusedIterationStrategy(BaseSearchStrategy):
iteration_progress,
{
"phase": f"iteration_{iteration}_results",
- "candidates_found": len(search_progress.found_candidates),
+ "candidates_found": len(
+ search_progress.found_candidates
+ ),
"entities_covered": sum(
- len(v) for v in search_progress.entity_coverage.values()
+ len(v)
+ for v in search_progress.entity_coverage.values()
),
"entity_coverage": serializable_entity_coverage, # JSON-serializable version
},
@@ -201,8 +212,10 @@ class FocusedIterationStrategy(BaseSearchStrategy):
# Check if we should generate verification searches
if iteration > 3 and search_progress.found_candidates:
- verification_searches = self.explorer.suggest_next_searches(
- extracted_entities, max_suggestions=2
+ verification_searches = (
+ self.explorer.suggest_next_searches(
+ extracted_entities, max_suggestions=2
+ )
)
if verification_searches:
logger.info(
@@ -210,7 +223,8 @@ class FocusedIterationStrategy(BaseSearchStrategy):
)
self._update_progress(
f"Running {len(verification_searches)} verification searches",
- iteration_progress + (80 / self.max_iterations / 8),
+ iteration_progress
+ + (80 / self.max_iterations / 8),
{
"phase": f"iteration_{iteration}_verification",
"verification_queries": verification_searches,
@@ -225,8 +239,10 @@ class FocusedIterationStrategy(BaseSearchStrategy):
iteration_results.extend(verification_results)
else:
# Simple parallel search (like source-based) with detailed reporting
- iteration_results = self._execute_parallel_searches_with_progress(
- questions, iteration
+ iteration_results = (
+ self._execute_parallel_searches_with_progress(
+ questions, iteration
+ )
)
# Accumulate all results (no filtering!)
@@ -294,8 +310,10 @@ class FocusedIterationStrategy(BaseSearchStrategy):
)
# Format findings
- formatted_findings = self.findings_repository.format_findings_to_text(
- findings, synthesized_content
+ formatted_findings = (
+ self.findings_repository.format_findings_to_text(
+ findings, synthesized_content
+ )
)
self._update_progress(
@@ -317,7 +335,9 @@ class FocusedIterationStrategy(BaseSearchStrategy):
# Add BrowseComp-specific data if available
if self.explorer and hasattr(self.explorer, "progress"):
- result["candidates"] = dict(self.explorer.progress.found_candidates)
+ result["candidates"] = dict(
+ self.explorer.progress.found_candidates
+ )
result["entity_coverage"] = {
k: list(v)
for k, v in self.explorer.progress.entity_coverage.items()
@@ -424,7 +444,8 @@ class FocusedIterationStrategy(BaseSearchStrategy):
max_workers=min(len(queries), 5)
) as executor:
futures = [
- executor.submit(search_question_with_progress, q) for q in queries
+ executor.submit(search_question_with_progress, q)
+ for q in queries
]
total_results_found = 0
@@ -485,12 +506,16 @@ class FocusedIterationStrategy(BaseSearchStrategy):
if extracted_entities := getattr(
self.question_generator, "extracted_entities", {}
):
- total_entities = sum(len(v) for v in extracted_entities.values())
+ total_entities = sum(
+ len(v) for v in extracted_entities.values()
+ )
covered_entities = sum(
len(v) for v in progress.entity_coverage.values()
)
coverage_ratio = (
- covered_entities / total_entities if total_entities > 0 else 0
+ covered_entities / total_entities
+ if total_entities > 0
+ else 0
)
# Continue if coverage is low
diff --git a/src/local_deep_research/advanced_search_system/strategies/improved_evidence_based_strategy.py b/src/local_deep_research/advanced_search_system/strategies/improved_evidence_based_strategy.py
index 7a12a16199..8309a651f9 100644
--- a/src/local_deep_research/advanced_search_system/strategies/improved_evidence_based_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/improved_evidence_based_strategy.py
@@ -10,22 +10,20 @@ Key improvements:
import itertools
from collections import defaultdict
-from dataclasses import dataclass, field
+from dataclasses import dataclass
from datetime import datetime
-from typing import Any, Dict, List, Optional, Set, Tuple
+from typing import Any, Dict, List, Set
from langchain_core.language_models import BaseChatModel
-from loguru import logger
-from ...utilities.search_utilities import format_findings, remove_think_tags
+from ...utilities.search_utilities import remove_think_tags
from ..candidates.base_candidate import Candidate
from ..constraints.base_constraint import Constraint, ConstraintType
from ..constraints.constraint_analyzer import ConstraintAnalyzer
-from ..evidence.base_evidence import Evidence, EvidenceType
+from ..evidence.base_evidence import EvidenceType
from ..evidence.evaluator import EvidenceEvaluator
from ..findings.repository import FindingsRepository
from .base_strategy import BaseSearchStrategy
-from .source_based_strategy import SourceBasedSearchStrategy
@dataclass
@@ -119,7 +117,8 @@ class ImprovedEvidenceBasedStrategy(BaseSearchStrategy):
# Step 3: Main evidence-gathering loop with adaptive search
while (
- self.iteration < self.max_iterations and not self._has_sufficient_answer()
+ self.iteration < self.max_iterations
+ and not self._has_sufficient_answer()
):
self.iteration += 1
@@ -196,7 +195,9 @@ class ImprovedEvidenceBasedStrategy(BaseSearchStrategy):
results = self._execute_tracked_search(
query, constraint_combo, "distinctive"
)
- candidates.extend(self._extract_candidates_with_context(results, query))
+ candidates.extend(
+ self._extract_candidates_with_context(results, query)
+ )
if candidates: # Track successful patterns
self.successful_patterns.append(
@@ -223,8 +224,12 @@ class ImprovedEvidenceBasedStrategy(BaseSearchStrategy):
type_groups[type1][:2], type_groups[type2][:2]
):
query = self._create_cross_constraint_query([c1, c2])
- results = self._execute_tracked_search(query, [c1, c2], "combined")
- candidates.extend(self._extract_candidates_with_context(results, query))
+ results = self._execute_tracked_search(
+ query, [c1, c2], "combined"
+ )
+ candidates.extend(
+ self._extract_candidates_with_context(results, query)
+ )
return candidates
@@ -255,7 +260,9 @@ Return only the queries, one per line.
results = self._execute_tracked_search(
query, self.constraints[:3], "exploratory"
)
- candidates.extend(self._extract_candidates_with_context(results, query))
+ candidates.extend(
+ self._extract_candidates_with_context(results, query)
+ )
return candidates
@@ -269,7 +276,9 @@ Return only the queries, one per line.
# Adapt successful patterns
for pattern in self.successful_patterns[:3]:
constraint_ids = pattern["constraints"]
- constraints = [c for c in self.constraints if c.id in constraint_ids]
+ constraints = [
+ c for c in self.constraints if c.id in constraint_ids
+ ]
# Create variations of successful queries
adapted_query = self._adapt_successful_query(
@@ -303,7 +312,9 @@ Return only the queries, one per line.
# Try single constraint
for c in constraints[:2]:
query = self._create_evidence_query(candidate, [c])
- results = self._execute_tracked_search(query, [c], "evidence")
+ results = self._execute_tracked_search(
+ query, [c], "evidence"
+ )
evidence = self.evidence_evaluator.extract_evidence(
results.get("current_knowledge", ""), candidate.name, c
)
@@ -311,22 +322,29 @@ Return only the queries, one per line.
# Try combined constraints of same type
if len(constraints) > 1:
- query = self._create_evidence_query(candidate, constraints[:2])
+ query = self._create_evidence_query(
+ candidate, constraints[:2]
+ )
results = self._execute_tracked_search(
query, constraints[:2], "evidence_combined"
)
for c in constraints[:2]:
evidence = self.evidence_evaluator.extract_evidence(
- results.get("current_knowledge", ""), candidate.name, c
+ results.get("current_knowledge", ""),
+ candidate.name,
+ c,
)
if (
c.id not in candidate.evidence
- or evidence.confidence > candidate.evidence[c.id].confidence
+ or evidence.confidence
+ > candidate.evidence[c.id].confidence
):
candidate.add_evidence(c.id, evidence)
- def _create_adaptive_search_query(self, constraints: List[Constraint]) -> str:
+ def _create_adaptive_search_query(
+ self, constraints: List[Constraint]
+ ) -> str:
"""Create adaptive search queries based on past performance."""
# Check if similar constraint combinations have been successful
constraint_ids = {c.id for c in constraints}
@@ -349,7 +367,9 @@ Return only the queries, one per line.
return base_query
- def _create_cross_constraint_query(self, constraints: List[Constraint]) -> str:
+ def _create_cross_constraint_query(
+ self, constraints: List[Constraint]
+ ) -> str:
"""Create queries that leverage relationships between constraints."""
prompt = f"""
Create a search query that finds candidates satisfying BOTH/ALL of these constraints:
@@ -429,7 +449,9 @@ Return only the search query.
# Update evidence if better found
for constraint in self.constraints:
evidence = self.evidence_evaluator.extract_evidence(
- results.get("current_knowledge", ""), candidate.name, constraint
+ results.get("current_knowledge", ""),
+ candidate.name,
+ constraint,
)
if (
@@ -446,7 +468,9 @@ Return only the search query.
results = self._execute_search(query)
# Track the attempt
- candidates_found = len(self._extract_candidates_with_context(results, query))
+ candidates_found = len(
+ self._extract_candidates_with_context(results, query)
+ )
attempt = SearchAttempt(
query=query,
constraint_ids=[c.id for c in constraints],
@@ -488,7 +512,9 @@ Return only the search query.
return combinations
- def _format_constraints_for_prompt(self, constraints: List[Constraint]) -> str:
+ def _format_constraints_for_prompt(
+ self, constraints: List[Constraint]
+ ) -> str:
"""Format constraints for LLM prompts."""
formatted = []
for c in constraints:
@@ -553,7 +579,9 @@ Return only the modified query.
# Confidence distribution (prefer balanced confidence)
confidences = [e.confidence for e in candidate.evidence.values()]
if confidences:
- variance = sum((c - 0.7) ** 2 for c in confidences) / len(confidences)
+ variance = sum((c - 0.7) ** 2 for c in confidences) / len(
+ confidences
+ )
confidence_score = 1.0 / (1.0 + variance)
else:
confidence_score = 0.0
@@ -587,7 +615,9 @@ Return only the modified query.
self.candidates = kept
- def _adds_diversity(self, candidate: Candidate, existing: List[Candidate]) -> bool:
+ def _adds_diversity(
+ self, candidate: Candidate, existing: List[Candidate]
+ ) -> bool:
"""Check if a candidate adds diversity to the existing set."""
# Check source diversity
candidate_sources = self.source_types.get(candidate.name, set())
@@ -633,9 +663,7 @@ Return only the query.
# Source-specific query
if self.source_types.get(candidate.name):
- source_query = (
- f'"{candidate.name}" site:{list(self.source_types[candidate.name])[0]}'
- )
+ source_query = f'"{candidate.name}" site:{list(self.source_types[candidate.name])[0]}'
queries.append(source_query)
return queries
@@ -681,7 +709,9 @@ Return only the search query.
for candidate in self.candidates[:5]:
covered_constraints.update(candidate.evidence.keys())
- uncovered = [c for c in self.constraints if c.id not in covered_constraints]
+ uncovered = [
+ c for c in self.constraints if c.id not in covered_constraints
+ ]
if uncovered:
# Search specifically for uncovered constraints
@@ -693,8 +723,12 @@ Return only the search query.
queries.append((query, constraint_group))
for query, constraints in queries[: self.adaptive_query_count]:
- results = self._execute_tracked_search(query, constraints, "adaptive")
- new_candidates = self._extract_candidates_with_context(results, query)
+ results = self._execute_tracked_search(
+ query, constraints, "adaptive"
+ )
+ new_candidates = self._extract_candidates_with_context(
+ results, query
+ )
# Add unique candidates
existing_names = {c.name.lower() for c in self.candidates}
@@ -724,19 +758,25 @@ Return only the search query.
for pattern in self.successful_patterns:
for constraint_id in pattern["constraints"]:
constraint = next(
- (c for c in self.constraints if c.id == constraint_id), None
+ (c for c in self.constraints if c.id == constraint_id),
+ None,
)
if constraint:
- type_success[constraint.type] += pattern["candidates_found"]
+ type_success[constraint.type] += pattern[
+ "candidates_found"
+ ]
# Sort by success rate
priority_order = sorted(
- priority_order, key=lambda t: type_success.get(t, 0), reverse=True
+ priority_order,
+ key=lambda t: type_success.get(t, 0),
+ reverse=True,
)
# Sort constraints by adjusted priority
sorted_constraints = sorted(
- self.constraints, key=lambda c: (priority_order.index(c.type), -c.weight)
+ self.constraints,
+ key=lambda c: (priority_order.index(c.type), -c.weight),
)
return sorted_constraints[:5]
diff --git a/src/local_deep_research/advanced_search_system/strategies/iterative_reasoning_strategy.py b/src/local_deep_research/advanced_search_system/strategies/iterative_reasoning_strategy.py
index 1146268a83..f9604971ce 100644
--- a/src/local_deep_research/advanced_search_system/strategies/iterative_reasoning_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/iterative_reasoning_strategy.py
@@ -49,7 +49,7 @@ Search History ({len(self.search_history)} searches):
{chr(10).join(f"- Search {i + 1}: {s['query']}" for i, s in enumerate(self.search_history[-3:])) if self.search_history else "- No searches yet"}
Candidate Answers ({len(self.candidate_answers)} total):
-{chr(10).join(f"- {c['answer']} (confidence: {c['confidence']:.0%})" for c in sorted(self.candidate_answers, key=lambda x: x['confidence'], reverse=True)) if self.candidate_answers else "- None yet"}
+{chr(10).join(f"- {c['answer']} (confidence: {c['confidence']:.0%})" for c in sorted(self.candidate_answers, key=lambda x: x["confidence"], reverse=True)) if self.candidate_answers else "- None yet"}
Current Confidence: {self.confidence:.1%}
"""
@@ -152,7 +152,6 @@ class IterativeReasoningStrategy(BaseSearchStrategy):
self.knowledge_state.iteration < self.max_iterations
and self.knowledge_state.confidence < self.confidence_threshold
):
-
self.knowledge_state.iteration += 1
logger.info(
f"Iteration {self.knowledge_state.iteration}/{self.max_iterations}, Current confidence: {self.knowledge_state.confidence:.1%}"
@@ -161,7 +160,10 @@ class IterativeReasoningStrategy(BaseSearchStrategy):
# Update progress
if self.progress_callback:
progress = (
- int((self.knowledge_state.iteration / self.max_iterations) * 80)
+ int(
+ (self.knowledge_state.iteration / self.max_iterations)
+ * 80
+ )
+ 10
)
facts_count = len(self.knowledge_state.key_facts)
@@ -188,7 +190,9 @@ class IterativeReasoningStrategy(BaseSearchStrategy):
"iteration": self.knowledge_state.iteration,
"confidence": self.knowledge_state.confidence,
"facts_found": facts_count,
- "uncertainties": len(self.knowledge_state.uncertainties),
+ "uncertainties": len(
+ self.knowledge_state.uncertainties
+ ),
"candidates_count": candidates_count,
"top_candidates": top_candidates,
},
@@ -242,7 +246,9 @@ class IterativeReasoningStrategy(BaseSearchStrategy):
self._assess_answer()
# Check if we made progress
- confidence_change = self.knowledge_state.confidence - prev_confidence
+ confidence_change = (
+ self.knowledge_state.confidence - prev_confidence
+ )
new_facts = len(self.knowledge_state.key_facts) - prev_facts_count
if confidence_change < 0.01 and new_facts == 0:
@@ -282,7 +288,7 @@ class IterativeReasoningStrategy(BaseSearchStrategy):
{chr(10).join(f"- {fact}" for fact in self.knowledge_state.key_facts[-3:]) if self.knowledge_state.key_facts else "- No new facts in this iteration"}
**Current Candidates** ({len(self.knowledge_state.candidate_answers)} total):
-{chr(10).join(f"- {c['answer']} (confidence: {c['confidence']:.0%})" for c in sorted(self.knowledge_state.candidate_answers, key=lambda x: x['confidence'], reverse=True)[:5]) if self.knowledge_state.candidate_answers else "- No candidates yet"}
+{chr(10).join(f"- {c['answer']} (confidence: {c['confidence']:.0%})" for c in sorted(self.knowledge_state.candidate_answers, key=lambda x: x["confidence"], reverse=True)[:5]) if self.knowledge_state.candidate_answers else "- No candidates yet"}
**Remaining Questions**:
{chr(10).join(f"- {u}" for u in self.knowledge_state.uncertainties[:3]) if self.knowledge_state.uncertainties else "- No specific uncertainties"}
@@ -296,7 +302,9 @@ class IterativeReasoningStrategy(BaseSearchStrategy):
"phase": f"Iteration {self.knowledge_state.iteration}",
"content": iteration_summary.strip(),
"search_query": next_search,
- "key_findings": self.knowledge_state.key_facts[-3:], # Last 3 facts
+ "key_findings": self.knowledge_state.key_facts[
+ -3:
+ ], # Last 3 facts
"confidence": self.knowledge_state.confidence,
"timestamp": self._get_timestamp(),
}
@@ -402,7 +410,9 @@ EXPECTED_OUTCOME: [what we hope to learn]
logger.warning("Could not extract next search from LLM response")
# Try to extract any search-like query from the response
for line in lines:
- if len(line) > 10 and "?" not in line: # Heuristic for search queries
+ if (
+ len(line) > 10 and "?" not in line
+ ): # Heuristic for search queries
next_search = line.strip()
logger.info(f"Extracted fallback search: {next_search}")
break
@@ -446,9 +456,7 @@ EXPECTED_OUTCOME: [what we hope to learn]
elif "questions" in message.lower():
display_message = f"Step {self.knowledge_state.iteration}: Generating follow-up questions"
elif "findings" in message.lower():
- display_message = (
- f"Step {self.knowledge_state.iteration}: Processing findings"
- )
+ display_message = f"Step {self.knowledge_state.iteration}: Processing findings"
else:
display_message = (
f"Step {self.knowledge_state.iteration}: {message}"
@@ -472,7 +480,9 @@ EXPECTED_OUTCOME: [what we hope to learn]
# Update our tracking
if "questions_by_iteration" in results:
- self.questions_by_iteration.extend(results["questions_by_iteration"])
+ self.questions_by_iteration.extend(
+ results["questions_by_iteration"]
+ )
return results
@@ -612,7 +622,9 @@ RESOLVED_UNCERTAINTIES:
confidence_spread = 0.0
if len(sorted_candidates) > 1:
second_best = sorted_candidates[1]
- confidence_spread = best_candidate["confidence"] - second_best["confidence"]
+ confidence_spread = (
+ best_candidate["confidence"] - second_best["confidence"]
+ )
# If top two candidates are very close, reduce overall confidence
if confidence_spread < 0.1: # Less than 10% difference
@@ -626,7 +638,9 @@ RESOLVED_UNCERTAINTIES:
fact_boost = min(len(self.knowledge_state.key_facts) * 0.05, 0.2)
# Reduce confidence if we have many uncertainties
- uncertainty_penalty = min(len(self.knowledge_state.uncertainties) * 0.05, 0.2)
+ uncertainty_penalty = min(
+ len(self.knowledge_state.uncertainties) * 0.05, 0.2
+ )
# Boost if we've done multiple searches that confirm
search_boost = min(len(self.knowledge_state.search_history) * 0.02, 0.1)
diff --git a/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py b/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py
index d60ab95251..e9676f64f4 100644
--- a/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py
@@ -71,7 +71,7 @@ class IterDRAGStrategy(BaseSearchStrategy):
try:
# Format context for question generation
context = f"""Current Query: {query}
-Current Date: {datetime.now().strftime('%Y-%m-%d')}
+Current Date: {datetime.now().strftime("%Y-%m-%d")}
Past Questions: {self.questions_by_iteration}
Current Knowledge: {current_knowledge}
@@ -80,7 +80,9 @@ Initial Search Results:
# Generate sub-queries using the question generator
return self.question_generator.generate_questions(
- query, context, int(get_db_setting("search.questions_per_iteration"))
+ query,
+ context,
+ int(get_db_setting("search.questions_per_iteration")),
)
except Exception:
logger.exception("Error generating sub-queries")
@@ -100,9 +102,7 @@ Initial Search Results:
# Check if search engine is available
if self.search is None:
- error_msg = (
- "Error: No search engine available. Please check your configuration."
- )
+ error_msg = "Error: No search engine available. Please check your configuration."
self._update_progress(
error_msg,
100,
@@ -140,7 +140,10 @@ Initial Search Results:
self._update_progress(
f"Found {len(initial_results)} initial results",
15,
- {"phase": "search_complete", "result_count": len(initial_results)},
+ {
+ "phase": "search_complete",
+ "result_count": len(initial_results),
+ },
)
# Extract and save links
@@ -161,7 +164,9 @@ Initial Search Results:
# Store questions in repository and in self.questions_by_iteration
self.questions_by_iteration = {0: sub_queries}
- self.findings_repository.set_questions_by_iteration(self.questions_by_iteration)
+ self.findings_repository.set_questions_by_iteration(
+ self.questions_by_iteration
+ )
if not sub_queries:
logger.error("No sub-queries were generated to analyze.")
@@ -231,11 +236,15 @@ Initial Search Results:
}
findings.append(finding)
self.findings_repository.add_finding(sub_query, finding)
- self.findings_repository.add_documents(result["documents"])
+ self.findings_repository.add_documents(
+ result["documents"]
+ )
# Add to current knowledge with space around +
current_knowledge = (
- current_knowledge + "\n\n\n New: \n" + result["content"]
+ current_knowledge
+ + "\n\n\n New: \n"
+ + result["content"]
)
except Exception:
logger.exception("Error analyzing sub-query results:")
@@ -259,7 +268,9 @@ Initial Search Results:
try:
# Extract finding contents for synthesis
- finding_contents = [f["content"] for f in findings if "content" in f]
+ finding_contents = [
+ f["content"] for f in findings if "content" in f
+ ]
# Synthesize findings into a final answer
final_answer = self.findings_repository.synthesize_findings(
@@ -270,7 +281,9 @@ Initial Search Results:
)
# Check if the synthesis failed with an error
- if isinstance(final_answer, str) and final_answer.startswith("Error:"):
+ if isinstance(final_answer, str) and final_answer.startswith(
+ "Error:"
+ ):
logger.error(f"Synthesis returned an error: {final_answer}")
# Extract error type for better handling
@@ -287,7 +300,9 @@ Initial Search Results:
error_type = "connection"
# Log with specific error type
- logger.error(f"Synthesis failed with error type: {error_type}")
+ logger.error(
+ f"Synthesis failed with error type: {error_type}"
+ )
# Add error information to progress update
self._update_progress(
@@ -304,7 +319,9 @@ Initial Search Results:
longest_finding = f["content"]
if longest_finding:
- logger.info("Using longest finding as fallback synthesis")
+ logger.info(
+ "Using longest finding as fallback synthesis"
+ )
final_answer = f"""
# Research Results (Fallback Mode)
@@ -316,7 +333,9 @@ This is a fallback response using the most detailed individual finding.
"""
else:
# If we don't have any findings with content, use current_knowledge
- logger.info("Using current knowledge as fallback synthesis")
+ logger.info(
+ "Using current knowledge as fallback synthesis"
+ )
final_answer = f"""
# Research Results (Fallback Mode)
@@ -338,7 +357,9 @@ This is a fallback response using the accumulated knowledge.
findings.append(finding)
# Store the synthesized content
- self.findings_repository.add_finding(query + "_synthesis", final_answer)
+ self.findings_repository.add_finding(
+ query + "_synthesis", final_answer
+ )
# Update current knowledge with the synthesized version
current_knowledge = final_answer
@@ -366,7 +387,11 @@ This is a fallback response using the accumulated knowledge.
# Extract best content from findings
key_findings = []
for i, f in enumerate(findings):
- if isinstance(f, dict) and "content" in f and f.get("content"):
+ if (
+ isinstance(f, dict)
+ and "content" in f
+ and f.get("content")
+ ):
# Only take the first 500 chars of each finding for the fallback
content_preview = f.get("content", "")[:500]
if content_preview:
@@ -405,10 +430,15 @@ Please try again with a different query or contact support.
"""
# Compress knowledge if needed
- if get_db_setting("general.knowledge_accumulation", "ITERATION") == "ITERATION":
+ if (
+ get_db_setting("general.knowledge_accumulation", "ITERATION")
+ == "ITERATION"
+ ):
try:
self._update_progress(
- "Compressing knowledge", 90, {"phase": "knowledge_compression"}
+ "Compressing knowledge",
+ 90,
+ {"phase": "knowledge_compression"},
)
current_knowledge = self.knowledge_generator.compress_knowledge(
current_knowledge, query, section_links
@@ -435,12 +465,16 @@ Please try again with a different query or contact support.
)
# Now format the findings with search questions and sources
- formatted_findings = self.findings_repository.format_findings_to_text(
- findings, final_answer
+ formatted_findings = (
+ self.findings_repository.format_findings_to_text(
+ findings, final_answer
+ )
)
except Exception:
logger.exception("Error formatting final findings")
- formatted_findings = "Error: Could not format findings due to an error."
+ formatted_findings = (
+ "Error: Could not format findings due to an error."
+ )
self._update_progress("Research complete", 100, {"phase": "complete"})
diff --git a/src/local_deep_research/advanced_search_system/strategies/llm_driven_modular_strategy.py b/src/local_deep_research/advanced_search_system/strategies/llm_driven_modular_strategy.py
index ec90c3f49e..e2f3a30ad7 100644
--- a/src/local_deep_research/advanced_search_system/strategies/llm_driven_modular_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/llm_driven_modular_strategy.py
@@ -214,7 +214,11 @@ class LLMConstraintProcessor:
logger.error(f"Failed to parse combinations: {e}")
# Fallback
- return ["fictional character humor", "TV show 1970s", "fourth wall breaking"]
+ return [
+ "fictional character humor",
+ "TV show 1970s",
+ "fourth wall breaking",
+ ]
def _parse_creative_searches(self, content):
"""Parse LLM creative searches response"""
@@ -251,12 +255,19 @@ class LLMConstraintProcessor:
"fictional character fourth wall humor",
"1970s TV show limited episodes",
],
- "systematic_granular": ["1970 TV show", "1971 TV show", "1972 TV show"],
+ "systematic_granular": [
+ "1970 TV show",
+ "1971 TV show",
+ "1972 TV show",
+ ],
"creative_angles": [
"superhero comedy television",
"cartoon character talks to audience",
],
- "contextual_searches": ["vintage TV comedy", "classic television humor"],
+ "contextual_searches": [
+ "vintage TV comedy",
+ "classic television humor",
+ ],
"fallback_broad": ["fictional character", "TV show character"],
}
@@ -277,7 +288,7 @@ class EarlyRejectionManager:
Quickly assess if this candidate matches the search criteria:
Candidate: {candidate.name}
- Available info: {getattr(candidate, 'metadata', {})}
+ Available info: {getattr(candidate, "metadata", {})}
Constraints to match:
{[c.description for c in constraints]}
@@ -429,7 +440,9 @@ class LLMDrivenModularStrategy(BaseSearchStrategy):
answer, metadata = future.result()
else:
# If not in async context, run directly
- answer, metadata = loop.run_until_complete(self.search(query))
+ answer, metadata = loop.run_until_complete(
+ self.search(query)
+ )
except RuntimeError:
# No event loop, create one
answer, metadata = asyncio.run(self.search(query))
@@ -440,7 +453,9 @@ class LLMDrivenModularStrategy(BaseSearchStrategy):
"final_answer": answer,
"metadata": metadata,
"links": getattr(self, "all_links_of_system", []),
- "questions_by_iteration": getattr(self, "questions_by_iteration", []),
+ "questions_by_iteration": getattr(
+ self, "questions_by_iteration", []
+ ),
}
except Exception as e:
@@ -478,7 +493,9 @@ class LLMDrivenModularStrategy(BaseSearchStrategy):
}
)
- base_constraints = self.constraint_analyzer.extract_constraints(query)
+ base_constraints = self.constraint_analyzer.extract_constraints(
+ query
+ )
logger.info(f"Extracted {len(base_constraints)} base constraints")
# Phase 2: LLM intelligent decomposition
@@ -491,10 +508,14 @@ class LLMDrivenModularStrategy(BaseSearchStrategy):
}
)
- decomposed = await self.llm_processor.decompose_constraints_intelligently(
- base_constraints
+ decomposed = (
+ await self.llm_processor.decompose_constraints_intelligently(
+ base_constraints
+ )
+ )
+ logger.info(
+ f"LLM decomposed constraints into {len(decomposed)} groups"
)
- logger.info(f"LLM decomposed constraints into {len(decomposed)} groups")
# Phase 3: LLM intelligent combinations
if progress_callback:
@@ -507,7 +528,9 @@ class LLMDrivenModularStrategy(BaseSearchStrategy):
)
intelligent_combinations = (
- await self.llm_processor.generate_intelligent_combinations(decomposed)
+ await self.llm_processor.generate_intelligent_combinations(
+ decomposed
+ )
)
logger.info(
f"LLM generated {len(intelligent_combinations)} intelligent combinations"
@@ -528,7 +551,9 @@ class LLMDrivenModularStrategy(BaseSearchStrategy):
query, decomposed
)
)
- logger.info(f"LLM generated {len(creative_searches)} creative searches")
+ logger.info(
+ f"LLM generated {len(creative_searches)} creative searches"
+ )
# Phase 5: LLM optimization
if progress_callback:
@@ -541,8 +566,10 @@ class LLMDrivenModularStrategy(BaseSearchStrategy):
)
all_searches = intelligent_combinations + creative_searches
- optimized_searches = await self.llm_processor.optimize_search_combinations(
- all_searches
+ optimized_searches = (
+ await self.llm_processor.optimize_search_combinations(
+ all_searches
+ )
)
total_searches = sum(
len(searches) for searches in optimized_searches.values()
@@ -560,7 +587,9 @@ class LLMDrivenModularStrategy(BaseSearchStrategy):
if not searches:
continue
- logger.info(f"Executing {category} searches: {len(searches)} queries")
+ logger.info(
+ f"Executing {category} searches: {len(searches)} queries"
+ )
if progress_callback:
progress_callback(
@@ -581,7 +610,9 @@ class LLMDrivenModularStrategy(BaseSearchStrategy):
# Execute batch searches in parallel
batch_tasks = []
for search_query in batch:
- task = self.candidate_explorer._execute_search(search_query)
+ task = self.candidate_explorer._execute_search(
+ search_query
+ )
batch_tasks.append(task)
# Wait for batch completion
@@ -592,13 +623,13 @@ class LLMDrivenModularStrategy(BaseSearchStrategy):
# Process batch results
for j, result in enumerate(batch_results):
if isinstance(result, Exception):
- logger.error(f"Search failed: {batch[j]} - {result}")
+ logger.error(
+ f"Search failed: {batch[j]} - {result}"
+ )
continue
- candidates = (
- self.candidate_explorer._extract_candidates_from_results(
- result, entity_type="fictional character"
- )
+ candidates = self.candidate_explorer._extract_candidates_from_results(
+ result, entity_type="fictional character"
)
# Early rejection if enabled
@@ -619,7 +650,10 @@ class LLMDrivenModularStrategy(BaseSearchStrategy):
)
continue
- if confidence.get("positive_confidence", 0) > 0.6:
+ if (
+ confidence.get("positive_confidence", 0)
+ > 0.6
+ ):
high_confidence_count += 1
category_candidates.append(candidate)
@@ -692,7 +726,9 @@ class LLMDrivenModularStrategy(BaseSearchStrategy):
evaluated_candidates.append(candidate)
except Exception as e:
- logger.error(f"Error evaluating candidate {candidate.name}: {e}")
+ logger.error(
+ f"Error evaluating candidate {candidate.name}: {e}"
+ )
continue
if not evaluated_candidates:
@@ -773,7 +809,7 @@ Constraints analyzed:
Constraint evaluation results:
{evaluation_info}
-Evidence summary: {getattr(best_candidate, 'summary', 'No summary available')}
+Evidence summary: {getattr(best_candidate, "summary", "No summary available")}
Provide a clear, factual answer that addresses the original question and explains how the candidate satisfies the constraints."""
@@ -807,7 +843,8 @@ Provide a clear, factual answer that addresses the original question and explain
for result in result_list:
evidence.append(
{
- "text": result.get("snippet", "") or result.get("content", ""),
+ "text": result.get("snippet", "")
+ or result.get("content", ""),
"source": result.get("url", "search_result"),
"confidence": 0.7,
"title": result.get("title", ""),
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 8655d4fa70..739d75eec6 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
@@ -18,7 +18,11 @@ from ..candidate_exploration import (
DiversityExplorer,
ParallelExplorer,
)
-from ..constraint_checking import DualConfidenceChecker, StrictChecker, ThresholdChecker
+from ..constraint_checking import (
+ DualConfidenceChecker,
+ StrictChecker,
+ ThresholdChecker,
+)
from ..constraints import ConstraintAnalyzer
from ..questions import StandardQuestionGenerator
from .base_strategy import BaseSearchStrategy
@@ -99,7 +103,9 @@ class LLMConstraintProcessor:
# Add the original query as first in our tracking
all_queries_used = (
- [original_query] + existing_queries if original_query else existing_queries
+ [original_query] + existing_queries
+ if original_query
+ else existing_queries
)
existing_queries_str = (
"\n".join([f"- {q}" for q in all_queries_used])
@@ -110,7 +116,7 @@ class LLMConstraintProcessor:
prompt = f"""
Create search query variations using TWO strategies:
- ORIGINAL QUERY: "{original_query if original_query else 'Not provided'}"
+ ORIGINAL QUERY: "{original_query if original_query else "Not provided"}"
ALREADY USED QUERIES (DO NOT REPEAT):
{existing_queries_str}
@@ -156,7 +162,9 @@ class LLMConstraintProcessor:
logger.error(f"Failed to parse decomposition: {e}")
# If parsing fails, return empty dict - let the system handle gracefully
- logger.warning("Failed to parse constraint decomposition, returning empty dict")
+ logger.warning(
+ "Failed to parse constraint decomposition, returning empty dict"
+ )
return {}
def _parse_combinations(self, content):
@@ -191,7 +199,7 @@ class EarlyRejectionManager:
Quickly assess if this candidate matches the search criteria:
Candidate: {candidate.name}
- Available info: {getattr(candidate, 'metadata', {})}
+ Available info: {getattr(candidate, "metadata", {})}
Constraints to match:
{[c.description for c in constraints]}
@@ -299,7 +307,9 @@ class ModularStrategy(BaseSearchStrategy):
# Initialize LLM constraint processor if enabled
self.llm_processor = (
- LLMConstraintProcessor(self.model) if llm_constraint_processing else None
+ LLMConstraintProcessor(self.model)
+ if llm_constraint_processing
+ else None
)
# Initialize early rejection manager if enabled
@@ -313,7 +323,9 @@ class ModularStrategy(BaseSearchStrategy):
)
# Initialize candidate explorer based on strategy
- self.candidate_explorer = self._create_candidate_explorer(exploration_strategy)
+ self.candidate_explorer = self._create_candidate_explorer(
+ exploration_strategy
+ )
# Initialize question generator
self.question_generator = StandardQuestionGenerator(model=self.model)
@@ -345,7 +357,8 @@ class ModularStrategy(BaseSearchStrategy):
)
elif checker_type == "strict":
return StrictChecker(
- model=self.model, evidence_gatherer=self._gather_evidence_for_constraint
+ model=self.model,
+ evidence_gatherer=self._gather_evidence_for_constraint,
)
elif checker_type == "threshold":
return ThresholdChecker(
@@ -360,11 +373,15 @@ class ModularStrategy(BaseSearchStrategy):
"""Create the appropriate candidate explorer."""
if strategy_type == "parallel":
return ParallelExplorer(
- search_engine=self.search_engine, model=self.model, max_workers=4
+ search_engine=self.search_engine,
+ model=self.model,
+ max_workers=4,
)
elif strategy_type == "adaptive":
return AdaptiveExplorer(
- search_engine=self.search_engine, model=self.model, learning_rate=0.1
+ search_engine=self.search_engine,
+ model=self.model,
+ learning_rate=0.1,
)
elif strategy_type == "constraint_guided":
return ConstraintGuidedExplorer(
@@ -372,7 +389,9 @@ class ModularStrategy(BaseSearchStrategy):
)
elif strategy_type == "diversity":
return DiversityExplorer(
- search_engine=self.search_engine, model=self.model, diversity_factor=0.3
+ search_engine=self.search_engine,
+ model=self.model,
+ diversity_factor=0.3,
)
else:
raise ValueError(f"Unknown exploration strategy: {strategy_type}")
@@ -400,7 +419,9 @@ class ModularStrategy(BaseSearchStrategy):
}
)
- base_constraints = self.constraint_analyzer.extract_constraints(query)
+ base_constraints = self.constraint_analyzer.extract_constraints(
+ query
+ )
logger.info(f"Extracted {len(base_constraints)} base constraints")
# Phase 2: LLM constraint processing (if enabled)
@@ -417,10 +438,8 @@ class ModularStrategy(BaseSearchStrategy):
logger.info("🤖 LLM CONSTRAINT PROCESSING ACTIVATED")
# LLM decomposition and combination
- decomposed = (
- await self.llm_processor.decompose_constraints_intelligently(
- base_constraints
- )
+ decomposed = await self.llm_processor.decompose_constraints_intelligently(
+ base_constraints
)
# Pass existing base constraint queries to avoid duplication
@@ -443,9 +462,9 @@ class ModularStrategy(BaseSearchStrategy):
# OPTIMIZATION: Start with original query, then use LLM-generated targeted queries
# This ensures we search for the exact question first, then explore variations
- all_search_queries = [
- query
- ] + intelligent_combinations # Original query first, then LLM combinations
+ all_search_queries = (
+ [query] + intelligent_combinations
+ ) # Original query first, then LLM combinations
logger.info(
f"🎯 Using original query + {len(intelligent_combinations)} targeted LLM search combinations (skipping broad base constraints)"
)
@@ -507,7 +526,9 @@ class ModularStrategy(BaseSearchStrategy):
}
)
- logger.info(f"📦 Processing batch {i // batch_size + 1}: {batch}")
+ logger.info(
+ f"📦 Processing batch {i // batch_size + 1}: {batch}"
+ )
# Execute batch searches in parallel using ThreadPoolExecutor
batch_results = []
@@ -541,10 +562,8 @@ class ModularStrategy(BaseSearchStrategy):
logger.error(f"❌ Search failed: {batch[j]} - {result}")
continue
- candidates = (
- self.candidate_explorer._extract_candidates_from_results(
- result, original_query=query
- )
+ candidates = self.candidate_explorer._extract_candidates_from_results(
+ result, original_query=query
)
logger.info(
@@ -571,16 +590,22 @@ class ModularStrategy(BaseSearchStrategy):
)
# CRITICAL: Yield control after each batch to allow background evaluation
- await asyncio.sleep(0.1) # Small delay to let background task process
+ await asyncio.sleep(
+ 0.1
+ ) # Small delay to let background task process
search_progress = min(search_progress + 10, 75)
# Signal completion to background evaluation and wait for final results
- await candidate_evaluation_queue.put(None) # Sentinel to signal completion
+ await candidate_evaluation_queue.put(
+ None
+ ) # Sentinel to signal completion
# Wait for background evaluation to complete
try:
- await asyncio.wait_for(evaluation_task, timeout=30.0) # 30s timeout
+ await asyncio.wait_for(
+ evaluation_task, timeout=30.0
+ ) # 30s timeout
except asyncio.TimeoutError:
logger.warning(
"⚠️ Background evaluation timed out, using partial results"
@@ -653,7 +678,9 @@ class ModularStrategy(BaseSearchStrategy):
if all_scored_candidates:
# Sort by score
- all_scored_candidates.sort(key=lambda x: x.score, reverse=True)
+ all_scored_candidates.sort(
+ key=lambda x: x.score, reverse=True
+ )
best_candidate = all_scored_candidates[0]
# Accept if score is above minimum threshold (20%)
@@ -668,7 +695,9 @@ class ModularStrategy(BaseSearchStrategy):
)
if not evaluated_candidates:
- logger.warning("❌ No valid candidates found after evaluation")
+ logger.warning(
+ "❌ No valid candidates found after evaluation"
+ )
return "No valid candidates found after evaluation", {
"strategy": "enhanced_modular",
"constraint_checker": self.constraint_checker_type,
@@ -709,7 +738,9 @@ class ModularStrategy(BaseSearchStrategy):
logger.info("=" * 80)
logger.info("🔍 SEARCH QUERY ANALYSIS SUMMARY")
logger.info("=" * 80)
- logger.info(f"📊 TOTAL QUERIES GENERATED: {len(all_search_queries)}")
+ logger.info(
+ f"📊 TOTAL QUERIES GENERATED: {len(all_search_queries)}"
+ )
logger.info(
f"📋 BASE CONSTRAINT QUERIES: {len(existing_queries) if 'existing_queries' in locals() else 0}"
)
@@ -717,7 +748,10 @@ class ModularStrategy(BaseSearchStrategy):
f"🧠 LLM INTELLIGENT QUERIES: {len(intelligent_combinations) if 'intelligent_combinations' in locals() else 0}"
)
- if "intelligent_combinations" in locals() and intelligent_combinations:
+ if (
+ "intelligent_combinations" in locals()
+ and intelligent_combinations
+ ):
logger.info("\n🎯 SAMPLE LLM-GENERATED QUERIES (first 10):")
for i, query in enumerate(intelligent_combinations[:10], 1):
logger.info(f" SAMPLE-{i:02d}: {query}")
@@ -778,7 +812,7 @@ Constraints analyzed:
Constraint evaluation results:
{evaluation_info}
-Evidence summary: {getattr(best_candidate, 'summary', 'No summary available')}
+Evidence summary: {getattr(best_candidate, "summary", "No summary available")}
Provide a clear, factual answer that addresses the original question and explains how the candidate satisfies the constraints."""
@@ -830,7 +864,9 @@ Provide a clear, factual answer that addresses the original question and explain
import re
years = re.findall(r"\b(19\d{2}|20\d{2})\b", constraint_value)
- decades = re.findall(r"\b(19\d{2}s|20\d{2}s)\b", constraint_value)
+ decades = re.findall(
+ r"\b(19\d{2}s|20\d{2}s)\b", constraint_value
+ )
if years:
for year in years:
@@ -969,7 +1005,12 @@ Provide a clear, factual answer that addresses the original question and explain
return []
async def _background_candidate_evaluation(
- self, queue, constraints, results, original_query=None, rejected_candidates=None
+ self,
+ queue,
+ constraints,
+ results,
+ original_query=None,
+ rejected_candidates=None,
):
"""Background task to evaluate candidates without blocking search progress."""
logger.info("🔄 Started background candidate evaluation")
@@ -1000,14 +1041,14 @@ Provide a clear, factual answer that addresses the original question and explain
# Now check early rejection AFTER we have a score
if self.early_rejection_manager:
- confidence = (
- await self.early_rejection_manager.quick_confidence_check(
- candidate, constraints
- )
+ confidence = await self.early_rejection_manager.quick_confidence_check(
+ candidate, constraints
)
should_reject, reason = (
- self.early_rejection_manager.should_reject_early(confidence)
+ self.early_rejection_manager.should_reject_early(
+ confidence
+ )
)
if (
should_reject and candidate.score < 0.5
@@ -1067,7 +1108,9 @@ Provide a clear, factual answer that addresses the original question and explain
answer, metadata = future.result()
else:
# If not in async context, run directly
- answer, metadata = loop.run_until_complete(self.search(query))
+ answer, metadata = loop.run_until_complete(
+ self.search(query)
+ )
except RuntimeError:
# No event loop, create one
answer, metadata = asyncio.run(self.search(query))
@@ -1079,7 +1122,9 @@ Provide a clear, factual answer that addresses the original question and explain
"current_knowledge": answer,
"metadata": metadata,
"links": getattr(self, "all_links_of_system", []),
- "questions_by_iteration": getattr(self, "questions_by_iteration", []),
+ "questions_by_iteration": getattr(
+ self, "questions_by_iteration", []
+ ),
}
except Exception as e:
diff --git a/src/local_deep_research/advanced_search_system/strategies/parallel_constrained_strategy.py b/src/local_deep_research/advanced_search_system/strategies/parallel_constrained_strategy.py
index d5c76658d2..54e9f7bfc7 100644
--- a/src/local_deep_research/advanced_search_system/strategies/parallel_constrained_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/parallel_constrained_strategy.py
@@ -10,7 +10,7 @@ Key improvements:
import concurrent.futures
from dataclasses import dataclass
-from typing import Dict, List, Set
+from typing import List
from loguru import logger
@@ -75,7 +75,10 @@ class ParallelConstrainedStrategy(ConstrainedSearchStrategy):
is_hard = False
# Temporal and statistic constraints are usually hard
- if constraint.type in [ConstraintType.TEMPORAL, ConstraintType.STATISTIC]:
+ if constraint.type in [
+ ConstraintType.TEMPORAL,
+ ConstraintType.STATISTIC,
+ ]:
is_hard = True
# Check for hard constraint keywords
@@ -101,8 +104,13 @@ class ParallelConstrainedStrategy(ConstrainedSearchStrategy):
max_search_iterations = 3
# Check if constraint_ranking is available
- if not hasattr(self, "constraint_ranking") or not self.constraint_ranking:
- logger.error("No constraint ranking available - calling parent method")
+ if (
+ not hasattr(self, "constraint_ranking")
+ or not self.constraint_ranking
+ ):
+ logger.error(
+ "No constraint ranking available - calling parent method"
+ )
return super()._progressive_constraint_search()
# Detect what type of entity we're looking for
@@ -139,7 +147,7 @@ class ParallelConstrainedStrategy(ConstrainedSearchStrategy):
# Log the actual combinations
for i, combo in enumerate(combinations):
logger.info(
- f" Combination {i+1}: query='{combo.query[:60]}...', constraints={len(combo.constraints)}"
+ f" Combination {i + 1}: query='{combo.query[:60]}...', constraints={len(combo.constraints)}"
)
if self.progress_callback:
@@ -177,7 +185,10 @@ class ParallelConstrainedStrategy(ConstrainedSearchStrategy):
self.progress_callback(
f"Found {len(unique_candidates)} candidates - continuing search",
None,
- {"phase": "search_continue", "candidates": len(unique_candidates)},
+ {
+ "phase": "search_continue",
+ "candidates": len(unique_candidates),
+ },
)
self.candidates = unique_candidates[: self.candidate_limit]
@@ -211,7 +222,9 @@ class ParallelConstrainedStrategy(ConstrainedSearchStrategy):
if c.type in [ConstraintType.EVENT, ConstraintType.TEMPORAL]
]
properties = [
- c for c in self.constraint_ranking if c.type == ConstraintType.PROPERTY
+ c
+ for c in self.constraint_ranking
+ if c.type == ConstraintType.PROPERTY
]
if temporal and properties:
@@ -221,7 +234,9 @@ class ParallelConstrainedStrategy(ConstrainedSearchStrategy):
# Strategy 3: Combine statistic + property
stats = [
- c for c in self.constraint_ranking if c.type == ConstraintType.STATISTIC
+ c
+ for c in self.constraint_ranking
+ if c.type == ConstraintType.STATISTIC
]
if stats and properties:
combined = stats[:1] + properties[:2]
@@ -254,7 +269,9 @@ class ParallelConstrainedStrategy(ConstrainedSearchStrategy):
for i, constraint in enumerate(self.constraint_ranking[:5]):
# Create multiple query variations
queries = self._generate_query_variations(constraint)
- for j, query in enumerate(queries[:2]): # 2 variations per constraint
+ for j, query in enumerate(
+ queries[:2]
+ ): # 2 variations per constraint
combinations.append(
SearchCombination([constraint], query, i * 10 + j + 30)
)
@@ -288,7 +305,9 @@ class ParallelConstrainedStrategy(ConstrainedSearchStrategy):
# Add type-specific variations
if constraint.type == ConstraintType.STATISTIC:
- variations.extend([f"list {base}", f"complete {base}", f"all {base}"])
+ variations.extend(
+ [f"list {base}", f"complete {base}", f"all {base}"]
+ )
elif constraint.type == ConstraintType.PROPERTY:
variations.extend(
[f"with {base}", f"featuring {base}", f"known for {base}"]
@@ -322,7 +341,7 @@ class ParallelConstrainedStrategy(ConstrainedSearchStrategy):
if self.progress_callback:
self.progress_callback(
- f"Completed search {i+1}/{len(combinations)}: {len(candidates)} results",
+ f"Completed search {i + 1}/{len(combinations)}: {len(candidates)} results",
None,
{
"phase": "parallel_result",
@@ -355,7 +374,9 @@ class ParallelConstrainedStrategy(ConstrainedSearchStrategy):
# Always use LLM extraction for accuracy
extracted = self._extract_relevant_candidates(
{"current_knowledge": content},
- combination.constraints[0] if combination.constraints else None,
+ combination.constraints[0]
+ if combination.constraints
+ else None,
)
candidates.extend(extracted)
@@ -382,7 +403,7 @@ Search result:
{content}
Constraints to consider:
-{chr(10).join(f'- {c.value}' for c in constraints)}
+{chr(10).join(f"- {c.value}" for c in constraints)}
Important:
- Extract ONLY {entity_type} names
@@ -417,10 +438,10 @@ Return the {entity_type} names, one per line.
Validate {entity_type} candidates against hard constraints.
Hard constraints that MUST be satisfied:
-{chr(10).join(f'- {c.value}' for c in self.hard_constraints)}
+{chr(10).join(f"- {c.value}" for c in self.hard_constraints)}
{entity_type} candidates to evaluate:
-{chr(10).join(f'- {c.name}' for c in candidates[:20])}
+{chr(10).join(f"- {c.name}" for c in candidates[:20])}
Return ONLY the {entity_type} names that satisfy ALL hard constraints, one per line.
Reject any candidates that:
@@ -450,7 +471,9 @@ Be strict - if there's doubt about a constraint being satisfied, reject the cand
def _detect_entity_type(self) -> str:
"""Use LLM to detect what type of entity we're searching for."""
# Build context from constraints
- constraint_text = "\n".join([f"- {c.value}" for c in self.constraint_ranking])
+ constraint_text = "\n".join(
+ [f"- {c.value}" for c in self.constraint_ranking]
+ )
prompt = f"""
Analyze these search constraints and determine what type of entity is being searched for:
diff --git a/src/local_deep_research/advanced_search_system/strategies/parallel_search_strategy.py b/src/local_deep_research/advanced_search_system/strategies/parallel_search_strategy.py
index b4088d14d6..c485ac7c20 100644
--- a/src/local_deep_research/advanced_search_system/strategies/parallel_search_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/parallel_search_strategy.py
@@ -123,7 +123,9 @@ class ParallelSearchStrategy(BaseSearchStrategy):
try:
# Run each iteration
for iteration in range(1, iterations_to_run + 1):
- iteration_progress_base = 5 + (iteration - 1) * (70 / iterations_to_run)
+ iteration_progress_base = 5 + (iteration - 1) * (
+ 70 / iterations_to_run
+ )
self._update_progress(
f"Starting iteration {iteration}/{iterations_to_run}",
@@ -175,7 +177,9 @@ class ParallelSearchStrategy(BaseSearchStrategy):
# Generate follow-up questions based on accumulated knowledge if iterations > 2
use_knowledge = iterations_to_run > 2
- knowledge_for_questions = current_knowledge if use_knowledge else ""
+ knowledge_for_questions = (
+ current_knowledge if use_knowledge else ""
+ )
context = f"""Current Knowledge: {knowledge_for_questions}
Iteration: {iteration} of {iterations_to_run}"""
@@ -219,7 +223,8 @@ class ParallelSearchStrategy(BaseSearchStrategy):
max_workers=len(all_questions)
) as executor:
futures = [
- executor.submit(search_question, q) for q in all_questions
+ executor.submit(search_question, q)
+ for q in all_questions
]
iteration_search_dict = {}
iteration_search_results = []
@@ -261,7 +266,10 @@ class ParallelSearchStrategy(BaseSearchStrategy):
self._update_progress(
f"Filtering search results for iteration {iteration}",
iteration_progress_base + 45,
- {"phase": "cross_engine_filtering", "iteration": iteration},
+ {
+ "phase": "cross_engine_filtering",
+ "iteration": iteration,
+ },
)
# Get the current link count (for indexing)
@@ -276,7 +284,9 @@ class ParallelSearchStrategy(BaseSearchStrategy):
start_index=existing_link_count, # Start indexing after existing links
)
- links = extract_links_from_search_results(filtered_search_results)
+ links = extract_links_from_search_results(
+ filtered_search_results
+ )
self.all_links_of_system.extend(links)
self._update_progress(
@@ -293,7 +303,9 @@ class ParallelSearchStrategy(BaseSearchStrategy):
iteration_search_results = filtered_search_results
else:
# Just extract links without filtering
- links = extract_links_from_search_results(iteration_search_results)
+ links = extract_links_from_search_results(
+ iteration_search_results
+ )
self.all_links_of_system.extend(links)
# Add to all search results
@@ -303,11 +315,13 @@ class ParallelSearchStrategy(BaseSearchStrategy):
if self.include_text_content and iteration_search_results:
# For iteration > 1 with knowledge accumulation, use follow-up analysis
if iteration > 1 and iterations_to_run > 2:
- citation_result = self.citation_handler.analyze_followup(
- query,
- iteration_search_results,
- current_knowledge,
- len(self.all_links_of_system) - len(links),
+ citation_result = (
+ self.citation_handler.analyze_followup(
+ query,
+ iteration_search_results,
+ current_knowledge,
+ len(self.all_links_of_system) - len(links),
+ )
)
else:
# For first iteration or without knowledge accumulation, use initial analysis
@@ -358,8 +372,10 @@ class ParallelSearchStrategy(BaseSearchStrategy):
if self.include_text_content:
# Generate a final synthesis from all search results
if iterations_to_run > 1:
- final_citation_result = self.citation_handler.analyze_initial(
- query, all_search_results
+ final_citation_result = (
+ self.citation_handler.analyze_initial(
+ query, all_search_results
+ )
)
# Add null check for final_citation_result
if final_citation_result:
@@ -402,8 +418,10 @@ class ParallelSearchStrategy(BaseSearchStrategy):
)
# Format findings
- formatted_findings = self.findings_repository.format_findings_to_text(
- findings, synthesized_content
+ formatted_findings = (
+ self.findings_repository.format_findings_to_text(
+ findings, synthesized_content
+ )
)
except Exception as e:
diff --git a/src/local_deep_research/advanced_search_system/strategies/rapid_search_strategy.py b/src/local_deep_research/advanced_search_system/strategies/rapid_search_strategy.py
index 3d6c58ac63..9ae63a562b 100644
--- a/src/local_deep_research/advanced_search_system/strategies/rapid_search_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/rapid_search_strategy.py
@@ -23,7 +23,11 @@ class RapidSearchStrategy(BaseSearchStrategy):
"""
def __init__(
- self, search=None, model=None, citation_handler=None, all_links_of_system=None
+ self,
+ search=None,
+ model=None,
+ citation_handler=None,
+ all_links_of_system=None,
):
"""Initialize with optional dependency injection for testing."""
super().__init__(all_links_of_system=all_links_of_system)
@@ -90,7 +94,10 @@ class RapidSearchStrategy(BaseSearchStrategy):
self._update_progress(
f"Found {len(initial_results)} initial results",
15,
- {"phase": "search_complete", "result_count": len(initial_results)},
+ {
+ "phase": "search_complete",
+ "result_count": len(initial_results),
+ },
)
# Extract snippets and links
@@ -123,7 +130,9 @@ class RapidSearchStrategy(BaseSearchStrategy):
# Step 2: Generate a few follow-up questions (optional, can be skipped for ultimate speed)
self._update_progress(
- "Generating follow-up questions", 25, {"phase": "question_generation"}
+ "Generating follow-up questions",
+ 25,
+ {"phase": "question_generation"},
)
questions = self.question_generator.generate_questions(
@@ -161,7 +170,10 @@ class RapidSearchStrategy(BaseSearchStrategy):
self._update_progress(
f"Found {len(search_results)} results for question: {question}",
int(question_progress + 5),
- {"phase": "search_complete", "result_count": len(search_results)},
+ {
+ "phase": "search_complete",
+ "result_count": len(search_results),
+ },
)
# Extract snippets only
@@ -195,7 +207,9 @@ class RapidSearchStrategy(BaseSearchStrategy):
# Step 4: Perform a single final synthesis with all collected snippets using the citation handler
self._update_progress(
- "Synthesizing all collected information", 80, {"phase": "final_synthesis"}
+ "Synthesizing all collected information",
+ 80,
+ {"phase": "final_synthesis"},
)
try:
@@ -203,7 +217,9 @@ class RapidSearchStrategy(BaseSearchStrategy):
# First, we need a stub of current knowledge
# Use the citation handler to analyze the results
- result = self.citation_handler.analyze_initial(query, all_search_results)
+ result = self.citation_handler.analyze_initial(
+ query, all_search_results
+ )
if result:
synthesized_content = result["content"]
@@ -224,12 +240,16 @@ class RapidSearchStrategy(BaseSearchStrategy):
)
# Format the findings with search questions and sources
- formatted_findings = self.findings_repository.format_findings_to_text(
- findings, synthesized_content
+ formatted_findings = (
+ self.findings_repository.format_findings_to_text(
+ findings, synthesized_content
+ )
)
# Also add to the repository
- self.findings_repository.add_documents(result.get("documents", []))
+ self.findings_repository.add_documents(
+ result.get("documents", [])
+ )
else:
# Fallback if citation handler fails
synthesized_content = (
diff --git a/src/local_deep_research/advanced_search_system/strategies/recursive_decomposition_strategy.py b/src/local_deep_research/advanced_search_system/strategies/recursive_decomposition_strategy.py
index 49f36e5a62..ec53d84f3a 100644
--- a/src/local_deep_research/advanced_search_system/strategies/recursive_decomposition_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/recursive_decomposition_strategy.py
@@ -66,7 +66,9 @@ class RecursiveDecompositionStrategy(BaseSearchStrategy):
Dictionary containing analysis results
"""
if recursion_depth >= self.max_recursion_depth:
- logger.warning(f"Max recursion depth {self.max_recursion_depth} reached")
+ logger.warning(
+ f"Max recursion depth {self.max_recursion_depth} reached"
+ )
return self._use_source_based_strategy(query)
# Initialize tracking at top level
@@ -107,7 +109,9 @@ class RecursiveDecompositionStrategy(BaseSearchStrategy):
{
"phase": "decomposition",
"depth": recursion_depth,
- "subtask_count": len(decomposition_decision["subtasks"]),
+ "subtask_count": len(
+ decomposition_decision["subtasks"]
+ ),
},
)
@@ -226,7 +230,9 @@ When creating subtasks, ensure they maintain relevance to the original topic."""
)
# Update progress for UI
- progress = 20 + (recursion_depth * 10) + ((i + 1) / len(subtasks) * 40)
+ progress = (
+ 20 + (recursion_depth * 10) + ((i + 1) / len(subtasks) * 40)
+ )
if self.progress_callback:
self.progress_callback(
f"Processing subtask {i + 1}/{len(subtasks)}: {subtask[:50]}...",
@@ -271,7 +277,10 @@ When creating subtasks, ensure they maintain relevance to the original topic."""
return aggregated_result
def _aggregate_subtask_results(
- self, original_query: str, subtask_results: List[Dict], recursion_depth: int
+ self,
+ original_query: str,
+ subtask_results: List[Dict],
+ recursion_depth: int,
) -> Dict:
"""Aggregate results from multiple subtasks to answer the original query.
@@ -322,7 +331,9 @@ When creating subtasks, ensure they maintain relevance to the original topic."""
# Include master context for better synthesis
master_context_info = ""
if self.original_query and original_query != self.original_query:
- master_context_info = f"\nMaster Research Topic: {self.original_query}"
+ master_context_info = (
+ f"\nMaster Research Topic: {self.original_query}"
+ )
# Use LLM to synthesize final answer
synthesis_prompt = f"""Based on the following subtask results, provide a comprehensive answer to the original query.
@@ -426,10 +437,16 @@ Synthesize the information to directly answer the original query. Be specific an
# create an enhanced query that includes the context
enhanced_query = query
if self.original_query and query != self.original_query:
- enhanced_query = f"{query} (in the context of: {self.original_query})"
- logger.info(f"Enhanced query for source-based search: {enhanced_query}")
+ enhanced_query = (
+ f"{query} (in the context of: {self.original_query})"
+ )
+ logger.info(
+ f"Enhanced query for source-based search: {enhanced_query}"
+ )
else:
- logger.info(f"Using source-based strategy for direct search: {query}")
+ logger.info(
+ f"Using source-based strategy for direct search: {query}"
+ )
# Create a source-based strategy instance with specified parameters
source_strategy = SourceBasedSearchStrategy(
@@ -443,7 +460,9 @@ Synthesize the information to directly answer the original query. Be specific an
# Configure with our parameters
source_strategy.max_iterations = self.source_search_iterations
- source_strategy.questions_per_iteration = self.source_questions_per_iteration
+ source_strategy.questions_per_iteration = (
+ self.source_questions_per_iteration
+ )
# Copy our callback to maintain UI integration
if self.progress_callback:
@@ -454,7 +473,9 @@ Synthesize the information to directly answer the original query. Be specific an
# Update our tracking to maintain consistency with UI
if hasattr(source_strategy, "questions_by_iteration"):
- self.questions_by_iteration.extend(source_strategy.questions_by_iteration)
+ self.questions_by_iteration.extend(
+ source_strategy.questions_by_iteration
+ )
# Ensure results have the fields the UI expects
if "findings" not in results:
diff --git a/src/local_deep_research/advanced_search_system/strategies/smart_decomposition_strategy.py b/src/local_deep_research/advanced_search_system/strategies/smart_decomposition_strategy.py
index 42bb98008d..75c097b7ed 100644
--- a/src/local_deep_research/advanced_search_system/strategies/smart_decomposition_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/smart_decomposition_strategy.py
@@ -80,7 +80,10 @@ class SmartDecompositionStrategy(BaseSearchStrategy):
self.progress_callback(
f"Analyzing query type: {query_type.value}",
5,
- {"phase": "query_classification", "query_type": query_type.value},
+ {
+ "phase": "query_classification",
+ "query_type": query_type.value,
+ },
)
# Choose and execute appropriate strategy
@@ -203,7 +206,9 @@ KEY_CHARACTERISTICS: [list main characteristics]
lower_query = query.lower()
indicator_count = sum(
- 1 for indicator in browsecomp_indicators if indicator.lower() in lower_query
+ 1
+ for indicator in browsecomp_indicators
+ if indicator.lower() in lower_query
)
# If 3+ indicators present, likely BrowseComp-style
diff --git a/src/local_deep_research/advanced_search_system/strategies/smart_query_strategy.py b/src/local_deep_research/advanced_search_system/strategies/smart_query_strategy.py
index 1a22f67acb..9daeb363c3 100644
--- a/src/local_deep_research/advanced_search_system/strategies/smart_query_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/smart_query_strategy.py
@@ -3,7 +3,7 @@ Smart query generation strategy that works for any type of search target.
"""
import concurrent.futures
-from typing import Dict, List, Optional
+from typing import Dict, List
from loguru import logger
@@ -52,13 +52,18 @@ class SmartQueryStrategy(EarlyStopConstrainedStrategy):
def _generate_smart_query(self, constraints: List[Constraint]) -> str:
"""Use LLM to generate optimal search queries."""
constraint_text = "\n".join(
- [f"- {c.type.value}: {c.value} (weight: {c.weight})" for c in constraints]
+ [
+ f"- {c.type.value}: {c.value} (weight: {c.weight})"
+ for c in constraints
+ ]
)
# Build a list of already searched queries to avoid duplication
searched_list = list(self.searched_queries)[:10] # Show last 10 to LLM
already_searched = (
- "\n".join([f"- {q}" for q in searched_list]) if searched_list else "None"
+ "\n".join([f"- {q}" for q in searched_list])
+ if searched_list
+ else "None"
)
prompt = f"""
@@ -67,7 +72,7 @@ Analyze these search constraints and generate an optimal web search query:
Constraints:
{constraint_text}
-Target type: {getattr(self, 'entity_type', 'unknown')}
+Target type: {getattr(self, "entity_type", "unknown")}
Already searched queries (avoid these):
{already_searched}
@@ -89,7 +94,9 @@ Return only the search query, nothing else.
# Check if this query is too similar to existing ones
normalized_query = query.strip().lower()
if normalized_query in self.searched_queries:
- logger.info(f"LLM generated duplicate query, using fallback: {query}")
+ logger.info(
+ f"LLM generated duplicate query, using fallback: {query}"
+ )
return self._build_standard_query(constraints)
logger.info(f"LLM generated query: {query}")
@@ -136,7 +143,7 @@ Return only the search query, nothing else.
return " ".join(query_parts)
- def _execute_combination_search(self, combo: "SearchCombination") -> List:
+ def _execute_combination_search(self, combo) -> List:
"""Override to generate multiple query variations per combination."""
all_candidates = []
@@ -163,7 +170,9 @@ Return only the search query, nothing else.
for query, future in futures:
try:
results = future.result()
- candidates = self._extract_candidates_from_results(results)
+ candidates = self._extract_candidates_from_results(
+ results
+ )
all_candidates.extend(candidates)
logger.info(
@@ -178,7 +187,9 @@ Return only the search query, nothing else.
return all_candidates
- def _generate_query_variations(self, constraints: List[Constraint]) -> List[str]:
+ def _generate_query_variations(
+ self, constraints: List[Constraint]
+ ) -> List[str]:
"""Generate multiple query variations for better coverage."""
# Handle single constraint case
if isinstance(constraints, Constraint):
@@ -191,7 +202,9 @@ Return only the search query, nothing else.
# Build a list of already searched queries to avoid duplication
searched_list = list(self.searched_queries)[:20] # Show last 20 to LLM
already_searched = (
- "\n".join([f"- {q}" for q in searched_list]) if searched_list else "None"
+ "\n".join([f"- {q}" for q in searched_list])
+ if searched_list
+ else "None"
)
prompt = f"""
@@ -226,7 +239,9 @@ Provide each query on a separate line.
unique_queries.append(query)
self.query_variations.add(normalized)
else:
- logger.info(f"Filtering out duplicate query variation: {query}")
+ logger.info(
+ f"Filtering out duplicate query variation: {query}"
+ )
# If all queries were duplicates, generate a fallback
if not unique_queries:
@@ -250,7 +265,7 @@ Provide each query on a separate line.
# Use LLM to extract relevant entities/topics from the content
prompt = f"""
-From the following search results, extract all relevant entities, topics, or answers that match our search target type: {getattr(self, 'entity_type', 'unknown')}
+From the following search results, extract all relevant entities, topics, or answers that match our search target type: {getattr(self, "entity_type", "unknown")}
Content:
{content}
@@ -354,7 +369,9 @@ Provide one name per line. Be specific with actual character/entity names.
# Look for exact matches
for candidate in candidates:
if seed.lower() in candidate.name.lower():
- logger.info(f"Found seeded entity: {candidate.name}")
+ logger.info(
+ f"Found seeded entity: {candidate.name}"
+ )
# Evaluate immediately
if hasattr(self, "_evaluate_candidate_immediately"):
self._evaluate_candidate_immediately(candidate)
@@ -372,7 +389,10 @@ Provide one name per line. Be specific with actual character/entity names.
property_queries = []
for constraint in self.constraint_ranking:
- if constraint.weight > 0.7 and constraint.type == ConstraintType.PROPERTY:
+ if (
+ constraint.weight > 0.7
+ and constraint.type == ConstraintType.PROPERTY
+ ):
# Create specific property-based queries
if (
"elastic" in constraint.value.lower()
@@ -389,14 +409,22 @@ Provide one name per line. Be specific with actual character/entity names.
"voice" in constraint.value.lower()
or "actor" in constraint.value.lower()
):
- property_queries.append(f"{constraint.value} {self.entity_type}")
+ property_queries.append(
+ f"{constraint.value} {self.entity_type}"
+ )
# Execute property searches
if property_queries:
- logger.info(f"Executing direct property searches: {property_queries}")
- with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
+ logger.info(
+ f"Executing direct property searches: {property_queries}"
+ )
+ with concurrent.futures.ThreadPoolExecutor(
+ max_workers=3
+ ) as executor:
futures = []
- for query in property_queries[:3]: # Limit to avoid too many searches
+ for query in property_queries[
+ :3
+ ]: # Limit to avoid too many searches
if query.lower() not in self.searched_queries:
self.searched_queries.add(query.lower())
future = executor.submit(self._execute_search, query)
@@ -405,7 +433,9 @@ Provide one name per line. Be specific with actual character/entity names.
for future in futures:
try:
results = future.result()
- candidates = self._extract_candidates_from_results(results)
+ candidates = self._extract_candidates_from_results(
+ results
+ )
for candidate in candidates:
if hasattr(self, "_evaluate_candidate_immediately"):
@@ -433,15 +463,21 @@ Provide one name per line. Be specific with actual character/entity names.
try:
results = self._execute_search(query)
- candidates = self._extract_candidates_from_results(results)
+ candidates = self._extract_candidates_from_results(
+ results
+ )
for candidate in candidates:
if entity_name.lower() in candidate.name.lower():
logger.info(
f"Found target entity in fallback: {candidate.name}"
)
- if hasattr(self, "_evaluate_candidate_immediately"):
- self._evaluate_candidate_immediately(candidate)
+ if hasattr(
+ self, "_evaluate_candidate_immediately"
+ ):
+ self._evaluate_candidate_immediately(
+ candidate
+ )
# Check for early stop
if (
@@ -471,5 +507,9 @@ Provide one name per line. Be specific with actual character/entity names.
super()._progressive_constraint_search()
# If still no good results, try name-based fallback
- if hasattr(self, "best_score") and self.best_score < 0.9 and self.entity_seeds:
+ if (
+ hasattr(self, "best_score")
+ and self.best_score < 0.9
+ and self.entity_seeds
+ ):
self._perform_entity_name_search()
diff --git a/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py b/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py
index 8bf654256e..55dc4dbae4 100644
--- a/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py
@@ -92,9 +92,7 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
Analyze a topic using source-based search strategy.
"""
logger.info(f"Starting source-based research on topic: {query}")
- accumulated_search_results_across_all_iterations = (
- []
- ) # tracking links across iterations but not global
+ accumulated_search_results_across_all_iterations = [] # tracking links across iterations but not global
findings = []
total_citation_count_before_this_search = len(self.all_links_of_system)
@@ -125,10 +123,14 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
iterations_to_run = int(iterations_to_run)
try:
filtered_search_results = []
- total_citation_count_before_this_search = len(self.all_links_of_system)
+ total_citation_count_before_this_search = len(
+ self.all_links_of_system
+ )
# Run each iteration
for iteration in range(1, iterations_to_run + 1):
- iteration_progress_base = 5 + (iteration - 1) * (70 / iterations_to_run)
+ iteration_progress_base = 5 + (iteration - 1) * (
+ 70 / iterations_to_run
+ )
self._update_progress(
f"Starting iteration {iteration}/{iterations_to_run}",
@@ -146,7 +148,9 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
# For first iteration, use initial query
if iteration == 1:
# Generate questions for first iteration
- context = f"""Iteration: {iteration} of {iterations_to_run}"""
+ context = (
+ f"""Iteration: {iteration} of {iterations_to_run}"""
+ )
questions = self.question_generator.generate_questions(
current_knowledge=context,
query=query,
@@ -176,7 +180,9 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
elif iterations_to_run == 1:
context = ""
else:
- context = f"""Iteration: {iteration} of {iterations_to_run}"""
+ context = (
+ f"""Iteration: {iteration} of {iterations_to_run}"""
+ )
# Use standard question generator with search results as context
questions = self.question_generator.generate_questions(
current_knowledge=context,
@@ -252,7 +258,10 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
self._update_progress(
f"Filtering search results for iteration {iteration}",
iteration_progress_base + 45,
- {"phase": "cross_engine_filtering", "iteration": iteration},
+ {
+ "phase": "cross_engine_filtering",
+ "iteration": iteration,
+ },
)
existing_link_count = len(self.all_links_of_system)
@@ -308,13 +317,17 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
80,
{"phase": "final_filtering"},
)
- final_filtered_results = self.cross_engine_filter.filter_results(
- accumulated_search_results_across_all_iterations,
- query,
- reorder=True, # Always reorder in final filtering
- reindex=True, # Always reindex in final filtering
- max_results=int(get_db_setting("search.final_max_results") or 100),
- start_index=len(self.all_links_of_system),
+ final_filtered_results = (
+ self.cross_engine_filter.filter_results(
+ accumulated_search_results_across_all_iterations,
+ query,
+ reorder=True, # Always reorder in final filtering
+ reindex=True, # Always reindex in final filtering
+ max_results=int(
+ get_db_setting("search.final_max_results") or 100
+ ),
+ start_index=len(self.all_links_of_system),
+ )
)
self._update_progress(
f"Filtered from {len(accumulated_search_results_across_all_iterations)} to {len(final_filtered_results)} results",
@@ -348,7 +361,9 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
synthesized_content = final_citation_result["content"]
documents = final_citation_result.get("documents", [])
else:
- synthesized_content = "No relevant results found in final synthesis."
+ synthesized_content = (
+ "No relevant results found in final synthesis."
+ )
documents = []
# Add a final synthesis finding
@@ -370,8 +385,10 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
)
# Format findings
- formatted_findings = self.findings_repository.format_findings_to_text(
- findings, synthesized_content
+ formatted_findings = (
+ self.findings_repository.format_findings_to_text(
+ findings, synthesized_content
+ )
)
except Exception as e:
diff --git a/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py b/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
index b5e1284dde..e773b0b339 100644
--- a/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
@@ -19,7 +19,11 @@ class StandardSearchStrategy(BaseSearchStrategy):
"""Standard iterative search strategy that generates follow-up questions."""
def __init__(
- self, search=None, model=None, citation_handler=None, all_links_of_system=None
+ self,
+ search=None,
+ model=None,
+ citation_handler=None,
+ all_links_of_system=None,
):
"""Initialize with optional dependency injection for testing."""
super().__init__(all_links_of_system=all_links_of_system)
@@ -73,9 +77,7 @@ class StandardSearchStrategy(BaseSearchStrategy):
# Check if search engine is available
if self.search is None:
- error_msg = (
- "Error: No search engine available. Please check your configuration."
- )
+ error_msg = "Error: No search engine available. Please check your configuration."
self._update_progress(
error_msg,
100,
@@ -127,7 +129,9 @@ Iteration: {iteration + 1} of {total_iterations}"""
)
for q_idx, question in enumerate(questions):
question_progress_base = iteration_progress_base + (
- ((q_idx + 1) / question_count) * (100 / total_iterations) * 0.5
+ ((q_idx + 1) / question_count)
+ * (100 / total_iterations)
+ * 0.5
)
self._update_progress(
@@ -156,7 +160,9 @@ Iteration: {iteration + 1} of {total_iterations}"""
except Exception as e:
error_msg = f"Error during search: {str(e)}"
logger.exception(f"SEARCH ERROR: {error_msg}")
- self._handle_search_error(error_msg, question_progress_base + 10)
+ self._handle_search_error(
+ error_msg, question_progress_base + 10
+ )
search_results = []
if search_results is None:
@@ -171,7 +177,10 @@ Iteration: {iteration + 1} of {total_iterations}"""
self._update_progress(
f"Found {len(search_results)} results for question: {question}",
int(question_progress_base + 2),
- {"phase": "search_complete", "result_count": len(search_results)},
+ {
+ "phase": "search_complete",
+ "result_count": len(search_results),
+ },
)
logger.info(f"len search: {len(search_results)}")
@@ -240,7 +249,9 @@ Iteration: {iteration + 1} of {total_iterations}"""
except Exception as e:
error_msg = f"Error analyzing results: {str(e)}"
logger.exception(f"ANALYSIS ERROR: {error_msg}")
- self._handle_search_error(error_msg, question_progress_base + 10)
+ self._handle_search_error(
+ error_msg, question_progress_base + 10
+ )
iteration += 1
@@ -250,11 +261,16 @@ Iteration: {iteration + 1} of {total_iterations}"""
{"phase": "knowledge_compression"},
)
- if knowledge_accumulation == KnowledgeAccumulationApproach.ITERATION.value:
+ if (
+ knowledge_accumulation
+ == KnowledgeAccumulationApproach.ITERATION.value
+ ):
try:
logger.info("ITERATION - Compressing Knowledge")
- current_knowledge = self.knowledge_generator.compress_knowledge(
- current_knowledge, query, section_links
+ current_knowledge = (
+ self.knowledge_generator.compress_knowledge(
+ current_knowledge, query, section_links
+ )
)
logger.info("FINISHED ITERATION - Compressing Knowledge")
except Exception as e:
@@ -271,7 +287,9 @@ Iteration: {iteration + 1} of {total_iterations}"""
)
# Extract content from findings for synthesis
- finding_contents = [f["content"] for f in findings if "content" in f]
+ finding_contents = [
+ f["content"] for f in findings if "content" in f
+ ]
# First synthesize findings to get coherent content
synthesized_content = self.findings_repository.synthesize_findings(
@@ -288,8 +306,10 @@ Iteration: {iteration + 1} of {total_iterations}"""
)
# Now format the findings with search questions and sources
- formatted_findings = self.findings_repository.format_findings_to_text(
- findings, synthesized_content
+ formatted_findings = (
+ self.findings_repository.format_findings_to_text(
+ findings, synthesized_content
+ )
)
# Add the synthesized content to the repository
diff --git a/src/local_deep_research/advanced_search_system/tools/base_tool.py b/src/local_deep_research/advanced_search_system/tools/base_tool.py
index 3d868157ae..47f3f94407 100644
--- a/src/local_deep_research/advanced_search_system/tools/base_tool.py
+++ b/src/local_deep_research/advanced_search_system/tools/base_tool.py
@@ -75,7 +75,10 @@ class BaseTool(ABC):
logger.error(f"Invalid type for parameter {param_name}")
return False
- if "enum" in param_schema and param_value not in param_schema["enum"]:
+ if (
+ "enum" in param_schema
+ and param_value not in param_schema["enum"]
+ ):
logger.error(f"Invalid value for parameter {param_name}")
return False
@@ -97,4 +100,6 @@ class BaseTool(ABC):
Args:
result: The result of the tool execution
"""
- logger.info(f"Tool {self.name} execution completed with result: {result}")
+ logger.info(
+ f"Tool {self.name} execution completed with result: {result}"
+ )
diff --git a/src/local_deep_research/api/benchmark_functions.py b/src/local_deep_research/api/benchmark_functions.py
index 794d36fdd7..2fd8fee06a 100644
--- a/src/local_deep_research/api/benchmark_functions.py
+++ b/src/local_deep_research/api/benchmark_functions.py
@@ -235,7 +235,9 @@ def compare_configurations(
import time
timestamp = time.strftime("%Y%m%d_%H%M%S")
- report_file = os.path.join(output_dir, f"comparison_{dataset_type}_{timestamp}.md")
+ report_file = os.path.join(
+ output_dir, f"comparison_{dataset_type}_{timestamp}.md"
+ )
with open(report_file, "w") as f:
f.write(f"# Configuration Comparison - {dataset_type.capitalize()}\n\n")
@@ -247,7 +249,9 @@ def compare_configurations(
for result in results:
accuracy = result.get("metrics", {}).get("accuracy", 0)
- avg_time = result.get("metrics", {}).get("average_processing_time", 0)
+ avg_time = result.get("metrics", {}).get(
+ "average_processing_time", 0
+ )
examples = result.get("total_examples", 0)
f.write(
diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.py
index 9584c9be22..ba67113771 100644
--- a/src/local_deep_research/api/research_functions.py
+++ b/src/local_deep_research/api/research_functions.py
@@ -221,7 +221,9 @@ def analyze_documents(
# Force reindex if requested
if force_reindex and hasattr(search, "embedding_manager"):
for folder_path in search.folder_paths:
- search.embedding_manager.index_folder(folder_path, force_reindex=True)
+ search.embedding_manager.index_folder(
+ folder_path, force_reindex=True
+ )
# Perform the search
results = search.run(query)
@@ -236,7 +238,8 @@ def analyze_documents(
docs_text = "\n\n".join(
[
- f"Document {i + 1}:" f" {doc.get('content', doc.get('snippet', ''))[:1000]}"
+ f"Document {i + 1}:"
+ f" {doc.get('content', doc.get('snippet', ''))[:1000]}"
for i, doc in enumerate(results[:5])
]
) # Limit to first 5 docs and 1000 chars each
@@ -270,7 +273,9 @@ def analyze_documents(
f.write(f"## Documents Found: {len(results)}\n\n")
for i, doc in enumerate(results):
- f.write(f"### Document {i + 1}:" f" {doc.get('title', 'Untitled')}\n\n")
+ f.write(
+ f"### Document {i + 1}: {doc.get('title', 'Untitled')}\n\n"
+ )
f.write(f"**Source:** {doc.get('link', 'Unknown')}\n\n")
f.write(
f"**Content:**\n\n{doc.get('content', doc.get('snippet', 'No content available'))[:1000]}...\n\n"
diff --git a/src/local_deep_research/benchmarks/__init__.py b/src/local_deep_research/benchmarks/__init__.py
index 28fb37bf75..76156d9a5d 100644
--- a/src/local_deep_research/benchmarks/__init__.py
+++ b/src/local_deep_research/benchmarks/__init__.py
@@ -25,7 +25,11 @@ from .optimization import (
optimize_for_speed,
optimize_parameters,
)
-from .runners import run_benchmark, run_browsecomp_benchmark, run_simpleqa_benchmark
+from .runners import (
+ run_benchmark,
+ run_browsecomp_benchmark,
+ run_simpleqa_benchmark,
+)
__all__ = [
# Core benchmark functionality
diff --git a/src/local_deep_research/benchmarks/benchmark_functions.py b/src/local_deep_research/benchmarks/benchmark_functions.py
index ae85cb4520..21f5f3f0c7 100644
--- a/src/local_deep_research/benchmarks/benchmark_functions.py
+++ b/src/local_deep_research/benchmarks/benchmark_functions.py
@@ -300,7 +300,9 @@ def compare_configurations(
import time
timestamp = time.strftime("%Y%m%d_%H%M%S")
- report_file = os.path.join(output_dir, f"comparison_{dataset_type}_{timestamp}.md")
+ report_file = os.path.join(
+ output_dir, f"comparison_{dataset_type}_{timestamp}.md"
+ )
with open(report_file, "w") as f:
f.write(f"# Configuration Comparison - {dataset_type.capitalize()}\n\n")
@@ -312,7 +314,9 @@ def compare_configurations(
for result in results:
accuracy = result.get("metrics", {}).get("accuracy", 0)
- avg_time = result.get("metrics", {}).get("average_processing_time", 0)
+ avg_time = result.get("metrics", {}).get(
+ "average_processing_time", 0
+ )
examples = result.get("total_examples", 0)
f.write(
diff --git a/src/local_deep_research/benchmarks/cli.py b/src/local_deep_research/benchmarks/cli.py
index c651265295..d4383c15c4 100644
--- a/src/local_deep_research/benchmarks/cli.py
+++ b/src/local_deep_research/benchmarks/cli.py
@@ -10,7 +10,6 @@ import logging
import os
import sys
from datetime import datetime
-from typing import Any, Dict, List, Optional
from .comparison import compare_configurations
from .efficiency import ResourceMonitor, SpeedProfiler
@@ -18,7 +17,8 @@ from .optimization import optimize_parameters
# Configure logging
logging.basicConfig(
- level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+ level=logging.INFO,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
@@ -44,7 +44,9 @@ Examples:
subparsers = parser.add_subparsers(dest="command", help="Command to run")
# Optimizer parser
- optimize_parser = subparsers.add_parser("optimize", help="Optimize parameters")
+ optimize_parser = subparsers.add_parser(
+ "optimize", help="Optimize parameters"
+ )
optimize_parser.add_argument("query", help="Research query to optimize for")
optimize_parser.add_argument(
"--output-dir",
@@ -67,21 +69,32 @@ Examples:
"--timeout", type=int, help="Maximum seconds to run optimization"
)
optimize_parser.add_argument(
- "--n-jobs", type=int, default=1, help="Number of parallel jobs for optimization"
+ "--n-jobs",
+ type=int,
+ default=1,
+ help="Number of parallel jobs for optimization",
+ )
+ optimize_parser.add_argument(
+ "--study-name", help="Name of the Optuna study"
)
- optimize_parser.add_argument("--study-name", help="Name of the Optuna study")
optimize_parser.add_argument(
"--speed-focus", action="store_true", help="Focus optimization on speed"
)
optimize_parser.add_argument(
- "--quality-focus", action="store_true", help="Focus optimization on quality"
+ "--quality-focus",
+ action="store_true",
+ help="Focus optimization on quality",
)
# Comparison parser
- compare_parser = subparsers.add_parser("compare", help="Compare configurations")
+ compare_parser = subparsers.add_parser(
+ "compare", help="Compare configurations"
+ )
compare_parser.add_argument("query", help="Research query to compare with")
compare_parser.add_argument(
- "--configs", required=True, help="JSON file with configurations to compare"
+ "--configs",
+ required=True,
+ help="JSON file with configurations to compare",
)
compare_parser.add_argument(
"--output-dir",
@@ -99,7 +112,9 @@ Examples:
)
# Profiling parser
- profile_parser = subparsers.add_parser("profile", help="Profile resource usage")
+ profile_parser = subparsers.add_parser(
+ "profile", help="Profile resource usage"
+ )
profile_parser.add_argument("query", help="Research query to profile")
profile_parser.add_argument(
"--output-dir",
@@ -203,7 +218,9 @@ def run_comparison(args):
for i, result in enumerate(
[r for r in results["results"] if r.get("success", False)]
):
- print(f"{i+1}. {result['name']}: {result.get('overall_score', 0):.4f}")
+ print(
+ f"{i + 1}. {result['name']}: {result.get('overall_score', 0):.4f}"
+ )
print(f"\nResults saved to: {results.get('report_path', args.output_dir)}")
@@ -275,12 +292,18 @@ def run_profiling(args):
if name != "total_duration" and name.endswith("_duration"):
component = name.replace("_duration", "")
duration = value
- percent = (duration / total_duration * 100) if total_duration > 0 else 0
+ percent = (
+ (duration / total_duration * 100)
+ if total_duration > 0
+ else 0
+ )
print(f"- {component}: {duration:.2f}s ({percent:.1f}%)")
# Resource summary
print("\nResource Usage Summary:")
- print(f"Peak memory: {resource_results.get('process_memory_max_mb', 0):.1f} MB")
+ print(
+ f"Peak memory: {resource_results.get('process_memory_max_mb', 0):.1f} MB"
+ )
print(
f"Average memory: {resource_results.get('process_memory_avg_mb', 0):.1f} MB"
)
@@ -308,7 +331,9 @@ def run_profiling(args):
"timing_results": timing_results,
"resource_results": resource_results,
"findings_count": len(results.get("findings", [])),
- "knowledge_length": len(results.get("current_knowledge", "")),
+ "knowledge_length": len(
+ results.get("current_knowledge", "")
+ ),
"timestamp": timestamp,
},
f,
diff --git a/src/local_deep_research/benchmarks/cli/benchmark_commands.py b/src/local_deep_research/benchmarks/cli/benchmark_commands.py
index 931d7cafb5..4955a5e61f 100644
--- a/src/local_deep_research/benchmarks/cli/benchmark_commands.py
+++ b/src/local_deep_research/benchmarks/cli/benchmark_commands.py
@@ -38,7 +38,10 @@ def setup_benchmark_parser(subparsers):
help="Number of search iterations (default: 3)",
)
benchmark_parent.add_argument(
- "--questions", type=int, default=3, help="Questions per iteration (default: 3)"
+ "--questions",
+ type=int,
+ default=3,
+ help="Questions per iteration (default: 3)",
)
benchmark_parent.add_argument(
"--search-tool",
@@ -75,7 +78,9 @@ def setup_benchmark_parser(subparsers):
"--search-model", type=str, help="Model to use for the search system"
)
benchmark_parent.add_argument(
- "--search-provider", type=str, help="Provider to use for the search system"
+ "--search-provider",
+ type=str,
+ help="Provider to use for the search system",
)
benchmark_parent.add_argument(
"--endpoint-url",
@@ -98,12 +103,16 @@ def setup_benchmark_parser(subparsers):
# BrowseComp benchmark command
browsecomp_parser = subparsers.add_parser(
- "browsecomp", parents=[benchmark_parent], help="Run BrowseComp benchmark"
+ "browsecomp",
+ parents=[benchmark_parent],
+ help="Run BrowseComp benchmark",
)
browsecomp_parser.set_defaults(func=run_browsecomp_cli)
# List available benchmarks command
- list_parser = subparsers.add_parser("list", help="List available benchmarks")
+ list_parser = subparsers.add_parser(
+ "list", help="List available benchmarks"
+ )
list_parser.set_defaults(func=list_benchmarks_cli)
# Compare configurations command
@@ -308,11 +317,14 @@ def main():
Main entry point for benchmark CLI.
"""
parser = argparse.ArgumentParser(
- description="Local Deep Research Benchmarking Tool", prog="ldr-benchmark"
+ description="Local Deep Research Benchmarking Tool",
+ prog="ldr-benchmark",
)
# Set up logging
- parser.add_argument("--verbose", action="store_true", help="Enable verbose logging")
+ parser.add_argument(
+ "--verbose", action="store_true", help="Enable verbose logging"
+ )
# Create subparsers
subparsers = parser.add_subparsers(
@@ -328,7 +340,8 @@ def main():
# Set up logging
log_level = logging.DEBUG if args.verbose else logging.INFO
logging.basicConfig(
- level=log_level, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+ level=log_level,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
# Run command
diff --git a/src/local_deep_research/benchmarks/comparison/__init__.py b/src/local_deep_research/benchmarks/comparison/__init__.py
index ebf4b86a6e..e492cfc803 100644
--- a/src/local_deep_research/benchmarks/comparison/__init__.py
+++ b/src/local_deep_research/benchmarks/comparison/__init__.py
@@ -5,7 +5,9 @@ This module provides tools for comparing the performance of different
parameters, models, and search engines.
"""
-from local_deep_research.benchmarks.comparison.evaluator import compare_configurations
+from local_deep_research.benchmarks.comparison.evaluator import (
+ compare_configurations,
+)
__all__ = [
"compare_configurations",
diff --git a/src/local_deep_research/benchmarks/comparison/evaluator.py b/src/local_deep_research/benchmarks/comparison/evaluator.py
index cbcea55f04..b31506acdf 100644
--- a/src/local_deep_research/benchmarks/comparison/evaluator.py
+++ b/src/local_deep_research/benchmarks/comparison/evaluator.py
@@ -8,15 +8,19 @@ and evaluating their performance across various metrics.
import json
import logging
import os
-import time
from datetime import datetime
-from typing import Any, Dict, List, Optional, Tuple
+from typing import Any, Dict, List, Optional
import matplotlib.pyplot as plt
+from matplotlib.patches import Circle, RegularPolygon
import numpy as np
-from local_deep_research.benchmarks.efficiency.resource_monitor import ResourceMonitor
-from local_deep_research.benchmarks.efficiency.speed_profiler import SpeedProfiler
+from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+)
+from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+)
from local_deep_research.benchmarks.optimization.metrics import (
calculate_combined_score,
calculate_quality_metrics,
@@ -76,17 +80,21 @@ def compare_configurations(
# Process each configuration
for i, config in enumerate(configurations):
- logger.info(f"Evaluating configuration {i+1}/{len(configurations)}: {config}")
+ logger.info(
+ f"Evaluating configuration {i + 1}/{len(configurations)}: {config}"
+ )
# Name for this configuration
- config_name = config.get("name", f"Configuration {i+1}")
+ config_name = config.get("name", f"Configuration {i + 1}")
# Results for all repetitions of this configuration
config_results = []
# Run multiple repetitions
for rep in range(repetitions):
- logger.info(f"Starting repetition {rep+1}/{repetitions} for {config_name}")
+ logger.info(
+ f"Starting repetition {rep + 1}/{repetitions} for {config_name}"
+ )
try:
# Run the configuration
@@ -99,17 +107,21 @@ def compare_configurations(
)
config_results.append(result)
- logger.info(f"Completed repetition {rep+1} for {config_name}")
+ logger.info(f"Completed repetition {rep + 1} for {config_name}")
except Exception as e:
- logger.error(f"Error in {config_name}, repetition {rep+1}: {str(e)}")
+ logger.error(
+ f"Error in {config_name}, repetition {rep + 1}: {str(e)}"
+ )
# Add error info but continue with other configurations
config_results.append({"error": str(e), "success": False})
# Calculate aggregate metrics across repetitions
if config_results:
# Filter out failed runs
- successful_runs = [r for r in config_results if r.get("success", False)]
+ successful_runs = [
+ r for r in config_results if r.get("success", False)
+ ]
if successful_runs:
# Calculate average metrics
@@ -175,7 +187,9 @@ def compare_configurations(
# Save results to file
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
- result_file = os.path.join(output_dir, f"comparison_results_{timestamp}.json")
+ result_file = os.path.join(
+ output_dir, f"comparison_results_{timestamp}.json"
+ )
with open(result_file, "w") as f:
json.dump(comparison_report, f, indent=2)
@@ -272,7 +286,9 @@ def _evaluate_single_configuration(
quality_metrics = calculate_quality_metrics(
results=results,
system_info={
- "all_links_of_system": getattr(system, "all_links_of_system", [])
+ "all_links_of_system": getattr(
+ system, "all_links_of_system", []
+ )
},
)
@@ -342,7 +358,11 @@ def _calculate_average_metrics(results: List[Dict[str, Any]]) -> Dict[str, Any]:
return {}
# Initialize average metrics
- avg_metrics = {"quality_metrics": {}, "speed_metrics": {}, "resource_metrics": {}}
+ avg_metrics = {
+ "quality_metrics": {},
+ "speed_metrics": {},
+ "resource_metrics": {},
+ }
# Quality metrics
quality_keys = set()
@@ -396,7 +416,9 @@ def _create_comparison_visualizations(
"""
# Check if there are successful results
successful_results = [
- r for r in comparison_report.get("results", []) if r.get("success", False)
+ r
+ for r in comparison_report.get("results", [])
+ if r.get("success", False)
]
if not successful_results:
@@ -405,7 +427,8 @@ def _create_comparison_visualizations(
# Extract configuration names
config_names = [
- r.get("name", f"Config {i+1}") for i, r in enumerate(successful_results)
+ r.get("name", f"Config {i + 1}")
+ for i, r in enumerate(successful_results)
]
# 1. Overall score comparison
@@ -419,7 +442,9 @@ def _create_comparison_visualizations(
plt.title("Configuration Performance Comparison")
plt.grid(axis="x", linestyle="--", alpha=0.7)
plt.tight_layout()
- plt.savefig(os.path.join(output_dir, f"overall_score_comparison_{timestamp}.png"))
+ plt.savefig(
+ os.path.join(output_dir, f"overall_score_comparison_{timestamp}.png")
+ )
plt.close()
# 2. Quality metrics comparison
@@ -445,14 +470,20 @@ def _create_comparison_visualizations(
)
# 4. Resource metrics comparison
- resource_metrics = ["overall_resource", "process_memory_max_mb", "system_cpu_avg"]
+ resource_metrics = [
+ "overall_resource",
+ "process_memory_max_mb",
+ "system_cpu_avg",
+ ]
_create_metric_comparison_chart(
successful_results,
config_names,
resource_metrics,
"resource_metrics",
"Resource Usage Comparison",
- os.path.join(output_dir, f"resource_metrics_comparison_{timestamp}.png"),
+ os.path.join(
+ output_dir, f"resource_metrics_comparison_{timestamp}.png"
+ ),
)
# 5. Spider chart for multi-dimensional comparison
@@ -489,7 +520,9 @@ def _create_metric_comparison_chart(
output_path: Path to save the chart
"""
# Create figure with multiple subplots (one per metric)
- fig, axes = plt.subplots(len(metric_keys), 1, figsize=(12, 5 * len(metric_keys)))
+ fig, axes = plt.subplots(
+ len(metric_keys), 1, figsize=(12, 5 * len(metric_keys))
+ )
# Handle case with only one metric
if len(metric_keys) == 1:
@@ -588,7 +621,9 @@ def _create_spider_chart(
(0.5, 0.5), num_vars, radius=0.5, edgecolor="k"
)
else:
- raise ValueError("Unknown value for 'frame': %s" % frame)
+ raise ValueError(
+ "Unknown value for 'frame': %s" % frame
+ )
def _gen_axes_spines(self):
if frame == "circle":
@@ -598,21 +633,27 @@ def _create_spider_chart(
verts = unit_poly_verts(num_vars)
vertices = [(0.5, 0.5)] + verts
codes = (
- [Path.MOVETO] + [Path.LINETO] * num_vars + [Path.CLOSEPOLY]
+ [Path.MOVETO]
+ + [Path.LINETO] * num_vars
+ + [Path.CLOSEPOLY]
)
path = Path(vertices, codes)
spine = Spine(self, spine_type, path)
spine.set_transform(self.transAxes)
return {"polar": spine}
else:
- raise ValueError("Unknown value for 'frame': %s" % frame)
+ raise ValueError(
+ "Unknown value for 'frame': %s" % frame
+ )
def unit_poly_verts(num_vars):
"""Return vertices of polygon for radar chart."""
verts = []
for i in range(num_vars):
angle = theta[i]
- verts.append((0.5 * (1 + np.cos(angle)), 0.5 * (1 + np.sin(angle))))
+ verts.append(
+ (0.5 * (1 + np.cos(angle)), 0.5 * (1 + np.sin(angle)))
+ )
return verts
register_projection(RadarAxes)
@@ -622,8 +663,14 @@ def _create_spider_chart(
metrics = [
{"name": "Quality", "key": "quality_metrics.overall_quality"},
{"name": "Speed", "key": "speed_metrics.overall_speed"},
- {"name": "Sources", "key": "quality_metrics.normalized_source_count"},
- {"name": "Content", "key": "quality_metrics.normalized_knowledge_length"},
+ {
+ "name": "Sources",
+ "key": "quality_metrics.normalized_source_count",
+ },
+ {
+ "name": "Content",
+ "key": "quality_metrics.normalized_knowledge_length",
+ },
{
"name": "Memory",
"key": "resource_metrics.normalized_memory_usage",
@@ -636,7 +683,9 @@ def _create_spider_chart(
num_vars = len(spoke_labels)
theta = radar_factory(num_vars)
- fig, ax = plt.subplots(figsize=(10, 10), subplot_kw=dict(projection="radar"))
+ fig, ax = plt.subplots(
+ figsize=(10, 10), subplot_kw=dict(projection="radar")
+ )
# Color map for different configurations
colors = plt.cm.viridis(np.linspace(0, 1, len(results)))
@@ -657,7 +706,13 @@ def _create_spider_chart(
values.append(value)
# Plot this configuration
- ax.plot(theta, values, color=colors[i], linewidth=2, label=config_names[i])
+ ax.plot(
+ theta,
+ values,
+ color=colors[i],
+ linewidth=2,
+ label=config_names[i],
+ )
ax.fill(theta, values, color=colors[i], alpha=0.25)
# Set chart properties
diff --git a/src/local_deep_research/benchmarks/datasets.py b/src/local_deep_research/benchmarks/datasets.py
index ba3dbc1e5b..b21ba6a40b 100644
--- a/src/local_deep_research/benchmarks/datasets.py
+++ b/src/local_deep_research/benchmarks/datasets.py
@@ -14,12 +14,7 @@ Notes on BrowseComp dataset:
3. Use a manual mapping for specific encrypted strings that have been verified
"""
-import logging
-from typing import Any, Dict, List, Optional
-
-from .datasets import DatasetRegistry, load_dataset
-
-logger = logging.getLogger(__name__)
+from .datasets import load_dataset
# Re-export the get_available_datasets function
# Re-export the default dataset URLs
diff --git a/src/local_deep_research/benchmarks/datasets/__init__.py b/src/local_deep_research/benchmarks/datasets/__init__.py
index 1e15f3b6ec..1915a36d2b 100644
--- a/src/local_deep_research/benchmarks/datasets/__init__.py
+++ b/src/local_deep_research/benchmarks/datasets/__init__.py
@@ -5,7 +5,7 @@ This module provides functions and classes for loading and processing
benchmark datasets in a maintainable, extensible way.
"""
-from .base import BenchmarkDataset, DatasetRegistry
+from .base import DatasetRegistry
from .browsecomp import BrowseCompDataset
from .simpleqa import SimpleQADataset
diff --git a/src/local_deep_research/benchmarks/datasets/base.py b/src/local_deep_research/benchmarks/datasets/base.py
index befde34845..3368f3d8c4 100644
--- a/src/local_deep_research/benchmarks/datasets/base.py
+++ b/src/local_deep_research/benchmarks/datasets/base.py
@@ -8,7 +8,7 @@ with benchmark datasets in a maintainable, extensible way.
import logging
import random
from abc import ABC, abstractmethod
-from typing import Any, Dict, List, Optional, Union
+from typing import Any, Dict, List, Optional
import pandas as pd
@@ -96,18 +96,22 @@ class BenchmarkDataset(ABC):
if self.dataset_path.endswith(".csv"):
df = pd.read_csv(self.dataset_path)
raw_examples = [row.to_dict() for _, row in df.iterrows()]
- elif self.dataset_path.endswith(".json") or self.dataset_path.endswith(
- ".jsonl"
- ):
+ elif self.dataset_path.endswith(
+ ".json"
+ ) or self.dataset_path.endswith(".jsonl"):
import json
with open(self.dataset_path, "r") as f:
if self.dataset_path.endswith(".jsonl"):
- raw_examples = [json.loads(line) for line in f if line.strip()]
+ raw_examples = [
+ json.loads(line) for line in f if line.strip()
+ ]
else:
raw_examples = json.load(f)
else:
- raise ValueError(f"Unsupported file format: {self.dataset_path}")
+ raise ValueError(
+ f"Unsupported file format: {self.dataset_path}"
+ )
# Process each example
processed_examples = []
@@ -119,9 +123,13 @@ class BenchmarkDataset(ABC):
logger.error(f"Error processing example {i}: {e}")
# Sample if needed
- if self.num_examples and self.num_examples < len(processed_examples):
+ if self.num_examples and self.num_examples < len(
+ processed_examples
+ ):
random.seed(self.seed)
- sampled_examples = random.sample(processed_examples, self.num_examples)
+ sampled_examples = random.sample(
+ processed_examples, self.num_examples
+ )
logger.info(
f"Sampled {self.num_examples} examples out of {len(processed_examples)}"
)
@@ -162,7 +170,7 @@ class BenchmarkDataset(ABC):
examples = self.get_examples()
if index < 0 or index >= len(examples):
raise IndexError(
- f"Example index {index} out of range (0-{len(examples)-1})"
+ f"Example index {index} out of range (0-{len(examples) - 1})"
)
return examples[index]
diff --git a/src/local_deep_research/benchmarks/datasets/browsecomp.py b/src/local_deep_research/benchmarks/datasets/browsecomp.py
index 7269f78b25..ce86134e6a 100644
--- a/src/local_deep_research/benchmarks/datasets/browsecomp.py
+++ b/src/local_deep_research/benchmarks/datasets/browsecomp.py
@@ -59,7 +59,9 @@ class BrowseCompDataset(BenchmarkDataset):
# Get the canary string to use as the decryption key
canary = example.get("canary", "")
if not canary:
- logger.warning(f"No canary found for example, skipping decryption")
+ logger.warning(
+ "No canary found for example, skipping decryption"
+ )
return processed
# Decrypt problem
diff --git a/src/local_deep_research/benchmarks/datasets/custom_dataset_template.py b/src/local_deep_research/benchmarks/datasets/custom_dataset_template.py
index fa35026067..704c42c90f 100644
--- a/src/local_deep_research/benchmarks/datasets/custom_dataset_template.py
+++ b/src/local_deep_research/benchmarks/datasets/custom_dataset_template.py
@@ -8,7 +8,7 @@ Copy this file and modify it to create your own dataset class.
import logging
from typing import Any, Dict
-from .base import BenchmarkDataset, DatasetRegistry
+from .base import BenchmarkDataset
logger = logging.getLogger(__name__)
diff --git a/src/local_deep_research/benchmarks/datasets/utils.py b/src/local_deep_research/benchmarks/datasets/utils.py
index 8ccea83a64..5359f93746 100644
--- a/src/local_deep_research/benchmarks/datasets/utils.py
+++ b/src/local_deep_research/benchmarks/datasets/utils.py
@@ -8,7 +8,7 @@ decryption, encoding detection, etc.
import base64
import hashlib
import logging
-from typing import Any, Dict
+from typing import Dict
logger = logging.getLogger(__name__)
@@ -64,7 +64,10 @@ def decrypt(ciphertext_b64: str, password: str) -> str:
decrypted = bytes(a ^ b for a, b in zip(encrypted, key))
result = decrypted.decode("utf-8", errors="replace")
- if all(32 <= ord(c) < 127 for c in result[:50]) and " " in result[:50]:
+ if (
+ all(32 <= ord(c) < 127 for c in result[:50])
+ and " " in result[:50]
+ ):
logger.debug(
f"Successfully decrypted with alternate method 1: {result[:50]}..."
)
@@ -81,7 +84,10 @@ def decrypt(ciphertext_b64: str, password: str) -> str:
decrypted = bytes(a ^ b for a, b in zip(encrypted, key))
result = decrypted.decode("utf-8", errors="replace")
- if all(32 <= ord(c) < 127 for c in result[:50]) and " " in result[:50]:
+ if (
+ all(32 <= ord(c) < 127 for c in result[:50])
+ and " " in result[:50]
+ ):
logger.debug(
f"Successfully decrypted with GUID method: {result[:50]}..."
)
@@ -98,13 +104,17 @@ def decrypt(ciphertext_b64: str, password: str) -> str:
result = decrypted.decode("utf-8", errors="replace")
if all(32 <= ord(c) < 127 for c in result[:50]) and " " in result[:50]:
- logger.debug(f"Successfully decrypted with hardcoded key: {result[:50]}...")
+ logger.debug(
+ f"Successfully decrypted with hardcoded key: {result[:50]}..."
+ )
return result
except Exception:
pass
# If all attempts fail, return the original
- logger.debug(f"All decryption attempts failed for: {ciphertext_b64[:20]}...")
+ logger.debug(
+ f"All decryption attempts failed for: {ciphertext_b64[:20]}..."
+ )
return ciphertext_b64
diff --git a/src/local_deep_research/benchmarks/efficiency/__init__.py b/src/local_deep_research/benchmarks/efficiency/__init__.py
index 0446e9f9b4..73c65bd71e 100644
--- a/src/local_deep_research/benchmarks/efficiency/__init__.py
+++ b/src/local_deep_research/benchmarks/efficiency/__init__.py
@@ -5,8 +5,12 @@ This module provides tools for measuring and optimizing execution speed
and resource usage of the research system.
"""
-from local_deep_research.benchmarks.efficiency.resource_monitor import ResourceMonitor
-from local_deep_research.benchmarks.efficiency.speed_profiler import SpeedProfiler
+from local_deep_research.benchmarks.efficiency.resource_monitor import (
+ ResourceMonitor,
+)
+from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+)
__all__ = [
"SpeedProfiler",
diff --git a/src/local_deep_research/benchmarks/efficiency/resource_monitor.py b/src/local_deep_research/benchmarks/efficiency/resource_monitor.py
index d7e64ba608..3215127e21 100644
--- a/src/local_deep_research/benchmarks/efficiency/resource_monitor.py
+++ b/src/local_deep_research/benchmarks/efficiency/resource_monitor.py
@@ -9,7 +9,7 @@ import logging
import threading
import time
from contextlib import contextmanager
-from typing import Any, Callable, Dict, List, Optional, Tuple
+from typing import Any, Dict
logger = logging.getLogger(__name__)
@@ -69,7 +69,9 @@ class ResourceMonitor:
def start(self):
"""Start monitoring resource usage."""
if not self.can_monitor:
- logger.warning("Resource monitoring not available (psutil not installed)")
+ logger.warning(
+ "Resource monitoring not available (psutil not installed)"
+ )
return
if self.monitoring:
@@ -129,7 +131,9 @@ class ResourceMonitor:
"cpu_percent": process_cpu,
"memory_rss": process_memory.rss, # Resident Set Size in bytes
"memory_vms": process_memory.vms, # Virtual Memory Size in bytes
- "memory_shared": getattr(process_memory, "shared", 0),
+ "memory_shared": getattr(
+ process_memory, "shared", 0
+ ),
"num_threads": current_process.num_threads(),
"open_files": len(current_process.open_files()),
"status": current_process.status(),
@@ -189,7 +193,6 @@ class ResourceMonitor:
return {}
# Extract data series
- timestamps = [d["timestamp"] for d in self.process_data]
cpu_values = [d["cpu_percent"] for d in self.process_data]
memory_values = [
d["memory_rss"] / (1024 * 1024) for d in self.process_data
@@ -199,15 +202,21 @@ class ResourceMonitor:
stats = {
"start_time": self.start_time,
"end_time": self.end_time,
- "duration": self.end_time - self.start_time if self.end_time else None,
+ "duration": self.end_time - self.start_time
+ if self.end_time
+ else None,
"sample_count": len(self.process_data),
"cpu_min": min(cpu_values) if cpu_values else None,
"cpu_max": max(cpu_values) if cpu_values else None,
- "cpu_avg": sum(cpu_values) / len(cpu_values) if cpu_values else None,
+ "cpu_avg": sum(cpu_values) / len(cpu_values)
+ if cpu_values
+ else None,
"memory_min_mb": min(memory_values) if memory_values else None,
"memory_max_mb": max(memory_values) if memory_values else None,
"memory_avg_mb": (
- sum(memory_values) / len(memory_values) if memory_values else None
+ sum(memory_values) / len(memory_values)
+ if memory_values
+ else None
),
"thread_max": (
max(d["num_threads"] for d in self.process_data)
@@ -229,7 +238,6 @@ class ResourceMonitor:
return {}
# Extract data series
- timestamps = [d["timestamp"] for d in self.system_data]
cpu_values = [d["cpu_percent"] for d in self.system_data]
memory_values = [d["memory_percent"] for d in self.system_data]
disk_values = [d["disk_percent"] for d in self.system_data]
@@ -238,15 +246,21 @@ class ResourceMonitor:
stats = {
"start_time": self.start_time,
"end_time": self.end_time,
- "duration": self.end_time - self.start_time if self.end_time else None,
+ "duration": self.end_time - self.start_time
+ if self.end_time
+ else None,
"sample_count": len(self.system_data),
"cpu_min": min(cpu_values) if cpu_values else None,
"cpu_max": max(cpu_values) if cpu_values else None,
- "cpu_avg": sum(cpu_values) / len(cpu_values) if cpu_values else None,
+ "cpu_avg": sum(cpu_values) / len(cpu_values)
+ if cpu_values
+ else None,
"memory_min_percent": min(memory_values) if memory_values else None,
"memory_max_percent": max(memory_values) if memory_values else None,
"memory_avg_percent": (
- sum(memory_values) / len(memory_values) if memory_values else None
+ sum(memory_values) / len(memory_values)
+ if memory_values
+ else None
),
"disk_min_percent": min(disk_values) if disk_values else None,
"disk_max_percent": max(disk_values) if disk_values else None,
@@ -281,7 +295,9 @@ class ResourceMonitor:
stats = {
"start_time": self.start_time,
"end_time": self.end_time,
- "duration": self.end_time - self.start_time if self.end_time else None,
+ "duration": self.end_time - self.start_time
+ if self.end_time
+ else None,
}
# Add process stats with 'process_' prefix
@@ -299,7 +315,6 @@ class ResourceMonitor:
process_stats.get("memory_max_mb") is not None
and system_stats.get("memory_total_gb") is not None
):
-
# Process memory as percentage of total system memory
system_memory_mb = system_stats["memory_total_gb"] * 1024
stats["process_memory_percent"] = (
diff --git a/src/local_deep_research/benchmarks/efficiency/speed_profiler.py b/src/local_deep_research/benchmarks/efficiency/speed_profiler.py
index 4bc70194b1..c796164dd7 100644
--- a/src/local_deep_research/benchmarks/efficiency/speed_profiler.py
+++ b/src/local_deep_research/benchmarks/efficiency/speed_profiler.py
@@ -8,7 +8,7 @@ of different components and processes in the research system.
import logging
import time
from contextlib import contextmanager
-from typing import Any, Callable, Dict, List, Optional
+from typing import Any, Callable, Dict
logger = logging.getLogger(__name__)
@@ -120,7 +120,10 @@ class SpeedProfiler:
data["avg"] = data["total"] / data["count"]
# Add total duration
- if self.total_start_time is not None and self.total_end_time is not None:
+ if (
+ self.total_start_time is not None
+ and self.total_end_time is not None
+ ):
result["total"] = {
"total": self.total_end_time - self.total_start_time,
"count": 1,
@@ -146,10 +149,17 @@ class SpeedProfiler:
# Total duration
if "total" in timings:
summary["total_duration"] = timings["total"]["total"]
- elif self.total_start_time is not None and self.total_end_time is not None:
- summary["total_duration"] = self.total_end_time - self.total_start_time
+ elif (
+ self.total_start_time is not None
+ and self.total_end_time is not None
+ ):
+ summary["total_duration"] = (
+ self.total_end_time - self.total_start_time
+ )
else:
- summary["total_duration"] = sum(t["total"] for t in timings.values())
+ summary["total_duration"] = sum(
+ t["total"] for t in timings.values()
+ )
# Component durations
for name, data in timings.items():
diff --git a/src/local_deep_research/benchmarks/evaluators/browsecomp.py b/src/local_deep_research/benchmarks/evaluators/browsecomp.py
index d10fbb030b..9cb488dae7 100644
--- a/src/local_deep_research/benchmarks/evaluators/browsecomp.py
+++ b/src/local_deep_research/benchmarks/evaluators/browsecomp.py
@@ -47,7 +47,9 @@ class BrowseCompEvaluator(BaseBenchmarkEvaluator):
benchmark_dir = self._create_subdirectory(output_dir)
# Log benchmark execution
- logger.info(f"Running BrowseComp benchmark with {num_examples} examples")
+ logger.info(
+ f"Running BrowseComp benchmark with {num_examples} examples"
+ )
try:
# Run BrowseComp benchmark
diff --git a/src/local_deep_research/benchmarks/evaluators/composite.py b/src/local_deep_research/benchmarks/evaluators/composite.py
index aa8319a42f..db9c1b2f53 100644
--- a/src/local_deep_research/benchmarks/evaluators/composite.py
+++ b/src/local_deep_research/benchmarks/evaluators/composite.py
@@ -54,7 +54,9 @@ class CompositeBenchmarkEvaluator:
}
# Log the weights being used
- logger.info(f"Using normalized benchmark weights: {self.normalized_weights}")
+ logger.info(
+ f"Using normalized benchmark weights: {self.normalized_weights}"
+ )
def evaluate(
self,
@@ -105,7 +107,9 @@ class CompositeBenchmarkEvaluator:
combined_score += weighted_contribution
except Exception as e:
- logger.error(f"Error running {benchmark_name} benchmark: {str(e)}")
+ logger.error(
+ f"Error running {benchmark_name} benchmark: {str(e)}"
+ )
all_results[benchmark_name] = {
"benchmark_type": benchmark_name,
"error": str(e),
diff --git a/src/local_deep_research/benchmarks/evaluators/simpleqa.py b/src/local_deep_research/benchmarks/evaluators/simpleqa.py
index c09b1140d7..aab5fc73c4 100644
--- a/src/local_deep_research/benchmarks/evaluators/simpleqa.py
+++ b/src/local_deep_research/benchmarks/evaluators/simpleqa.py
@@ -9,9 +9,8 @@ import json
import logging
import os
import time
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict
-from local_deep_research.api import quick_summary
from ..datasets.base import DatasetRegistry
from ..metrics import calculate_metrics, generate_report
@@ -141,7 +140,9 @@ class SimpleQAEvaluator(BaseBenchmarkEvaluator):
evaluation_file = os.path.join(
output_dir, f"simpleqa_{timestamp}_evaluation.jsonl"
)
- report_file = os.path.join(output_dir, f"simpleqa_{timestamp}_report.md")
+ report_file = os.path.join(
+ output_dir, f"simpleqa_{timestamp}_report.md"
+ )
# Process each example
results = []
@@ -151,7 +152,9 @@ class SimpleQAEvaluator(BaseBenchmarkEvaluator):
question = dataset_instance.get_question(example)
correct_answer = dataset_instance.get_answer(example)
- logger.info(f"Processing {i + 1}/{len(examples)}: {question[:50]}...")
+ logger.info(
+ f"Processing {i + 1}/{len(examples)}: {question[:50]}..."
+ )
try:
# Format query based on dataset type
@@ -166,7 +169,9 @@ class SimpleQAEvaluator(BaseBenchmarkEvaluator):
"questions_per_iteration": system_config.get(
"questions_per_iteration", 3
),
- "search_tool": system_config.get("search_tool", "searxng"),
+ "search_tool": system_config.get(
+ "search_tool", "searxng"
+ ),
# Note: search_strategy is stored in the config but not passed to quick_summary
# as it's not supported by the underlying API
}
@@ -192,7 +197,9 @@ class SimpleQAEvaluator(BaseBenchmarkEvaluator):
# Extract structured answer
from ..graders import extract_answer_from_response
- extracted = extract_answer_from_response(response, "simpleqa")
+ extracted = extract_answer_from_response(
+ response, "simpleqa"
+ )
# Format result
result = {
@@ -236,7 +243,7 @@ class SimpleQAEvaluator(BaseBenchmarkEvaluator):
# Grade results
from ..graders import grade_results
- evaluation_results = grade_results(
+ grade_results(
results_file=results_file,
output_file=evaluation_file,
dataset_type="simpleqa",
diff --git a/src/local_deep_research/benchmarks/graders.py b/src/local_deep_research/benchmarks/graders.py
index 0bb4d011a6..7e2390dff6 100644
--- a/src/local_deep_research/benchmarks/graders.py
+++ b/src/local_deep_research/benchmarks/graders.py
@@ -59,7 +59,9 @@ def get_evaluation_llm(custom_config: Optional[Dict[str, Any]] = None):
"api_key",
}
- filtered_config = {k: v for k, v in config.items() if k in ldr_supported_params}
+ filtered_config = {
+ k: v for k, v in config.items() if k in ldr_supported_params
+ }
# Check if we're using openai_endpoint but don't have an API key configured
if filtered_config.get("provider") == "openai_endpoint":
@@ -182,7 +184,9 @@ def grade_results(
try:
# Grade using LLM
- if hasattr(evaluation_llm, "invoke") and callable(evaluation_llm.invoke):
+ if hasattr(evaluation_llm, "invoke") and callable(
+ evaluation_llm.invoke
+ ):
if hasattr(evaluation_llm, "chat_messages"):
# Handle ChatOpenAI and similar models that use messages
grading_response = evaluation_llm.invoke(
@@ -214,7 +218,9 @@ def grade_results(
grading_response,
re.DOTALL,
)
- reasoning = reasoning_match.group(1).strip() if reasoning_match else ""
+ reasoning = (
+ reasoning_match.group(1).strip() if reasoning_match else ""
+ )
correct_match = re.search(
r"correct:\s*(yes|no)", grading_response, re.IGNORECASE
@@ -225,8 +231,12 @@ def grade_results(
else False
)
- confidence_match = re.search(r"confidence:\s*(\d+)", grading_response)
- confidence = confidence_match.group(1) if confidence_match else "100"
+ confidence_match = re.search(
+ r"confidence:\s*(\d+)", grading_response
+ )
+ confidence = (
+ confidence_match.group(1) if confidence_match else "100"
+ )
else:
# SimpleQA extraction
extracted_answer_match = re.search(
@@ -239,9 +249,13 @@ def grade_results(
)
reasoning_match = re.search(
- r"Reasoning:\s*(.*?)(?:\nCorrect:|\Z)", grading_response, re.DOTALL
+ r"Reasoning:\s*(.*?)(?:\nCorrect:|\Z)",
+ grading_response,
+ re.DOTALL,
+ )
+ reasoning = (
+ reasoning_match.group(1).strip() if reasoning_match else ""
)
- reasoning = reasoning_match.group(1).strip() if reasoning_match else ""
correct_match = re.search(
r"Correct:\s*(yes|no)", grading_response, re.IGNORECASE
@@ -304,7 +318,11 @@ def grade_results(
progress_callback(
idx,
len(results),
- {"status": "error", "error": str(e), "result": error_result},
+ {
+ "status": "error",
+ "error": str(e),
+ "result": error_result,
+ },
)
accuracy = correct_count / len(results) if results else 0
@@ -366,7 +384,9 @@ def human_evaluation(
# Get human judgment
while True:
judgment = (
- input("\nIs the model's answer correct? (y/n): ").strip().lower()
+ input("\nIs the model's answer correct? (y/n): ")
+ .strip()
+ .lower()
)
if judgment in ["y", "n"]:
break
@@ -375,7 +395,9 @@ def human_evaluation(
is_correct = judgment == "y"
# Get reasoning
- reasoning = input("Please provide reasoning for your judgment: ").strip()
+ reasoning = input(
+ "Please provide reasoning for your judgment: "
+ ).strip()
else:
# Non-interactive mode - placeholder for API/UI implementation
# In a real implementation, this would be filled by UI actions
diff --git a/src/local_deep_research/benchmarks/metrics/calculation.py b/src/local_deep_research/benchmarks/metrics/calculation.py
index 6a3c350e9c..5060c76609 100644
--- a/src/local_deep_research/benchmarks/metrics/calculation.py
+++ b/src/local_deep_research/benchmarks/metrics/calculation.py
@@ -11,7 +11,7 @@ import os
import tempfile
import time
from datetime import datetime
-from typing import Any, Dict, List, Optional, Union
+from typing import Any, Dict, Optional
logger = logging.getLogger(__name__)
@@ -50,7 +50,9 @@ def calculate_metrics(results_file: str) -> Dict[str, Any]:
processing_times = [
r.get("processing_time", 0) for r in results if "processing_time" in r
]
- avg_time = sum(processing_times) / len(processing_times) if processing_times else 0
+ avg_time = (
+ sum(processing_times) / len(processing_times) if processing_times else 0
+ )
# Average confidence if available
confidence_values = []
@@ -62,7 +64,9 @@ def calculate_metrics(results_file: str) -> Dict[str, Any]:
pass
avg_confidence = (
- sum(confidence_values) / len(confidence_values) if confidence_values else 0
+ sum(confidence_values) / len(confidence_values)
+ if confidence_values
+ else 0
)
# Calculate error rate
@@ -100,7 +104,9 @@ def calculate_metrics(results_file: str) -> Dict[str, Any]:
"total": counts["total"],
"correct": counts["correct"],
"accuracy": (
- counts["correct"] / counts["total"] if counts["total"] else 0
+ counts["correct"] / counts["total"]
+ if counts["total"]
+ else 0
),
}
metrics["categories"] = category_metrics
@@ -136,7 +142,9 @@ def evaluate_benchmark_quality(
# Create search configuration from system config
search_config = {
"iterations": system_config.get("iterations", 2),
- "questions_per_iteration": system_config.get("questions_per_iteration", 2),
+ "questions_per_iteration": system_config.get(
+ "questions_per_iteration", 2
+ ),
"search_strategy": system_config.get("search_strategy", "iterdrag"),
"search_tool": system_config.get("search_tool", "searxng"),
"model_name": system_config.get("model_name"),
@@ -174,7 +182,9 @@ def evaluate_benchmark_quality(
try:
shutil.rmtree(temp_dir)
except Exception as e:
- logger.warning(f"Failed to clean up temporary directory: {str(e)}")
+ logger.warning(
+ f"Failed to clean up temporary directory: {str(e)}"
+ )
def measure_execution_time(
@@ -216,7 +226,7 @@ def measure_execution_time(
try:
for i in range(num_runs):
- logger.info(f"Executing speed test run {i+1}/{num_runs}")
+ logger.info(f"Executing speed test run {i + 1}/{num_runs}")
start_time = time.time()
system.search(query, full_response=False)
end_time = time.time()
@@ -264,7 +274,9 @@ def calculate_quality_metrics(
"""
# Run quality evaluation
quality_results = evaluate_benchmark_quality(
- system_config=system_config, num_examples=num_examples, output_dir=output_dir
+ system_config=system_config,
+ num_examples=num_examples,
+ output_dir=output_dir,
)
# Return normalized quality score
@@ -337,7 +349,10 @@ def calculate_resource_metrics(
# Normalize to 0-1 scale (lower is better)
resource_score = 1.0 / (1.0 + (complexity / 4.0))
- return {"resource_score": resource_score, "estimated_complexity": complexity}
+ return {
+ "resource_score": resource_score,
+ "estimated_complexity": complexity,
+ }
def calculate_combined_score(
diff --git a/src/local_deep_research/benchmarks/metrics/reporting.py b/src/local_deep_research/benchmarks/metrics/reporting.py
index 4e702f1f26..d4f7e9f170 100644
--- a/src/local_deep_research/benchmarks/metrics/reporting.py
+++ b/src/local_deep_research/benchmarks/metrics/reporting.py
@@ -46,7 +46,9 @@ def generate_report(
# Sample up to 5 correct and 5 incorrect examples
correct_examples = [r for r in results if r.get("is_correct", False)][:5]
incorrect_examples = [
- r for r in results if "is_correct" in r and not r.get("is_correct", False)
+ r
+ for r in results
+ if "is_correct" in r and not r.get("is_correct", False)
][:5]
# Create report
@@ -67,7 +69,9 @@ def generate_report(
)
if "average_confidence" in metrics:
- report.append(f"- **Average Confidence**: {metrics['average_confidence']:.2f}%")
+ report.append(
+ f"- **Average Confidence**: {metrics['average_confidence']:.2f}%"
+ )
if "error_count" in metrics and metrics["error_count"] > 0:
report.append(f"- **Error Count**: {metrics['error_count']}")
diff --git a/src/local_deep_research/benchmarks/metrics/visualization.py b/src/local_deep_research/benchmarks/metrics/visualization.py
index 07c5d15f3f..631e685527 100644
--- a/src/local_deep_research/benchmarks/metrics/visualization.py
+++ b/src/local_deep_research/benchmarks/metrics/visualization.py
@@ -6,8 +6,7 @@ of benchmark and optimization results.
"""
import logging
-import os
-from typing import Dict, List, Optional, Tuple, Union
+from typing import Dict, List, Optional
import numpy as np
@@ -21,7 +20,9 @@ try:
MATPLOTLIB_AVAILABLE = True
except ImportError:
MATPLOTLIB_AVAILABLE = False
- logger.warning("Matplotlib not available. Visualization functions will be limited.")
+ logger.warning(
+ "Matplotlib not available. Visualization functions will be limited."
+ )
def plot_optimization_history(
@@ -167,10 +168,18 @@ def plot_quality_vs_speed(
# Add reference lines
ax.axhline(
- y=0.7, color="r", linestyle="--", alpha=0.3, label="Good Quality Threshold"
+ y=0.7,
+ color="r",
+ linestyle="--",
+ alpha=0.3,
+ label="Good Quality Threshold",
)
ax.axvline(
- x=0.7, color="g", linestyle="--", alpha=0.3, label="Good Speed Threshold"
+ x=0.7,
+ color="g",
+ linestyle="--",
+ alpha=0.3,
+ label="Good Speed Threshold",
)
# Mark Pareto frontier
diff --git a/src/local_deep_research/benchmarks/optimization/__init__.py b/src/local_deep_research/benchmarks/optimization/__init__.py
index 927371f2f1..9ed320a5c7 100644
--- a/src/local_deep_research/benchmarks/optimization/__init__.py
+++ b/src/local_deep_research/benchmarks/optimization/__init__.py
@@ -17,7 +17,9 @@ from local_deep_research.benchmarks.optimization.metrics import (
calculate_resource_metrics,
calculate_speed_metrics,
)
-from local_deep_research.benchmarks.optimization.optuna_optimizer import OptunaOptimizer
+from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ OptunaOptimizer,
+)
__all__ = [
"OptunaOptimizer",
diff --git a/src/local_deep_research/benchmarks/optimization/api.py b/src/local_deep_research/benchmarks/optimization/api.py
index eaa724a9df..b9c091f426 100644
--- a/src/local_deep_research/benchmarks/optimization/api.py
+++ b/src/local_deep_research/benchmarks/optimization/api.py
@@ -257,7 +257,13 @@ def get_default_param_space() -> Dict[str, Any]:
},
"search_strategy": {
"type": "categorical",
- "choices": ["iterdrag", "standard", "rapid", "parallel", "source_based"],
+ "choices": [
+ "iterdrag",
+ "standard",
+ "rapid",
+ "parallel",
+ "source_based",
+ ],
},
"max_results": {
"type": "int",
diff --git a/src/local_deep_research/benchmarks/optimization/optuna_optimizer.py b/src/local_deep_research/benchmarks/optimization/optuna_optimizer.py
index 369aabc2a1..4a8053fa86 100644
--- a/src/local_deep_research/benchmarks/optimization/optuna_optimizer.py
+++ b/src/local_deep_research/benchmarks/optimization/optuna_optimizer.py
@@ -24,8 +24,12 @@ from optuna.visualization import (
plot_slice,
)
-from local_deep_research.benchmarks.efficiency.speed_profiler import SpeedProfiler
-from local_deep_research.benchmarks.evaluators import CompositeBenchmarkEvaluator
+from local_deep_research.benchmarks.efficiency.speed_profiler import (
+ SpeedProfiler,
+)
+from local_deep_research.benchmarks.evaluators import (
+ CompositeBenchmarkEvaluator,
+)
# Import benchmark evaluator components
@@ -108,7 +112,9 @@ class OptunaOptimizer:
# Initialize benchmark evaluator with weights
self.benchmark_weights = benchmark_weights or {"simpleqa": 1.0}
- self.benchmark_evaluator = CompositeBenchmarkEvaluator(self.benchmark_weights)
+ self.benchmark_evaluator = CompositeBenchmarkEvaluator(
+ self.benchmark_weights
+ )
# Normalize weights to sum to 1.0
total_weight = sum(self.metric_weights.values())
@@ -200,7 +206,9 @@ class OptunaOptimizer:
# Create visualizations
self._create_visualizations()
- logger.info(f"Optimization complete. Best parameters: {self.best_params}")
+ logger.info(
+ f"Optimization complete. Best parameters: {self.best_params}"
+ )
logger.info(f"Best value: {self.study.best_value}")
# Report completion
@@ -281,7 +289,9 @@ class OptunaOptimizer:
},
}
- def _objective(self, trial: optuna.Trial, param_space: Dict[str, Any]) -> float:
+ def _objective(
+ self, trial: optuna.Trial, param_space: Dict[str, Any]
+ ) -> float:
"""
Objective function for Optuna optimization.
@@ -496,7 +506,9 @@ class OptunaOptimizer:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
# Save trial history
- history_file = os.path.join(self.output_dir, f"{self.study_name}_history.json")
+ history_file = os.path.join(
+ self.output_dir, f"{self.study_name}_history.json"
+ )
with open(history_file, "w") as f:
# Convert numpy values to native Python types for JSON serialization
clean_history = []
@@ -517,7 +529,11 @@ class OptunaOptimizer:
json.dump(clean_history, f, indent=2)
# Save current best parameters
- if self.study and hasattr(self.study, "best_params") and self.study.best_params:
+ if (
+ self.study
+ and hasattr(self.study, "best_params")
+ and self.study.best_params
+ ):
best_params_file = os.path.join(
self.output_dir, f"{self.study_name}_best_params.json"
)
@@ -541,7 +557,9 @@ class OptunaOptimizer:
# Save the Optuna study
if self.study:
- study_file = os.path.join(self.output_dir, f"{self.study_name}_study.pkl")
+ study_file = os.path.join(
+ self.output_dir, f"{self.study_name}_study.pkl"
+ )
joblib.dump(self.study, study_file)
logger.info(f"Results saved to {self.output_dir}")
@@ -549,7 +567,9 @@ class OptunaOptimizer:
def _create_visualizations(self):
"""Create and save comprehensive visualizations of the optimization results."""
if not PLOTTING_AVAILABLE:
- logger.warning("Matplotlib not available, skipping visualization creation")
+ logger.warning(
+ "Matplotlib not available, skipping visualization creation"
+ )
return
if not self.study or len(self.study.trials) < 2:
@@ -570,7 +590,11 @@ class OptunaOptimizer:
def _create_quick_visualizations(self):
"""Create a smaller set of visualizations for intermediate progress."""
- if not PLOTTING_AVAILABLE or not self.study or len(self.study.trials) < 2:
+ if (
+ not PLOTTING_AVAILABLE
+ or not self.study
+ or len(self.study.trials) < 2
+ ):
return
# Create directory for visualizations
@@ -582,7 +606,8 @@ class OptunaOptimizer:
fig = plot_optimization_history(self.study)
fig.write_image(
os.path.join(
- viz_dir, f"{self.study_name}_optimization_history_current.png"
+ viz_dir,
+ f"{self.study_name}_optimization_history_current.png",
)
)
except Exception as e:
@@ -602,7 +627,8 @@ class OptunaOptimizer:
fig = plot_optimization_history(self.study)
fig.write_image(
os.path.join(
- viz_dir, f"{self.study_name}_optimization_history_{timestamp}.png"
+ viz_dir,
+ f"{self.study_name}_optimization_history_{timestamp}.png",
)
)
except Exception as e:
@@ -613,7 +639,8 @@ class OptunaOptimizer:
fig = plot_param_importances(self.study)
fig.write_image(
os.path.join(
- viz_dir, f"{self.study_name}_param_importances_{timestamp}.png"
+ viz_dir,
+ f"{self.study_name}_param_importances_{timestamp}.png",
)
)
except Exception as e:
@@ -625,7 +652,8 @@ class OptunaOptimizer:
fig = plot_slice(self.study, [param_name])
fig.write_image(
os.path.join(
- viz_dir, f"{self.study_name}_slice_{param_name}_{timestamp}.png"
+ viz_dir,
+ f"{self.study_name}_slice_{param_name}_{timestamp}.png",
)
)
except Exception as e:
@@ -684,7 +712,9 @@ class OptunaOptimizer:
# Extract data from successful trials
successful_trials = [
- t for t in self.trials_history if t.get("result", {}).get("success", False)
+ t
+ for t in self.trials_history
+ if t.get("result", {}).get("success", False)
]
if not successful_trials:
@@ -715,7 +745,9 @@ class OptunaOptimizer:
questions_values.append(questions)
# Create scatter plot with size based on iterations*questions
- sizes = [i * q * 5 for i, q in zip(iterations_values, questions_values)]
+ sizes = [
+ i * q * 5 for i, q in zip(iterations_values, questions_values)
+ ]
scatter = plt.scatter(
quality_scores,
speed_scores,
@@ -727,12 +759,15 @@ class OptunaOptimizer:
# Highlight best trial
best_trial = max(
- successful_trials, key=lambda x: x.get("result", {}).get("score", 0)
+ successful_trials,
+ key=lambda x: x.get("result", {}).get("score", 0),
)
best_quality = best_trial["result"].get("quality_score", 0)
best_speed = best_trial["result"].get("speed_score", 0)
best_iter = best_trial["params"].get("iterations", 0)
- best_questions = best_trial["params"].get("questions_per_iteration", 0)
+ best_questions = best_trial["params"].get(
+ "questions_per_iteration", 0
+ )
plt.scatter(
[best_quality],
@@ -745,7 +780,9 @@ class OptunaOptimizer:
)
# Add annotations for key points
- for i, (q, s, l) in enumerate(zip(quality_scores, speed_scores, labels)):
+ for i, (q, s, label) in enumerate(
+ zip(quality_scores, speed_scores, labels)
+ ):
if i % max(1, len(quality_scores) // 5) == 0: # Label ~5 points
plt.annotate(
f"{iterations_values[i]}×{questions_values[i]}",
@@ -762,7 +799,9 @@ class OptunaOptimizer:
weights_str = ", ".join(
[f"{k}:{v:.1f}" for k, v in self.benchmark_weights.items()]
)
- plt.title(f"Quality vs. Speed Trade-off\nBenchmark Weights: {weights_str}")
+ plt.title(
+ f"Quality vs. Speed Trade-off\nBenchmark Weights: {weights_str}"
+ )
plt.xlabel("Quality Score (Benchmark Accuracy)")
plt.ylabel("Speed Score")
plt.grid(True, linestyle="--", alpha=0.7)
@@ -786,7 +825,8 @@ class OptunaOptimizer:
plt.tight_layout()
plt.savefig(
os.path.join(
- viz_dir, f"{self.study_name}_quality_vs_speed_{timestamp}.png"
+ viz_dir,
+ f"{self.study_name}_quality_vs_speed_{timestamp}.png",
)
)
plt.close()
@@ -895,7 +935,9 @@ class OptunaOptimizer:
duration = trial.get("duration", 0)
score = trial.get("score", 0)
iterations = trial.get("params", {}).get("iterations", 1)
- questions = trial.get("params", {}).get("questions_per_iteration", 1)
+ questions = trial.get("params", {}).get(
+ "questions_per_iteration", 1
+ )
trial_durations.append(duration)
trial_scores.append(score)
@@ -903,13 +945,17 @@ class OptunaOptimizer:
trial_questions.append(questions)
# Total questions per trial
- total_questions = [i * q for i, q in zip(trial_iterations, trial_questions)]
+ total_questions = [
+ i * q for i, q in zip(trial_iterations, trial_questions)
+ ]
# Create scatter plot with size based on total questions
plt.scatter(
trial_durations,
trial_scores,
- s=[q * 5 for q in total_questions], # Size based on total questions
+ s=[
+ q * 5 for q in total_questions
+ ], # Size based on total questions
alpha=0.7,
c=range(len(trial_durations)),
cmap="viridis",
@@ -923,7 +969,9 @@ class OptunaOptimizer:
# Add trial number annotations for selected points
for i, (d, s) in enumerate(zip(trial_durations, trial_scores)):
- if i % max(1, len(trial_durations) // 5) == 0: # Annotate ~5 points
+ if (
+ i % max(1, len(trial_durations) // 5) == 0
+ ): # Annotate ~5 points
plt.annotate(
f"{trial_iterations[i]}×{trial_questions[i]}",
(d, s),
@@ -935,7 +983,8 @@ class OptunaOptimizer:
plt.tight_layout()
plt.savefig(
os.path.join(
- viz_dir, f"{self.study_name}_duration_vs_score_{timestamp}.png"
+ viz_dir,
+ f"{self.study_name}_duration_vs_score_{timestamp}.png",
)
)
plt.close()
diff --git a/src/local_deep_research/benchmarks/runners.py b/src/local_deep_research/benchmarks/runners.py
index 34cd3e638c..a6d2e293ae 100644
--- a/src/local_deep_research/benchmarks/runners.py
+++ b/src/local_deep_research/benchmarks/runners.py
@@ -109,11 +109,15 @@ def run_benchmark(
# Set up output files
timestamp = time.strftime("%Y%m%d_%H%M%S")
- results_file = os.path.join(output_dir, f"{dataset_type}_{timestamp}_results.jsonl")
+ results_file = os.path.join(
+ output_dir, f"{dataset_type}_{timestamp}_results.jsonl"
+ )
evaluation_file = os.path.join(
output_dir, f"{dataset_type}_{timestamp}_evaluation.jsonl"
)
- report_file = os.path.join(output_dir, f"{dataset_type}_{timestamp}_report.md")
+ report_file = os.path.join(
+ output_dir, f"{dataset_type}_{timestamp}_report.md"
+ )
# Make sure output files don't exist
for file in [results_file, evaluation_file, report_file]:
@@ -140,12 +144,15 @@ def run_benchmark(
for i, example in enumerate(dataset):
# Extract question and answer in a way that uses the dataset class when available
if "dataset_instance" in locals() and isinstance(
- dataset_instance, DatasetRegistry.get_dataset_class(dataset_type.lower())
+ dataset_instance,
+ DatasetRegistry.get_dataset_class(dataset_type.lower()),
):
# Use the dataset class methods to extract question and answer
question = dataset_instance.get_question(example)
correct_answer = dataset_instance.get_answer(example)
- logger.debug(f"Using dataset class methods to extract question and answer")
+ logger.debug(
+ "Using dataset class methods to extract question and answer"
+ )
else:
# Fallback to the legacy approach
if dataset_type.lower() == "simpleqa":
@@ -169,7 +176,9 @@ def run_benchmark(
"current": i + 1,
"total": total_examples,
"question": (
- question[:50] + "..." if len(question) > 50 else question
+ question[:50] + "..."
+ if len(question) > 50
+ else question
),
},
)
@@ -187,7 +196,9 @@ def run_benchmark(
search_result = quick_summary(
query=formatted_query,
iterations=search_config.get("iterations", 3),
- questions_per_iteration=search_config.get("questions_per_iteration", 3),
+ questions_per_iteration=search_config.get(
+ "questions_per_iteration", 3
+ ),
search_tool=search_config.get("search_tool", "searxng"),
)
@@ -284,7 +295,9 @@ def run_benchmark(
logger.info("Running human evaluation...")
evaluation_results = evaluate(
- results_file=results_file, output_file=evaluation_file, interactive=True
+ results_file=results_file,
+ output_file=evaluation_file,
+ interactive=True,
)
else:
logger.info("Running automated evaluation...")
@@ -355,7 +368,9 @@ def run_benchmark(
# Generate report
if progress_callback:
- progress_callback("Generating report", 95, {"status": "generating_report"})
+ progress_callback(
+ "Generating report", 95, {"status": "generating_report"}
+ )
dataset_name = dataset_type.capitalize()
report_path = generate_report(
@@ -372,7 +387,9 @@ def run_benchmark(
"questions_per_iteration", 3
),
"Search tool": search_config.get("search_tool", "searxng"),
- "Evaluation method": "Human" if human_evaluation else "Automated",
+ "Evaluation method": "Human"
+ if human_evaluation
+ else "Automated",
},
)
@@ -381,7 +398,11 @@ def run_benchmark(
progress_callback(
"Benchmark complete",
100,
- {"status": "complete", "metrics": metrics, "report_path": report_path},
+ {
+ "status": "complete",
+ "metrics": metrics,
+ "report_path": report_path,
+ },
)
return {
@@ -423,10 +444,14 @@ def run_simpleqa_benchmark(num_examples: int = 100, **kwargs) -> Dict[str, Any]:
Returns:
Dictionary with benchmark results
"""
- return run_benchmark(dataset_type="simpleqa", num_examples=num_examples, **kwargs)
+ return run_benchmark(
+ dataset_type="simpleqa", num_examples=num_examples, **kwargs
+ )
-def run_browsecomp_benchmark(num_examples: int = 100, **kwargs) -> Dict[str, Any]:
+def run_browsecomp_benchmark(
+ num_examples: int = 100, **kwargs
+) -> Dict[str, Any]:
"""
Run BrowseComp benchmark with default settings.
@@ -437,4 +462,6 @@ def run_browsecomp_benchmark(num_examples: int = 100, **kwargs) -> Dict[str, Any
Returns:
Dictionary with benchmark results
"""
- return run_benchmark(dataset_type="browsecomp", num_examples=num_examples, **kwargs)
+ return run_benchmark(
+ dataset_type="browsecomp", num_examples=num_examples, **kwargs
+ )
diff --git a/src/local_deep_research/citation_handlers/forced_answer_citation_handler.py b/src/local_deep_research/citation_handlers/forced_answer_citation_handler.py
index 0b93513c94..6e01c5ba0d 100644
--- a/src/local_deep_research/citation_handlers/forced_answer_citation_handler.py
+++ b/src/local_deep_research/citation_handlers/forced_answer_citation_handler.py
@@ -44,7 +44,9 @@ Example response format:
# If the response still doesn't have a direct answer, extract one
if self._needs_answer_extraction(response, query):
- response = self._extract_direct_answer(query, response, formatted_sources)
+ response = self._extract_direct_answer(
+ query, response, formatted_sources
+ )
return {"content": response, "documents": documents}
@@ -56,7 +58,9 @@ Example response format:
nr_of_links: int,
) -> Dict[str, Any]:
"""Follow-up analysis with forced answer generation."""
- documents = self._create_documents(search_results, nr_of_links=nr_of_links)
+ documents = self._create_documents(
+ search_results, nr_of_links=nr_of_links
+ )
formatted_sources = self._format_sources(documents)
# Fact-checking step (if enabled)
@@ -103,7 +107,9 @@ Remember: A wrong answer is better than no answer for this task."""
# Final check - if still no direct answer, force extraction
if self._needs_answer_extraction(content, question):
- content = self._extract_direct_answer(question, content, formatted_sources)
+ content = self._extract_direct_answer(
+ question, content, formatted_sources
+ )
logger.info(f"Forced answer extraction applied: {content[:100]}...")
return {"content": content, "documents": documents}
@@ -129,7 +135,9 @@ Remember: A wrong answer is better than no answer for this task."""
return True
# Check if it's a direct question but no direct answer given
- if query.lower().startswith(("what", "who", "which", "where", "when", "name")):
+ if query.lower().startswith(
+ ("what", "who", "which", "where", "when", "name")
+ ):
# Look for a direct answer pattern in first 100 chars
first_part = content[:100].lower()
if not any(
@@ -139,7 +147,9 @@ Remember: A wrong answer is better than no answer for this task."""
return False
- def _extract_direct_answer(self, query: str, content: str, sources: str) -> str:
+ def _extract_direct_answer(
+ self, query: str, content: str, sources: str
+ ) -> str:
"""Force extraction of a direct answer using LLM."""
extraction_prompt = f"""Based on the content below, extract a SINGLE, DIRECT answer to the question.
diff --git a/src/local_deep_research/citation_handlers/precision_extraction_handler.py b/src/local_deep_research/citation_handlers/precision_extraction_handler.py
index 3931bc90e4..5da019e412 100644
--- a/src/local_deep_research/citation_handlers/precision_extraction_handler.py
+++ b/src/local_deep_research/citation_handlers/precision_extraction_handler.py
@@ -25,7 +25,9 @@ class PrecisionExtractionHandler(BaseCitationHandler):
# Answer type patterns
self.answer_patterns = {
- "full_name": re.compile(r"\b([A-Z][a-z]+(?:\s+[A-Z][a-z]+){1,4})\b"),
+ "full_name": re.compile(
+ r"\b([A-Z][a-z]+(?:\s+[A-Z][a-z]+){1,4})\b"
+ ),
"year": re.compile(r"\b(19\d{2}|20\d{2})\b"),
"number": re.compile(r"\b(\d+(?:\.\d+)?)\b"),
"dimension": re.compile(
@@ -84,7 +86,9 @@ Format: Start with the direct, precise answer, then explain with citations."""
nr_of_links: int,
) -> Dict[str, Any]:
"""Follow-up analysis with precision extraction."""
- documents = self._create_documents(search_results, nr_of_links=nr_of_links)
+ documents = self._create_documents(
+ search_results, nr_of_links=nr_of_links
+ )
formatted_sources = self._format_sources(documents)
question_type = self._identify_question_type(question)
@@ -155,14 +159,23 @@ Provide the precise answer with citations."""
# Score/result questions
if any(
- phrase in query_lower for phrase in ["score", "result", "final", "outcome"]
+ phrase in query_lower
+ for phrase in ["score", "result", "final", "outcome"]
):
return "score"
# Dimension questions
if any(
phrase in query_lower
- for phrase in ["height", "length", "width", "size", "tall", "long", "wide"]
+ for phrase in [
+ "height",
+ "length",
+ "width",
+ "size",
+ "tall",
+ "long",
+ "wide",
+ ]
):
return "dimension"
@@ -223,10 +236,14 @@ Which is the FULL name (including middle name if present)?"""
for line in lines:
if "full name" in line.lower() or "longest" in line.lower():
# Extract name from this line
- matches = self.answer_patterns["full_name"].findall(line)
+ matches = self.answer_patterns["full_name"].findall(
+ line
+ )
if matches:
# Choose the longest match
- full_name = max(matches, key=lambda x: len(x.split()))
+ full_name = max(
+ matches, key=lambda x: len(x.split())
+ )
return f"{full_name}. {content}"
# Fallback: find all names and pick the longest
@@ -257,7 +274,9 @@ Which is the FULL name (including middle name if present)?"""
return content
- def _extract_single_answer(self, content: str, query: str, sources: str) -> str:
+ def _extract_single_answer(
+ self, content: str, query: str, sources: str
+ ) -> str:
"""Extract a single answer when multiple options might be present."""
extraction_prompt = f"""The question asks for ONE specific answer. Extract ONLY that answer.
@@ -275,7 +294,9 @@ The single answer is:"""
answer = self.llm.invoke(extraction_prompt).content.strip()
# Clean up the answer
- answer = answer.split(",")[0].strip() # Take only first if comma-separated
+ answer = answer.split(",")[
+ 0
+ ].strip() # Take only first if comma-separated
answer = answer.split(" and ")[
0
].strip() # Take only first if "and"-separated
@@ -322,7 +343,7 @@ Question: {query}
Content: {content[:1500]}
Rules:
-1. Find the specific {dimension_type or 'dimension'} measurement
+1. Find the specific {dimension_type or "dimension"} measurement
2. Return ONLY the number and unit (e.g., "20 meters", "5.5 feet")
3. Distinguish between different types of measurements:
- Height/tall: vertical measurements
@@ -331,7 +352,7 @@ Rules:
4. Look for context clues near the measurement
5. If multiple measurements, choose the one that matches the question type
-The exact {dimension_type or 'dimension'} is:"""
+The exact {dimension_type or "dimension"} is:"""
try:
answer = self.llm.invoke(extraction_prompt).content.strip()
@@ -339,7 +360,9 @@ The exact {dimension_type or 'dimension'} is:"""
# Clean and validate the answer
import re
- measurement_match = re.search(r"(\d+(?:\.\d+)?)\s*([a-zA-Z/°]+)", answer)
+ measurement_match = re.search(
+ r"(\d+(?:\.\d+)?)\s*([a-zA-Z/°]+)", answer
+ )
if measurement_match:
number, unit = measurement_match.groups()
clean_answer = f"{number} {unit}"
@@ -372,11 +395,13 @@ The exact {dimension_type or 'dimension'} is:"""
# Score based on unit appropriateness
unit_lower = unit.lower()
if dimension_type == "height" and any(
- u in unit_lower for u in ["m", "meter", "ft", "feet", "cm"]
+ u in unit_lower
+ for u in ["m", "meter", "ft", "feet", "cm"]
):
score += 5
elif dimension_type == "length" and any(
- u in unit_lower for u in ["m", "meter", "km", "mile", "ft"]
+ u in unit_lower
+ for u in ["m", "meter", "km", "mile", "ft"]
):
score += 5
elif dimension_type == "weight" and any(
@@ -385,7 +410,8 @@ The exact {dimension_type or 'dimension'} is:"""
):
score += 5
elif dimension_type == "speed" and any(
- u in unit_lower for u in ["mph", "kmh", "km/h", "m/s"]
+ u in unit_lower
+ for u in ["mph", "kmh", "km/h", "m/s"]
):
score += 5
@@ -401,7 +427,9 @@ The exact {dimension_type or 'dimension'} is:"""
return f"{best_dimension}. {content}"
# Final fallback: first dimension
- return f"{all_dimensions[0][0]} {all_dimensions[0][1]}. {content}"
+ return (
+ f"{all_dimensions[0][0]} {all_dimensions[0][1]}. {content}"
+ )
except Exception as e:
logger.error(f"Error in dimension extraction: {e}")
@@ -463,7 +491,9 @@ The answer is:"""
def _extract_number(self, content: str, query: str, sources: str) -> str:
"""Extract specific numbers."""
# Find all numbers
- numbers = self.answer_patterns["number"].findall(content + " " + sources)
+ numbers = self.answer_patterns["number"].findall(
+ content + " " + sources
+ )
if numbers:
extraction_prompt = f"""Which number specifically answers this question?
@@ -486,7 +516,9 @@ The answer is:"""
def _extract_best_name(self, content: str, query: str, sources: str) -> str:
"""Extract the best matching name (not necessarily full)."""
# Find all potential names
- names = self.answer_patterns["full_name"].findall(content + " " + sources)
+ names = self.answer_patterns["full_name"].findall(
+ content + " " + sources
+ )
if names:
# Count frequency
@@ -500,7 +532,9 @@ The answer is:"""
return content
- def _extract_key_facts(self, previous_knowledge: str, question_type: str) -> str:
+ def _extract_key_facts(
+ self, previous_knowledge: str, question_type: str
+ ) -> str:
"""Extract key facts from previous knowledge."""
extraction_prompt = f"""Extract key facts related to a {question_type} question from this knowledge:
diff --git a/src/local_deep_research/citation_handlers/standard_citation_handler.py b/src/local_deep_research/citation_handlers/standard_citation_handler.py
index b0c5bf877b..d0ee2b8ac9 100644
--- a/src/local_deep_research/citation_handlers/standard_citation_handler.py
+++ b/src/local_deep_research/citation_handlers/standard_citation_handler.py
@@ -14,7 +14,6 @@ class StandardCitationHandler(BaseCitationHandler):
def analyze_initial(
self, query: str, search_results: Union[str, List[Dict]]
) -> Dict[str, Any]:
-
documents = self._create_documents(search_results)
formatted_sources = self._format_sources(documents)
prompt = f"""Analyze the following information concerning the question and include citations using numbers in square brackets [1], [2], etc. When citing, use the source number provided at the start of each source.
@@ -40,7 +39,9 @@ Provide a detailed analysis with citations. Do not create the bibliography, it w
nr_of_links: int,
) -> Dict[str, Any]:
"""Process follow-up analysis with citations."""
- documents = self._create_documents(search_results, nr_of_links=nr_of_links)
+ documents = self._create_documents(
+ search_results, nr_of_links=nr_of_links
+ )
formatted_sources = self._format_sources(documents)
# Add fact-checking step
fact_check_prompt = f"""Analyze these sources for factual consistency:
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.py
index dbaf827574..fc47a2786c 100644
--- a/src/local_deep_research/config/llm_config.py
+++ b/src/local_deep_research/config/llm_config.py
@@ -7,7 +7,6 @@ from langchain_core.language_models import FakeListChatModel
from langchain_ollama import ChatOllama
from langchain_openai import ChatOpenAI
from loguru import logger
-from functools import cache
from ..utilities.db_utils import get_db_setting
from ..utilities.search_utilities import remove_think_tags
@@ -58,16 +57,22 @@ def is_ollama_available():
try:
import requests
- raw_base_url = get_db_setting("llm.ollama.url", "http://localhost:11434")
+ raw_base_url = get_db_setting(
+ "llm.ollama.url", "http://localhost:11434"
+ )
base_url = (
- normalize_url(raw_base_url) if raw_base_url else "http://localhost:11434"
+ normalize_url(raw_base_url)
+ if raw_base_url
+ else "http://localhost:11434"
)
logger.info(f"Checking Ollama availability at {base_url}/api/tags")
try:
response = requests.get(f"{base_url}/api/tags", timeout=3.0)
if response.status_code == 200:
- logger.info(f"Ollama is available. Status code: {response.status_code}")
+ logger.info(
+ f"Ollama is available. Status code: {response.status_code}"
+ )
# Log first 100 chars of response to debug
logger.info(f"Response preview: {str(response.text)[:100]}")
return True
@@ -77,7 +82,9 @@ def is_ollama_available():
)
return False
except requests.exceptions.RequestException as req_error:
- logger.error(f"Request error when checking Ollama: {str(req_error)}")
+ logger.error(
+ f"Request error when checking Ollama: {str(req_error)}"
+ )
return False
except Exception:
logger.exception("Unexpected error when checking Ollama")
@@ -103,7 +110,9 @@ def is_lmstudio_available():
try:
import requests
- lmstudio_url = get_db_setting("llm.lmstudio.url", "http://localhost:1234")
+ lmstudio_url = get_db_setting(
+ "llm.lmstudio.url", "http://localhost:1234"
+ )
# LM Studio typically uses OpenAI-compatible endpoints
response = requests.get(f"{lmstudio_url}/v1/models", timeout=1.0)
return response.status_code == 200
@@ -239,7 +248,8 @@ def get_llm(
if get_db_setting("llm.supports_max_tokens", True):
# Use 80% of context window to leave room for prompts
max_tokens = min(
- int(get_db_setting("llm.max_tokens", 30000)), int(context_window_size * 0.8)
+ int(get_db_setting("llm.max_tokens", 30000)),
+ int(context_window_size * 0.8),
)
common_params["max_tokens"] = max_tokens
@@ -265,7 +275,9 @@ def get_llm(
elif provider == "openai":
api_key = get_db_setting("llm.openai.api_key")
if not api_key:
- logger.warning("OPENAI_API_KEY not found. Falling back to default model.")
+ logger.warning(
+ "OPENAI_API_KEY not found. Falling back to default model."
+ )
return get_fallback_model(temperature)
llm = ChatOpenAI(model=model_name, api_key=api_key, **common_params)
@@ -326,7 +338,9 @@ def get_llm(
elif provider == "ollama":
try:
# Use the configurable Ollama base URL
- raw_base_url = get_db_setting("llm.ollama.url", "http://localhost:11434")
+ raw_base_url = get_db_setting(
+ "llm.ollama.url", "http://localhost:11434"
+ )
base_url = (
normalize_url(raw_base_url)
if raw_base_url
@@ -344,7 +358,9 @@ def get_llm(
import requests
try:
- logger.info(f"Checking if model '{model_name}' exists in Ollama")
+ logger.info(
+ f"Checking if model '{model_name}' exists in Ollama"
+ )
response = requests.get(f"{base_url}/api/tags", timeout=3.0)
if response.status_code == 200:
# Handle both newer and older Ollama API formats
@@ -369,14 +385,18 @@ def get_llm(
)
return get_fallback_model(temperature)
except Exception:
- logger.exception(f"Error checking for model '{model_name}' in Ollama")
+ logger.exception(
+ f"Error checking for model '{model_name}' in Ollama"
+ )
# Continue anyway, let ChatOllama handle potential errors
logger.info(
f"Creating ChatOllama with model={model_name}, base_url={base_url}"
)
try:
- llm = ChatOllama(model=model_name, base_url=base_url, **common_params)
+ llm = ChatOllama(
+ model=model_name, base_url=base_url, **common_params
+ )
# Test invoke to validate model works
logger.info("Testing Ollama model with simple invocation")
test_result = llm.invoke("Hello")
@@ -398,7 +418,9 @@ def get_llm(
elif provider == "lmstudio":
# LM Studio supports OpenAI API format, so we can use ChatOpenAI directly
- lmstudio_url = get_db_setting("llm.lmstudio.url", "http://localhost:1234")
+ lmstudio_url = get_db_setting(
+ "llm.lmstudio.url", "http://localhost:1234"
+ )
llm = ChatOpenAI(
model=model_name,
@@ -420,7 +442,9 @@ def get_llm(
from langchain_community.llms import LlamaCpp
# Get LlamaCpp connection mode from settings
- connection_mode = get_db_setting("llm.llamacpp_connection_mode", "local")
+ connection_mode = get_db_setting(
+ "llm.llamacpp_connection_mode", "local"
+ )
if connection_mode == "http":
# Use HTTP client mode
@@ -496,7 +520,9 @@ def wrap_llm_without_think_tags(
from ..metrics import TokenCounter
token_counter = TokenCounter()
- token_callback = token_counter.create_callback(research_id, research_context)
+ token_callback = token_counter.create_callback(
+ research_id, research_context
+ )
# Set provider and model info on the callback
if provider:
token_callback.preset_provider = provider
@@ -533,4 +559,4 @@ def wrap_llm_without_think_tags(
def __getattr__(self, name):
return getattr(self.base_llm, name)
- return ProcessingLLMWrapper(llm)
\ No newline at end of file
+ return ProcessingLLMWrapper(llm)
diff --git a/src/local_deep_research/config/search_config.py b/src/local_deep_research/config/search_config.py
index c4295dfde3..88cfd58715 100644
--- a/src/local_deep_research/config/search_config.py
+++ b/src/local_deep_research/config/search_config.py
@@ -2,7 +2,9 @@
from loguru import logger
from ..utilities.db_utils import get_db_setting
-from ..web_search_engines.search_engine_factory import get_search as factory_get_search
+from ..web_search_engines.search_engine_factory import (
+ get_search as factory_get_search,
+)
from .llm_config import get_llm
# Whether to check the quality search results using the LLM.
@@ -43,7 +45,9 @@ def get_search(search_tool=None, llm_instance=None):
"safe_search": get_db_setting("search.safe_search", True),
"search_snippets_only": get_search_snippets_only_setting(),
"search_language": get_db_setting("search.search_language", "English"),
- "max_filtered_results": get_db_setting("search.max_filtered_results", 5),
+ "max_filtered_results": get_db_setting(
+ "search.max_filtered_results", 5
+ ),
}
# Log NULL parameters for debugging
@@ -62,4 +66,4 @@ def get_search(search_tool=None, llm_instance=None):
else:
logger.error(f"Failed to create search engine for tool: {tool}")
- return search_engine
\ No newline at end of file
+ return search_engine
diff --git a/src/local_deep_research/defaults/__init__.py b/src/local_deep_research/defaults/__init__.py
index 32c52c0235..cab8385650 100644
--- a/src/local_deep_research/defaults/__init__.py
+++ b/src/local_deep_research/defaults/__init__.py
@@ -6,7 +6,6 @@ configuration files and resources used throughout the application.
"""
import logging
-import os
from pathlib import Path
logger = logging.getLogger(__name__)
diff --git a/src/local_deep_research/metrics/db_models.py b/src/local_deep_research/metrics/db_models.py
index 5699741f56..a0b3a4dd01 100644
--- a/src/local_deep_research/metrics/db_models.py
+++ b/src/local_deep_research/metrics/db_models.py
@@ -24,7 +24,9 @@ class TokenUsage(Base):
Integer
) # Removed foreign key constraint to fix token tracking
model_name = Column(String)
- provider = Column(String) # Added provider column for accurate cost tracking
+ provider = Column(
+ String
+ ) # Added provider column for accurate cost tracking
prompt_tokens = Column(Integer)
completion_tokens = Column(Integer)
total_tokens = Column(Integer)
@@ -37,7 +39,9 @@ class TokenUsage(Base):
# Phase 1 Enhancement: Performance metrics
response_time_ms = Column(Integer)
- success_status = Column(String, default="success") # 'success', 'error', 'timeout'
+ success_status = Column(
+ String, default="success"
+ ) # 'success', 'error', 'timeout'
error_type = Column(String)
# Phase 1 Enhancement: Search engine context
@@ -80,7 +84,9 @@ class ResearchRating(Base):
research_id = Column(Integer, unique=True) # References research session ID
rating = Column(Integer) # 1-5 star rating
rated_at = Column(DateTime, server_default=func.now())
- updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())
+ updated_at = Column(
+ DateTime, server_default=func.now(), onupdate=func.now()
+ )
class SearchCall(Base):
diff --git a/src/local_deep_research/metrics/migrate_add_provider_to_token_usage.py b/src/local_deep_research/metrics/migrate_add_provider_to_token_usage.py
index 4b19573daf..7f781012ce 100644
--- a/src/local_deep_research/metrics/migrate_add_provider_to_token_usage.py
+++ b/src/local_deep_research/metrics/migrate_add_provider_to_token_usage.py
@@ -35,7 +35,9 @@ def add_provider_column_to_token_usage():
provider_exists = result.fetchone()[0] > 0
if provider_exists:
- logger.info("Provider column already exists in token_usage table")
+ logger.info(
+ "Provider column already exists in token_usage table"
+ )
return True
logger.info("Adding provider column to token_usage table...")
diff --git a/src/local_deep_research/metrics/migrate_call_stack_tracking.py b/src/local_deep_research/metrics/migrate_call_stack_tracking.py
index 0810e571d1..0c7c301027 100644
--- a/src/local_deep_research/metrics/migrate_call_stack_tracking.py
+++ b/src/local_deep_research/metrics/migrate_call_stack_tracking.py
@@ -39,10 +39,14 @@ def migrate_call_stack_tracking(db_path: str):
f"ALTER TABLE token_usage ADD COLUMN {column_name} {column_type}"
)
else:
- logger.info(f"Column {column_name} already exists in token_usage table")
+ logger.info(
+ f"Column {column_name} already exists in token_usage table"
+ )
conn.commit()
- logger.success("Call stack tracking columns migration completed successfully")
+ logger.success(
+ "Call stack tracking columns migration completed successfully"
+ )
except sqlite3.Error as e:
logger.error(f"Database error during call stack migration: {e}")
diff --git a/src/local_deep_research/metrics/migrate_enhanced_tracking.py b/src/local_deep_research/metrics/migrate_enhanced_tracking.py
index d0e06598d2..51f88f9d36 100644
--- a/src/local_deep_research/metrics/migrate_enhanced_tracking.py
+++ b/src/local_deep_research/metrics/migrate_enhanced_tracking.py
@@ -28,7 +28,9 @@ def migrate_enhanced_tracking():
)
if not cursor.fetchone():
- logger.info("token_usage table doesn't exist yet, skipping migration")
+ logger.info(
+ "token_usage table doesn't exist yet, skipping migration"
+ )
conn.close()
return
diff --git a/src/local_deep_research/metrics/models.py b/src/local_deep_research/metrics/models.py
index 3177edb3da..66874e3d5d 100644
--- a/src/local_deep_research/metrics/models.py
+++ b/src/local_deep_research/metrics/models.py
@@ -27,7 +27,9 @@ class TokenUsage(Base):
# Phase 1 Enhancement: Performance metrics
response_time_ms = Column(Integer)
- success_status = Column(String, default="success") # 'success', 'error', 'timeout'
+ success_status = Column(
+ String, default="success"
+ ) # 'success', 'error', 'timeout'
error_type = Column(String)
# Phase 1 Enhancement: Search engine context
diff --git a/src/local_deep_research/metrics/pricing/cost_calculator.py b/src/local_deep_research/metrics/pricing/cost_calculator.py
index cda68d1440..b851e31e23 100644
--- a/src/local_deep_research/metrics/pricing/cost_calculator.py
+++ b/src/local_deep_research/metrics/pricing/cost_calculator.py
@@ -44,7 +44,9 @@ class CostCalculator:
# Fetch from API
if self.pricing_fetcher:
- pricing = await self.pricing_fetcher.get_model_pricing(model_name, provider)
+ pricing = await self.pricing_fetcher.get_model_pricing(
+ model_name, provider
+ )
if pricing:
self.cache.set(f"model:{cache_key}", pricing)
return pricing
@@ -113,7 +115,9 @@ class CostCalculator:
results.append(result)
except Exception as e:
- logger.error(f"Failed to calculate cost for record {record}: {e}")
+ logger.error(
+ f"Failed to calculate cost for record {record}: {e}"
+ )
# Add record with zero cost on error
results.append(
{
@@ -142,7 +146,10 @@ class CostCalculator:
pricing = fetcher.static_pricing.get(model_name)
if not pricing:
# Find partial match
- for static_model, static_pricing in fetcher.static_pricing.items():
+ for (
+ static_model,
+ static_pricing,
+ ) in fetcher.static_pricing.items():
if (
static_model.lower() in model_name.lower()
or model_name.lower() in static_model.lower()
@@ -177,7 +184,9 @@ class CostCalculator:
total_completion_cost = sum(c["completion_cost"] for c in costs)
total_prompt_tokens = sum(r["prompt_tokens"] for r in usage_records)
- total_completion_tokens = sum(r["completion_tokens"] for r in usage_records)
+ total_completion_tokens = sum(
+ r["completion_tokens"] for r in usage_records
+ )
total_tokens = total_prompt_tokens + total_completion_tokens
# Model breakdown
@@ -207,7 +216,9 @@ class CostCalculator:
"total_calls": len(usage_records),
"model_breakdown": model_costs,
"avg_cost_per_call": (
- round(total_cost / len(usage_records), 6) if usage_records else 0.0
+ round(total_cost / len(usage_records), 6)
+ if usage_records
+ else 0.0
),
"cost_per_token": (
round(total_cost / total_tokens, 8) if total_tokens > 0 else 0.0
diff --git a/src/local_deep_research/metrics/pricing/pricing_cache.py b/src/local_deep_research/metrics/pricing/pricing_cache.py
index a8618b16e3..f453ca6917 100644
--- a/src/local_deep_research/metrics/pricing/pricing_cache.py
+++ b/src/local_deep_research/metrics/pricing/pricing_cache.py
@@ -47,7 +47,9 @@ class PricingCache:
with open(self.cache_file, "r") as f:
data = json.load(f)
self._cache = data.get("cache", {})
- logger.info(f"Loaded pricing cache with {len(self._cache)} entries")
+ logger.info(
+ f"Loaded pricing cache with {len(self._cache)} entries"
+ )
except Exception as e:
logger.warning(f"Failed to load pricing cache: {e}")
self._cache = {}
diff --git a/src/local_deep_research/metrics/pricing/pricing_fetcher.py b/src/local_deep_research/metrics/pricing/pricing_fetcher.py
index 3dc04ced64..393a858d2c 100644
--- a/src/local_deep_research/metrics/pricing/pricing_fetcher.py
+++ b/src/local_deep_research/metrics/pricing/pricing_fetcher.py
@@ -75,7 +75,9 @@ class PricingFetcher:
try:
# Note: Anthropic doesn't have a public pricing API
# This would need to be web scraping or manual updates
- logger.info("Using static Anthropic pricing (no public API available)")
+ logger.info(
+ "Using static Anthropic pricing (no public API available)"
+ )
return None
except Exception as e:
logger.warning(f"Failed to fetch Anthropic pricing: {e}")
@@ -104,7 +106,9 @@ class PricingFetcher:
async with self.session.get(url) as response:
if response.status == 200:
# Would need to parse HTML for pricing info
- logger.info("HuggingFace pricing would require HTML parsing")
+ logger.info(
+ "HuggingFace pricing would require HTML parsing"
+ )
return None
except Exception as e:
logger.warning(f"Failed to fetch HuggingFace pricing: {e}")
@@ -121,11 +125,17 @@ class PricingFetcher:
# Provider-first approach: Check if provider indicates local/free models
local_providers = ["ollama", "vllm", "lmstudio", "llamacpp"]
if provider in local_providers:
- logger.debug(f"Local provider '{provider}' detected - returning zero cost")
+ logger.debug(
+ f"Local provider '{provider}' detected - returning zero cost"
+ )
return {"prompt": 0.0, "completion": 0.0}
# Try to fetch live pricing first (most providers don't have APIs)
- if provider == "openai" or "gpt" in model_name or "openai" in model_name:
+ if (
+ provider == "openai"
+ or "gpt" in model_name
+ or "openai" in model_name
+ ):
await self.fetch_openai_pricing()
elif (
provider == "anthropic"
@@ -133,7 +143,11 @@ class PricingFetcher:
or "anthropic" in model_name
):
await self.fetch_anthropic_pricing()
- elif provider == "google" or "gemini" in model_name or "google" in model_name:
+ elif (
+ provider == "google"
+ or "gemini" in model_name
+ or "google" in model_name
+ ):
await self.fetch_google_pricing()
# Fallback to static pricing with provider priority
@@ -149,31 +163,45 @@ class PricingFetcher:
# General model name matching
for static_model, pricing in self.static_pricing.items():
- if static_model.lower() in model_name or model_name in static_model.lower():
+ if (
+ static_model.lower() in model_name
+ or model_name in static_model.lower()
+ ):
return pricing
# Default pricing for unknown models
logger.warning(
f"No pricing found for model: {model_name}, provider: {provider}"
)
- return {"prompt": 0.001, "completion": 0.002} # Default to GPT-3.5 pricing
+ return {
+ "prompt": 0.001,
+ "completion": 0.002,
+ } # Default to GPT-3.5 pricing
- def _get_models_by_provider(self, provider: str) -> Dict[str, Dict[str, float]]:
+ def _get_models_by_provider(
+ self, provider: str
+ ) -> Dict[str, Dict[str, float]]:
"""Get models for a specific provider."""
provider = provider.lower()
provider_models = {}
if provider == "openai":
provider_models = {
- k: v for k, v in self.static_pricing.items() if k.startswith("gpt")
+ k: v
+ for k, v in self.static_pricing.items()
+ if k.startswith("gpt")
}
elif provider == "anthropic":
provider_models = {
- k: v for k, v in self.static_pricing.items() if k.startswith("claude")
+ k: v
+ for k, v in self.static_pricing.items()
+ if k.startswith("claude")
}
elif provider == "google":
provider_models = {
- k: v for k, v in self.static_pricing.items() if k.startswith("gemini")
+ k: v
+ for k, v in self.static_pricing.items()
+ if k.startswith("gemini")
}
elif provider in ["ollama", "vllm", "lmstudio", "llamacpp"]:
# All local models are free
diff --git a/src/local_deep_research/metrics/search_tracker.py b/src/local_deep_research/metrics/search_tracker.py
index cb9a44456a..bf5747a167 100644
--- a/src/local_deep_research/metrics/search_tracker.py
+++ b/src/local_deep_research/metrics/search_tracker.py
@@ -95,7 +95,9 @@ class SearchTracker:
)
# Apply time filter
- time_condition = get_time_filter_condition(period, SearchCall.timestamp)
+ time_condition = get_time_filter_condition(
+ period, SearchCall.timestamp
+ )
if time_condition is not None:
query = query.filter(time_condition)
@@ -110,11 +112,17 @@ class SearchTracker:
search_stats = session.query(
SearchCall.search_engine,
func.count().label("call_count"),
- func.avg(SearchCall.response_time_ms).label("avg_response_time"),
+ func.avg(SearchCall.response_time_ms).label(
+ "avg_response_time"
+ ),
func.sum(SearchCall.results_count).label("total_results"),
- func.avg(SearchCall.results_count).label("avg_results_per_call"),
+ func.avg(SearchCall.results_count).label(
+ "avg_results_per_call"
+ ),
func.sum(
- case((SearchCall.success_status == "success", 1), else_=0)
+ case(
+ (SearchCall.success_status == "success", 1), else_=0
+ )
).label("success_count"),
func.sum(
case((SearchCall.success_status == "error", 1), else_=0)
@@ -136,9 +144,13 @@ class SearchTracker:
# Get recent search calls
recent_calls_query = session.query(SearchCall)
if time_condition is not None:
- recent_calls_query = recent_calls_query.filter(time_condition)
+ recent_calls_query = recent_calls_query.filter(
+ time_condition
+ )
if mode_condition is not None:
- recent_calls_query = recent_calls_query.filter(mode_condition)
+ recent_calls_query = recent_calls_query.filter(
+ mode_condition
+ )
recent_calls = (
recent_calls_query.order_by(SearchCall.timestamp.desc())
@@ -153,7 +165,8 @@ class SearchTracker:
"call_count": stat.call_count,
"avg_response_time": stat.avg_response_time or 0,
"total_results": stat.total_results or 0,
- "avg_results_per_call": stat.avg_results_per_call or 0,
+ "avg_results_per_call": stat.avg_results_per_call
+ or 0,
"success_rate": (
(stat.success_count / stat.call_count * 100)
if stat.call_count > 0
@@ -204,9 +217,14 @@ class SearchTracker:
func.avg(SearchCall.response_time_ms).label(
"avg_response_time"
),
- func.sum(SearchCall.results_count).label("total_results"),
+ func.sum(SearchCall.results_count).label(
+ "total_results"
+ ),
func.sum(
- case((SearchCall.success_status == "success", 1), else_=0)
+ case(
+ (SearchCall.success_status == "success", 1),
+ else_=0,
+ )
).label("success_count"),
)
.filter(SearchCall.research_id == research_id)
@@ -217,7 +235,9 @@ class SearchTracker:
# Calculate totals
total_searches = len(search_calls)
- total_results = sum(call.results_count or 0 for call in search_calls)
+ total_results = sum(
+ call.results_count or 0 for call in search_calls
+ )
avg_response_time = (
sum(call.response_time_ms or 0 for call in search_calls)
/ total_searches
@@ -225,7 +245,9 @@ class SearchTracker:
else 0
)
successful_searches = sum(
- 1 for call in search_calls if call.success_status == "success"
+ 1
+ for call in search_calls
+ if call.success_status == "success"
)
success_rate = (
(successful_searches / total_searches * 100)
@@ -297,7 +319,9 @@ class SearchTracker:
)
# Apply time filter
- time_condition = get_time_filter_condition(period, SearchCall.timestamp)
+ time_condition = get_time_filter_condition(
+ period, SearchCall.timestamp
+ )
if time_condition is not None:
query = query.filter(time_condition)
diff --git a/src/local_deep_research/metrics/token_counter.py b/src/local_deep_research/metrics/token_counter.py
index 7ddb213520..0ab7245ee4 100644
--- a/src/local_deep_research/metrics/token_counter.py
+++ b/src/local_deep_research/metrics/token_counter.py
@@ -78,16 +78,15 @@ class TokenCountingCallback(BaseCallbackHandler):
and "site-packages" not in file_path
and "venv" not in file_path
):
-
# Extract relative path from local_deep_research
if "src/local_deep_research" in file_path:
- relative_path = file_path.split("src/local_deep_research")[
- -1
- ].lstrip("/")
+ relative_path = file_path.split(
+ "src/local_deep_research"
+ )[-1].lstrip("/")
elif "local_deep_research/src" in file_path:
- relative_path = file_path.split("local_deep_research/src")[
- -1
- ].lstrip("/")
+ relative_path = file_path.split(
+ "local_deep_research/src"
+ )[-1].lstrip("/")
elif "local_deep_research" in file_path:
# Get everything after local_deep_research
relative_path = file_path.split("local_deep_research")[
@@ -111,7 +110,9 @@ class TokenCountingCallback(BaseCallbackHandler):
call_stack_frames.append(frame_name)
self.call_stack = (
- " -> ".join(call_stack_frames) if call_stack_frames else None
+ " -> ".join(call_stack_frames)
+ if call_stack_frames
+ else None
)
break
except Exception as e:
@@ -131,9 +132,9 @@ class TokenCountingCallback(BaseCallbackHandler):
# First check invocation_params
invocation_params = kwargs.get("invocation_params", {})
- model_name = invocation_params.get("model") or invocation_params.get(
- "model_name"
- )
+ model_name = invocation_params.get(
+ "model"
+ ) or invocation_params.get("model_name")
# Check kwargs directly
if not model_name:
@@ -227,7 +228,9 @@ class TokenCountingCallback(BaseCallbackHandler):
usage_meta = generation.message.usage_metadata
token_usage = {
"prompt_tokens": usage_meta.get("input_tokens", 0),
- "completion_tokens": usage_meta.get("output_tokens", 0),
+ "completion_tokens": usage_meta.get(
+ "output_tokens", 0
+ ),
"total_tokens": usage_meta.get("total_tokens", 0),
}
break
@@ -240,9 +243,15 @@ class TokenCountingCallback(BaseCallbackHandler):
"eval_count"
):
token_usage = {
- "prompt_tokens": resp_meta.get("prompt_eval_count", 0),
- "completion_tokens": resp_meta.get("eval_count", 0),
- "total_tokens": resp_meta.get("prompt_eval_count", 0)
+ "prompt_tokens": resp_meta.get(
+ "prompt_eval_count", 0
+ ),
+ "completion_tokens": resp_meta.get(
+ "eval_count", 0
+ ),
+ "total_tokens": resp_meta.get(
+ "prompt_eval_count", 0
+ )
+ resp_meta.get("eval_count", 0),
}
break
@@ -268,9 +277,9 @@ class TokenCountingCallback(BaseCallbackHandler):
self.counts["by_model"][self.current_model][
"completion_tokens"
] += completion_tokens
- self.counts["by_model"][self.current_model][
- "total_tokens"
- ] += total_tokens
+ self.counts["by_model"][self.current_model]["total_tokens"] += (
+ total_tokens
+ )
# Save to database if we have a research_id
if self.research_id:
@@ -351,7 +360,8 @@ class TokenCountingCallback(BaseCallbackHandler):
model_usage = (
session.query(ModelUsage)
.filter_by(
- research_id=self.research_id, model_name=self.current_model
+ research_id=self.research_id,
+ model_name=self.current_model,
)
.first()
)
@@ -359,7 +369,9 @@ class TokenCountingCallback(BaseCallbackHandler):
if model_usage:
model_usage.prompt_tokens += prompt_tokens
model_usage.completion_tokens += completion_tokens
- model_usage.total_tokens += prompt_tokens + completion_tokens
+ model_usage.total_tokens += (
+ prompt_tokens + completion_tokens
+ )
model_usage.calls += 1
else:
model_usage = ModelUsage(
@@ -466,7 +478,9 @@ class TokenCounter:
query = session.query(TokenUsage)
# Apply time filter
- time_condition = get_time_filter_condition(period, TokenUsage.timestamp)
+ time_condition = get_time_filter_condition(
+ period, TokenUsage.timestamp
+ )
if time_condition is not None:
query = query.filter(time_condition)
@@ -479,7 +493,8 @@ class TokenCounter:
# Total tokens and researches
total_tokens = (
- query.with_entities(func.sum(TokenUsage.total_tokens)).scalar() or 0
+ query.with_entities(func.sum(TokenUsage.total_tokens)).scalar()
+ or 0
)
total_researches = (
query.with_entities(
@@ -494,7 +509,9 @@ class TokenCounter:
func.sum(TokenUsage.total_tokens).label("tokens"),
func.count().label("calls"),
func.sum(TokenUsage.prompt_tokens).label("prompt_tokens"),
- func.sum(TokenUsage.completion_tokens).label("completion_tokens"),
+ func.sum(TokenUsage.completion_tokens).label(
+ "completion_tokens"
+ ),
).filter(TokenUsage.model_name.isnot(None))
# Apply same filters to model stats
@@ -518,7 +535,9 @@ class TokenCounter:
.filter(ModelUsage.model_name == stat.model_name)
.first()
)
- provider = provider_info.provider if provider_info else "unknown"
+ provider = (
+ provider_info.provider if provider_info else "unknown"
+ )
by_model.append(
{
@@ -540,9 +559,13 @@ class TokenCounter:
).filter(TokenUsage.research_id.isnot(None))
if time_condition is not None:
- recent_research_query = recent_research_query.filter(time_condition)
+ recent_research_query = recent_research_query.filter(
+ time_condition
+ )
if mode_condition is not None:
- recent_research_query = recent_research_query.filter(mode_condition)
+ recent_research_query = recent_research_query.filter(
+ mode_condition
+ )
recent_research_data = (
recent_research_query.group_by(TokenUsage.research_id)
@@ -581,9 +604,13 @@ class TokenCounter:
# Token breakdown statistics
breakdown_query = query.with_entities(
func.sum(TokenUsage.prompt_tokens).label("total_input_tokens"),
- func.sum(TokenUsage.completion_tokens).label("total_output_tokens"),
+ func.sum(TokenUsage.completion_tokens).label(
+ "total_output_tokens"
+ ),
func.avg(TokenUsage.prompt_tokens).label("avg_input_tokens"),
- func.avg(TokenUsage.completion_tokens).label("avg_output_tokens"),
+ func.avg(TokenUsage.completion_tokens).label(
+ "avg_output_tokens"
+ ),
func.avg(TokenUsage.total_tokens).label("avg_total_tokens"),
)
token_breakdown = breakdown_query.first()
@@ -594,13 +621,21 @@ class TokenCounter:
"by_model": by_model,
"recent_researches": recent_researches,
"token_breakdown": {
- "total_input_tokens": int(token_breakdown.total_input_tokens or 0),
+ "total_input_tokens": int(
+ token_breakdown.total_input_tokens or 0
+ ),
"total_output_tokens": int(
token_breakdown.total_output_tokens or 0
),
- "avg_input_tokens": int(token_breakdown.avg_input_tokens or 0),
- "avg_output_tokens": int(token_breakdown.avg_output_tokens or 0),
- "avg_total_tokens": int(token_breakdown.avg_total_tokens or 0),
+ "avg_input_tokens": int(
+ token_breakdown.avg_input_tokens or 0
+ ),
+ "avg_output_tokens": int(
+ token_breakdown.avg_output_tokens or 0
+ ),
+ "avg_total_tokens": int(
+ token_breakdown.avg_total_tokens or 0
+ ),
},
}
@@ -621,7 +656,9 @@ class TokenCounter:
query = session.query(TokenUsage)
# Apply time filter
- time_condition = get_time_filter_condition(period, TokenUsage.timestamp)
+ time_condition = get_time_filter_condition(
+ period, TokenUsage.timestamp
+ )
if time_condition is not None:
query = query.filter(time_condition)
@@ -656,7 +693,9 @@ class TokenCounter:
time_series.append(
{
- "timestamp": str(usage.timestamp) if usage.timestamp else None,
+ "timestamp": str(usage.timestamp)
+ if usage.timestamp
+ else None,
"tokens": usage.total_tokens or 0,
"prompt_tokens": usage.prompt_tokens or 0,
"completion_tokens": usage.completion_tokens or 0,
@@ -669,7 +708,9 @@ class TokenCounter:
)
# Basic performance stats using ORM
- performance_query = query.filter(TokenUsage.response_time_ms.isnot(None))
+ performance_query = query.filter(
+ TokenUsage.response_time_ms.isnot(None)
+ )
total_calls = performance_query.count()
if total_calls > 0:
@@ -731,7 +772,9 @@ class TokenCounter:
TokenUsage.research_mode,
func.count().label("count"),
func.avg(TokenUsage.total_tokens).label("avg_tokens"),
- func.avg(TokenUsage.response_time_ms).label("avg_response_time"),
+ func.avg(TokenUsage.response_time_ms).label(
+ "avg_response_time"
+ ),
)
.group_by(TokenUsage.research_mode)
.all()
@@ -769,7 +812,9 @@ class TokenCounter:
"total_tokens": usage.total_tokens,
"prompt_tokens": usage.prompt_tokens,
"completion_tokens": usage.completion_tokens,
- "timestamp": str(usage.timestamp) if usage.timestamp else None,
+ "timestamp": str(usage.timestamp)
+ if usage.timestamp
+ else None,
"research_id": usage.research_id,
"calling_file": usage.calling_file,
"calling_function": usage.calling_function,
@@ -785,7 +830,9 @@ class TokenCounter:
TokenUsage.search_engine_selected,
func.count().label("count"),
func.avg(TokenUsage.total_tokens).label("avg_tokens"),
- func.avg(TokenUsage.response_time_ms).label("avg_response_time"),
+ func.avg(TokenUsage.response_time_ms).label(
+ "avg_response_time"
+ ),
)
.group_by(TokenUsage.search_engine_selected)
.all()
@@ -808,7 +855,9 @@ class TokenCounter:
TokenUsage.research_phase,
func.count().label("count"),
func.avg(TokenUsage.total_tokens).label("avg_tokens"),
- func.avg(TokenUsage.response_time_ms).label("avg_response_time"),
+ func.avg(TokenUsage.response_time_ms).label(
+ "avg_response_time"
+ ),
)
.group_by(TokenUsage.research_phase)
.all()
@@ -970,8 +1019,12 @@ class TokenCounter:
"query": research_info[0],
"mode": research_info[1],
"status": research_info[2],
- "created_at": str(research_info[3]) if research_info[3] else None,
- "completed_at": str(research_info[4]) if research_info[4] else None,
+ "created_at": str(research_info[3])
+ if research_info[3]
+ else None,
+ "completed_at": str(research_info[4])
+ if research_info[4]
+ else None,
}
# Calculate summary stats
diff --git a/src/local_deep_research/migrate_db.py b/src/local_deep_research/migrate_db.py
index 1dad8f8b50..a2d37b1f67 100644
--- a/src/local_deep_research/migrate_db.py
+++ b/src/local_deep_research/migrate_db.py
@@ -60,7 +60,9 @@ def main():
action="store_true",
help="Only check what would be migrated, don't perform actual migration",
)
- parser.add_argument("--verbose", action="store_true", help="Enable verbose logging")
+ parser.add_argument(
+ "--verbose", action="store_true", help="Enable verbose logging"
+ )
args = parser.parse_args()
diff --git a/src/local_deep_research/report_generator.py b/src/local_deep_research/report_generator.py
index e5dd537c0f..9d50e66bfa 100644
--- a/src/local_deep_research/report_generator.py
+++ b/src/local_deep_research/report_generator.py
@@ -36,7 +36,9 @@ class IntegratedReportGenerator:
"""
self.model = llm or get_llm()
# Use provided search_system or create a new one
- self.search_system = search_system or AdvancedSearchSystem(llm=self.model)
+ self.search_system = search_system or AdvancedSearchSystem(
+ llm=self.model
+ )
self.searches_per_section = (
searches_per_section # Control search depth per section
)
@@ -57,7 +59,9 @@ class IntegratedReportGenerator:
return report
- def _determine_report_structure(self, findings: Dict, query: str) -> List[Dict]:
+ def _determine_report_structure(
+ self, findings: Dict, query: str
+ ) -> List[Dict]:
"""Analyze content and determine optimal report structure."""
combined_content = findings["current_knowledge"]
prompt = f"""
@@ -84,7 +88,9 @@ class IntegratedReportGenerator:
Each subsection must include its purpose after the | symbol.
"""
- response = search_utilities.remove_think_tags(self.model.invoke(prompt).content)
+ response = search_utilities.remove_think_tags(
+ self.model.invoke(prompt).content
+ )
# Parse the structure
structure = []
@@ -141,7 +147,9 @@ class IntegratedReportGenerator:
self.search_system.max_iterations = 1 # Keep search focused
# Perform search for this subsection
- subsection_results = self.search_system.analyze_topic(subsection_query)
+ subsection_results = self.search_system.analyze_topic(
+ subsection_query
+ )
# Restore original iterations setting
self.search_system.max_iterations = original_max_iterations
@@ -151,7 +159,9 @@ class IntegratedReportGenerator:
"current_knowledge" in subsection_results
and subsection_results["current_knowledge"]
):
- section_content.append(subsection_results["current_knowledge"])
+ section_content.append(
+ subsection_results["current_knowledge"]
+ )
else:
section_content.append(
"*Limited information was found for this subsection.*\n"
@@ -215,8 +225,10 @@ class IntegratedReportGenerator:
# Format links from search system
# Get utilities module dynamically to avoid circular imports
utilities = importlib.import_module("local_deep_research.utilities")
- formatted_all_links = utilities.search_utilities.format_links_to_markdown(
- all_links=self.search_system.all_links_of_system
+ formatted_all_links = (
+ utilities.search_utilities.format_links_to_markdown(
+ all_links=self.search_system.all_links_of_system
+ )
)
# Create final report with all parts
@@ -240,5 +252,7 @@ class IntegratedReportGenerator:
return {"content": final_report_content, "metadata": metadata}
def _generate_error_report(self, query: str, error_msg: str) -> str:
- error_report = f"=== ERROR REPORT ===\nQuery: {query}\nError: {error_msg}"
+ error_report = (
+ f"=== ERROR REPORT ===\nQuery: {query}\nError: {error_msg}"
+ )
return error_report
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index 0747de01a3..0abad1ace5 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -26,14 +26,18 @@ from .advanced_search_system.strategies.evidence_based_strategy_v2 import (
from .advanced_search_system.strategies.iterative_reasoning_strategy import (
IterativeReasoningStrategy,
)
-from .advanced_search_system.strategies.iterdrag_strategy import IterDRAGStrategy
+from .advanced_search_system.strategies.iterdrag_strategy import (
+ IterDRAGStrategy,
+)
from .advanced_search_system.strategies.parallel_constrained_strategy import (
ParallelConstrainedStrategy,
)
from .advanced_search_system.strategies.parallel_search_strategy import (
ParallelSearchStrategy,
)
-from .advanced_search_system.strategies.rapid_search_strategy import RapidSearchStrategy
+from .advanced_search_system.strategies.rapid_search_strategy import (
+ RapidSearchStrategy,
+)
from .advanced_search_system.strategies.recursive_decomposition_strategy import (
RecursiveDecompositionStrategy,
)
@@ -43,7 +47,9 @@ from .advanced_search_system.strategies.smart_decomposition_strategy import (
from .advanced_search_system.strategies.source_based_strategy import (
SourceBasedSearchStrategy,
)
-from .advanced_search_system.strategies.standard_strategy import StandardSearchStrategy
+from .advanced_search_system.strategies.standard_strategy import (
+ StandardSearchStrategy,
+)
from .citation_handler import CitationHandler
from .config.llm_config import get_llm
from .config.search_config import get_search
@@ -255,7 +261,10 @@ class AdvancedSearchSystem:
questions_per_iteration=self.questions_per_iteration,
min_candidates_per_stage=20, # Increased from 5
)
- elif strategy_name.lower() in ["parallel-constrained", "parallel_constrained"]:
+ elif strategy_name.lower() in [
+ "parallel-constrained",
+ "parallel_constrained",
+ ]:
logger.info("Creating ParallelConstrainedStrategy instance")
self.strategy = ParallelConstrainedStrategy(
model=self.model,
@@ -447,7 +456,10 @@ class AdvancedSearchSystem:
constraint_checker_type="dual_confidence", # Concurrent evaluation with +/-/? scoring
exploration_strategy="parallel", # Parallel constraint searches
)
- elif strategy_name.lower() in ["focused-iteration", "focused_iteration"]:
+ elif strategy_name.lower() in [
+ "focused-iteration",
+ "focused_iteration",
+ ]:
from .advanced_search_system.strategies.focused_iteration_strategy import (
FocusedIterationStrategy,
)
@@ -463,7 +475,10 @@ class AdvancedSearchSystem:
questions_per_iteration=5, # PROVEN OPTIMAL FOR SIMPLEQA
use_browsecomp_optimization=True, # Enable BrowseComp optimizations
)
- elif strategy_name.lower() in ["browsecomp-entity", "browsecomp_entity"]:
+ elif strategy_name.lower() in [
+ "browsecomp-entity",
+ "browsecomp_entity",
+ ]:
from .advanced_search_system.strategies.browsecomp_entity_strategy import (
BrowseCompEntityStrategy,
)
@@ -489,13 +504,17 @@ class AdvancedSearchSystem:
if hasattr(self, "progress_callback") and self.progress_callback:
self.strategy.set_progress_callback(self.progress_callback)
- def _progress_callback(self, message: str, progress: int, metadata: dict) -> None:
+ def _progress_callback(
+ self, message: str, progress: int, metadata: dict
+ ) -> None:
"""Handle progress updates from the strategy."""
logger.info(f"Progress: {progress}% - {message}")
if hasattr(self, "progress_callback"):
self.progress_callback(message, progress, metadata)
- def set_progress_callback(self, callback: Callable[[str, int, dict], None]) -> None:
+ def set_progress_callback(
+ self, callback: Callable[[str, int, dict], None]
+ ) -> None:
"""Set a callback function to receive progress updates."""
self.progress_callback = callback
if hasattr(self, "strategy"):
@@ -539,13 +558,17 @@ class AdvancedSearchSystem:
# Update our attributes for backward compatibility
- self.questions_by_iteration = self.strategy.questions_by_iteration.copy()
+ self.questions_by_iteration = (
+ self.strategy.questions_by_iteration.copy()
+ )
# Send progress message with search info
# Only extend if they're different objects in memory to avoid duplication
# This check prevents doubling the list when they reference the same object
# Fix for issue #301: "too many links in detailed report mode"
- if id(self.all_links_of_system) != id(self.strategy.all_links_of_system):
+ if id(self.all_links_of_system) != id(
+ self.strategy.all_links_of_system
+ ):
self.all_links_of_system.extend(self.strategy.all_links_of_system)
# Include the search system instance for access to citations
diff --git a/src/local_deep_research/test_migration.py b/src/local_deep_research/test_migration.py
index 549786886e..237bc702a4 100644
--- a/src/local_deep_research/test_migration.py
+++ b/src/local_deep_research/test_migration.py
@@ -24,7 +24,9 @@ def check_db_content(db_path, description):
# Get list of tables
cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
tables = [
- row[0] for row in cursor.fetchall() if not row[0].startswith("sqlite_")
+ row[0]
+ for row in cursor.fetchall()
+ if not row[0].startswith("sqlite_")
]
if not tables:
@@ -56,7 +58,9 @@ def check_db_content(db_path, description):
key_cols = (
"id, query, status"
if table == "research_history"
- else "id, key, value" if table == "settings" else "id, message"
+ else "id, key, value"
+ if table == "settings"
+ else "id, message"
)
cursor.execute(f"SELECT {key_cols} FROM {table} LIMIT 3")
sample = cursor.fetchall()
@@ -110,13 +114,19 @@ def main():
if choice == "y":
# Run the migration script directly
try:
- from src.local_deep_research.setup_data_dir import setup_data_dir
+ from src.local_deep_research.setup_data_dir import (
+ setup_data_dir,
+ )
except ImportError:
# If that fails, try with the direct import
sys.path.append(
- os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ os.path.dirname(
+ os.path.dirname(os.path.abspath(__file__))
+ )
+ )
+ from local_deep_research.setup_data_dir import (
+ setup_data_dir,
)
- from local_deep_research.setup_data_dir import setup_data_dir
setup_data_dir()
diff --git a/src/local_deep_research/utilities/db_utils.py b/src/local_deep_research/utilities/db_utils.py
index 6ce388aa97..95737623ab 100644
--- a/src/local_deep_research/utilities/db_utils.py
+++ b/src/local_deep_research/utilities/db_utils.py
@@ -10,7 +10,9 @@ from ..utilities.threading_utils import thread_specific_cache
from ..web.services.settings_manager import SettingsManager
# Database path.
-DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "data"))
+DATA_DIR = os.path.abspath(
+ os.path.join(os.path.dirname(__file__), "..", "..", "data")
+)
DB_PATH = os.path.join(DATA_DIR, "ldr.db")
diff --git a/src/local_deep_research/utilities/es_utils.py b/src/local_deep_research/utilities/es_utils.py
index 22bcdb3c00..64c429db9a 100644
--- a/src/local_deep_research/utilities/es_utils.py
+++ b/src/local_deep_research/utilities/es_utils.py
@@ -2,10 +2,9 @@
Elasticsearch utilities for indexing and managing documents.
"""
-import json
import logging
import os
-from typing import Any, Dict, List, Optional, Union
+from typing import Any, Dict, List, Optional
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk
@@ -68,7 +67,9 @@ class ElasticsearchManager:
)
except Exception as e:
logger.error(f"Failed to connect to Elasticsearch: {str(e)}")
- raise ConnectionError(f"Could not connect to Elasticsearch: {str(e)}")
+ raise ConnectionError(
+ f"Could not connect to Elasticsearch: {str(e)}"
+ )
def create_index(
self,
@@ -103,7 +104,10 @@ class ElasticsearchManager:
"type": "text",
"analyzer": "standard",
"fields": {
- "keyword": {"type": "keyword", "ignore_above": 256}
+ "keyword": {
+ "type": "keyword",
+ "ignore_above": 256,
+ }
},
},
"content": {"type": "text", "analyzer": "standard"},
@@ -119,7 +123,9 @@ class ElasticsearchManager:
settings = {
"number_of_shards": 1,
"number_of_replicas": 0,
- "analysis": {"analyzer": {"standard": {"type": "standard"}}},
+ "analysis": {
+ "analyzer": {"standard": {"type": "standard"}}
+ },
}
# Create the index with mappings and settings
@@ -248,7 +254,9 @@ class ElasticsearchManager:
return success
except Exception as e:
- logger.error(f"Error bulk indexing documents in '{index_name}': {str(e)}")
+ logger.error(
+ f"Error bulk indexing documents in '{index_name}': {str(e)}"
+ )
return 0
def index_file(
@@ -275,7 +283,9 @@ class ElasticsearchManager:
str: Document ID if successful, None otherwise
"""
try:
- from langchain_community.document_loaders import UnstructuredFileLoader
+ from langchain_community.document_loaders import (
+ UnstructuredFileLoader,
+ )
# Extract file content and metadata
loader = UnstructuredFileLoader(file_path)
@@ -304,7 +314,9 @@ class ElasticsearchManager:
# Add file-specific metadata
document["source"] = file_path
- document["file_extension"] = os.path.splitext(filename)[1].lstrip(".")
+ document["file_extension"] = os.path.splitext(filename)[
+ 1
+ ].lstrip(".")
document["filename"] = filename
# Index the document
@@ -380,7 +392,9 @@ class ElasticsearchManager:
return successful_count
except Exception as e:
- logger.error(f"Error indexing directory '{directory_path}': {str(e)}")
+ logger.error(
+ f"Error indexing directory '{directory_path}': {str(e)}"
+ )
return 0
def search(
diff --git a/src/local_deep_research/utilities/llm_utils.py b/src/local_deep_research/utilities/llm_utils.py
index 756dd0d6e3..44db195965 100644
--- a/src/local_deep_research/utilities/llm_utils.py
+++ b/src/local_deep_research/utilities/llm_utils.py
@@ -78,7 +78,9 @@ def get_model(
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
raise ValueError("OPENAI_API_KEY environment variable not set")
- return ChatOpenAI(model=model_name, api_key=api_key, **common_params)
+ return ChatOpenAI(
+ model=model_name, api_key=api_key, **common_params
+ )
except ImportError:
logger.error("langchain_openai not available")
raise
@@ -89,7 +91,9 @@ def get_model(
api_key = os.getenv("ANTHROPIC_API_KEY")
if not api_key:
- raise ValueError("ANTHROPIC_API_KEY environment variable not set")
+ raise ValueError(
+ "ANTHROPIC_API_KEY environment variable not set"
+ )
return ChatAnthropic(
model=model_name, anthropic_api_key=api_key, **common_params
)
@@ -103,7 +107,9 @@ def get_model(
api_key = os.getenv("OPENAI_ENDPOINT_API_KEY")
if not api_key:
- raise ValueError("OPENAI_ENDPOINT_API_KEY environment variable not set")
+ raise ValueError(
+ "OPENAI_ENDPOINT_API_KEY environment variable not set"
+ )
endpoint_url = kwargs.get(
"OPENAI_ENDPOINT_URL", "https://openrouter.ai/api/v1"
@@ -113,7 +119,9 @@ def get_model(
"OPENAI_ENDPOINT_REQUIRES_MODEL", True
):
return ChatOpenAI(
- api_key=api_key, openai_api_base=endpoint_url, **common_params
+ api_key=api_key,
+ openai_api_base=endpoint_url,
+ **common_params,
)
else:
return ChatOpenAI(
@@ -130,7 +138,9 @@ def get_model(
try:
from langchain_ollama import ChatOllama
- logger.warning(f"Unknown model type '{model_type}', defaulting to Ollama")
+ logger.warning(
+ f"Unknown model type '{model_type}', defaulting to Ollama"
+ )
return ChatOllama(model=model_name, **common_params)
except (ImportError, Exception) as e:
logger.error(f"Failed to load any model: {e}")
diff --git a/src/local_deep_research/utilities/log_utils.py b/src/local_deep_research/utilities/log_utils.py
index 1b321927dd..a158789926 100644
--- a/src/local_deep_research/utilities/log_utils.py
+++ b/src/local_deep_research/utilities/log_utils.py
@@ -56,7 +56,9 @@ class InterceptHandler(logging.Handler):
)
-def log_for_research(to_wrap: Callable[[int, ...], Any]) -> Callable[[int, ...], Any]:
+def log_for_research(
+ to_wrap: Callable[[int, ...], Any],
+) -> Callable[[int, ...], Any]:
"""
Decorator for a function that's part of the research process. It expects the function to
take the research ID as the first parameter, and configures all log
diff --git a/src/local_deep_research/utilities/search_cache.py b/src/local_deep_research/utilities/search_cache.py
index 3fcecee308..8509568488 100644
--- a/src/local_deep_research/utilities/search_cache.py
+++ b/src/local_deep_research/utilities/search_cache.py
@@ -95,7 +95,9 @@ class SearchCache:
return normalized
- def _get_query_hash(self, query: str, search_engine: str = "default") -> str:
+ def _get_query_hash(
+ self, query: str, search_engine: str = "default"
+ ) -> str:
"""Generate hash for query + search engine combination."""
normalized_query = self._normalize_query(query)
cache_key = f"{search_engine}:{normalized_query}"
@@ -108,7 +110,8 @@ class SearchCache:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
- "DELETE FROM search_cache WHERE expires_at < ?", (current_time,)
+ "DELETE FROM search_cache WHERE expires_at < ?",
+ (current_time,),
)
deleted = cursor.rowcount
conn.commit()
@@ -196,7 +199,9 @@ class SearchCache:
self._access_times[query_hash] = current_time
self._evict_lru_memory()
- logger.debug(f"Cache hit (database) for query: {query[:50]}...")
+ logger.debug(
+ f"Cache hit (database) for query: {query[:50]}..."
+ )
return results
except Exception as e:
@@ -281,7 +286,8 @@ class SearchCache:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
- "DELETE FROM search_cache WHERE query_hash = ?", (query_hash,)
+ "DELETE FROM search_cache WHERE query_hash = ?",
+ (query_hash,),
)
deleted = cursor.rowcount
conn.commit()
diff --git a/src/local_deep_research/utilities/search_utilities.py b/src/local_deep_research/utilities/search_utilities.py
index 27f7fcdb71..8afcfca335 100644
--- a/src/local_deep_research/utilities/search_utilities.py
+++ b/src/local_deep_research/utilities/search_utilities.py
@@ -47,7 +47,6 @@ def format_links_to_markdown(all_links: List[Dict]) -> str:
logger.info(f"Formatting {len(all_links)} links to markdown...")
if all_links:
-
# Group links by URL and collect all their indices
url_to_indices = {}
for link in all_links:
@@ -57,7 +56,6 @@ def format_links_to_markdown(all_links: List[Dict]) -> str:
index = link.get("index", "")
# logger.info(f"URL \n {str(url)} ")
if url:
-
if url not in url_to_indices:
url_to_indices[url] = []
url_to_indices[url].append(index)
@@ -139,7 +137,9 @@ def format_findings(
logger.info(f"Formatting {len(findings_list)} detailed finding items.")
for idx, finding in enumerate(findings_list):
- logger.debug(f"Formatting finding item {idx}. Keys: {list(finding.keys())}")
+ logger.debug(
+ f"Formatting finding item {idx}. Keys: {list(finding.keys())}"
+ )
# Use .get() for safety
phase = finding.get("phase", "Unknown Phase")
content = finding.get("content", "No content available.")
@@ -201,8 +201,14 @@ def format_findings(
)
# If the question is in the finding itself, display it
- if not question_displayed and "question" in finding and finding["question"]:
- formatted_text += f"### SEARCH QUESTION:\n{finding['question']}\n\n"
+ if (
+ not question_displayed
+ and "question" in finding
+ and finding["question"]
+ ):
+ formatted_text += (
+ f"### SEARCH QUESTION:\n{finding['question']}\n\n"
+ )
# Content
formatted_text += f"\n\n{content}\n\n"
@@ -213,7 +219,9 @@ def format_findings(
links = extract_links_from_search_results(search_results)
if links:
formatted_text += "### SOURCES USED IN THIS SECTION:\n"
- formatted_text += format_links_to_markdown(links) + "\n\n"
+ formatted_text += (
+ format_links_to_markdown(links) + "\n\n"
+ )
except Exception:
logger.exception(
f"Error processing search results/links for finding {idx}"
diff --git a/src/local_deep_research/utilities/threading_utils.py b/src/local_deep_research/utilities/threading_utils.py
index 9b9c1be14e..01162fe8a1 100644
--- a/src/local_deep_research/utilities/threading_utils.py
+++ b/src/local_deep_research/utilities/threading_utils.py
@@ -46,7 +46,9 @@ def thread_with_app_context(to_wrap: Callable) -> Callable:
"""
@wraps(to_wrap)
- def _run_with_context(app_context: AppContext, *args: Any, **kwargs: Any) -> Any:
+ def _run_with_context(
+ app_context: AppContext, *args: Any, **kwargs: Any
+ ) -> Any:
with app_context:
return to_wrap(*args, **kwargs)
diff --git a/src/local_deep_research/web/api.py b/src/local_deep_research/web/api.py
index b3d36c78f3..c880a8f699 100644
--- a/src/local_deep_research/web/api.py
+++ b/src/local_deep_research/web/api.py
@@ -48,7 +48,9 @@ def api_access_control(f):
# Remove timestamps older than 1 minute
rate_limit_data[client_ip] = [
- ts for ts in rate_limit_data[client_ip] if current_time - ts < 60
+ ts
+ for ts in rate_limit_data[client_ip]
+ if current_time - ts < 60
]
# Check if rate limit is exceeded
@@ -155,10 +157,14 @@ def api_quick_summary_test():
return jsonify(result)
except Exception as e:
- logger.error(f"Error in quick_summary_test API: {str(e)}", exc_info=True)
+ logger.error(
+ f"Error in quick_summary_test API: {str(e)}", exc_info=True
+ )
return (
jsonify(
- {"error": "An internal error has occurred. Please try again later."}
+ {
+ "error": "An internal error has occurred. Please try again later."
+ }
),
500,
)
@@ -215,7 +221,9 @@ def api_quick_summary():
logger.error(f"Error in quick_summary API: {str(e)}", exc_info=True)
return (
jsonify(
- {"error": "An internal error has occurred. Please try again later."}
+ {
+ "error": "An internal error has occurred. Please try again later."
+ }
),
500,
)
@@ -265,7 +273,9 @@ def api_generate_report():
and len(result["content"]) > 10000
):
# Include a summary of the report content
- content_preview = result["content"][:2000] + "... [Content truncated]"
+ content_preview = (
+ result["content"][:2000] + "... [Content truncated]"
+ )
result["content"] = content_preview
result["content_truncated"] = True
@@ -273,14 +283,18 @@ def api_generate_report():
except TimeoutError:
logger.error("Request timed out")
return (
- jsonify({"error": "Request timed out. Please try with a simpler query."}),
+ jsonify(
+ {"error": "Request timed out. Please try with a simpler query."}
+ ),
504,
)
except Exception as e:
logger.error(f"Error in generate_report API: {str(e)}", exc_info=True)
return (
jsonify(
- {"error": "An internal error has occurred. Please try again later."}
+ {
+ "error": "An internal error has occurred. Please try again later."
+ }
),
500,
)
@@ -305,14 +319,18 @@ def api_analyze_documents():
if not data or "query" not in data or "collection_name" not in data:
return (
jsonify(
- {"error": "Both query and collection_name parameters are required"}
+ {
+ "error": "Both query and collection_name parameters are required"
+ }
),
400,
)
query = data.get("query")
collection_name = data.get("collection_name")
- params = {k: v for k, v in data.items() if k not in ["query", "collection_name"]}
+ params = {
+ k: v for k, v in data.items() if k not in ["query", "collection_name"]
+ }
try:
result = analyze_documents(query, collection_name, **params)
@@ -321,7 +339,9 @@ def api_analyze_documents():
logger.error(f"Error in analyze_documents API: {str(e)}", exc_info=True)
return (
jsonify(
- {"error": "An internal error has occurred. Please try again later."}
+ {
+ "error": "An internal error has occurred. Please try again later."
+ }
),
500,
)
diff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.py
index 1ed921b33a..70e920f348 100644
--- a/src/local_deep_research/web/app.py
+++ b/src/local_deep_research/web/app.py
@@ -36,9 +36,9 @@ def check_migration_needed():
"""Check if database migration is needed, based on presence of legacy files and absence of new DB"""
if not os.path.exists(DB_PATH):
# The new database doesn't exist, check if legacy databases exist
- legacy_files_exist = os.path.exists(LEGACY_DEEP_RESEARCH_DB) or os.path.exists(
- LEGACY_RESEARCH_HISTORY_DB
- )
+ legacy_files_exist = os.path.exists(
+ LEGACY_DEEP_RESEARCH_DB
+ ) or os.path.exists(LEGACY_RESEARCH_HISTORY_DB)
if legacy_files_exist:
logger.info(
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index eb0f5929a3..62a3fae6eb 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -36,7 +36,9 @@ def create_app():
TEMPLATE_DIR = (package_dir / "templates").as_posix()
# Initialize Flask app with package directories
- app = Flask(__name__, static_folder=STATIC_DIR, template_folder=TEMPLATE_DIR)
+ app = Flask(
+ __name__, static_folder=STATIC_DIR, template_folder=TEMPLATE_DIR
+ )
logger.debug(f"Using package static path: {STATIC_DIR}")
logger.debug(f"Using package template path: {TEMPLATE_DIR}")
except Exception:
@@ -198,7 +200,8 @@ def register_blueprints(app):
csrf.exempt("api")
for rule in app.url_map.iter_rules():
if rule.endpoint and (
- rule.endpoint.startswith("api_v1.") or rule.endpoint.startswith("api.")
+ rule.endpoint.startswith("api_v1.")
+ or rule.endpoint.startswith("api.")
):
csrf.exempt(rule.endpoint)
@@ -250,7 +253,9 @@ def create_database(app):
Base.metadata.create_all(engine)
# Configure session factory
- session_factory = sessionmaker(bind=engine, autocommit=False, autoflush=False)
+ session_factory = sessionmaker(
+ bind=engine, autocommit=False, autoflush=False
+ )
app.db_session = scoped_session(session_factory)
# Run migrations and setup predefined settings
diff --git a/src/local_deep_research/web/database/migrate_to_ldr_db.py b/src/local_deep_research/web/database/migrate_to_ldr_db.py
index 3f3850930b..a9fb46057f 100644
--- a/src/local_deep_research/web/database/migrate_to_ldr_db.py
+++ b/src/local_deep_research/web/database/migrate_to_ldr_db.py
@@ -90,7 +90,9 @@ def migrate_to_ldr_db():
)
# Migrate from deep_research.db
- migrated_deep_research = migrate_deep_research_db(ldr_conn, LEGACY_DEEP_RESEARCH_DB)
+ migrated_deep_research = migrate_deep_research_db(
+ ldr_conn, LEGACY_DEEP_RESEARCH_DB
+ )
# Re-enable foreign keys and commit
ldr_cursor.execute("PRAGMA foreign_keys = ON")
@@ -127,7 +129,9 @@ def migrate_research_history_db(ldr_conn, legacy_path):
logger.info(f"Connected to legacy database: {legacy_path}")
# Get tables from legacy database
- legacy_cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
+ legacy_cursor.execute(
+ "SELECT name FROM sqlite_master WHERE type='table'"
+ )
tables = [row[0] for row in legacy_cursor.fetchall()]
for table in tables:
@@ -181,7 +185,9 @@ def migrate_research_history_db(ldr_conn, legacy_path):
# Verify data was inserted
ldr_cursor.execute(f"SELECT COUNT(*) FROM {table}")
count = ldr_cursor.fetchone()[0]
- logger.info(f"Migrated {count} rows to {table} (expected {len(rows)})")
+ logger.info(
+ f"Migrated {count} rows to {table} (expected {len(rows)})"
+ )
else:
logger.info(f"No data to migrate from {table}")
@@ -218,7 +224,9 @@ def migrate_deep_research_db(ldr_conn, legacy_path):
logger.info(f"Connected to legacy database: {legacy_path}")
# Get tables from legacy database
- legacy_cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
+ legacy_cursor.execute(
+ "SELECT name FROM sqlite_master WHERE type='table'"
+ )
tables = [row[0] for row in legacy_cursor.fetchall()]
# Migrate each table
diff --git a/src/local_deep_research/web/database/migrations.py b/src/local_deep_research/web/database/migrations.py
index 2df2ee3cf3..2064c58be0 100644
--- a/src/local_deep_research/web/database/migrations.py
+++ b/src/local_deep_research/web/database/migrations.py
@@ -24,14 +24,12 @@ def import_default_settings_file(db_session):
settings_mgr.load_from_defaults_file(overwrite=False, delete_extra=True)
logger.info("Successfully imported settings from files")
-
# Update the saved version.
settings_mgr.update_db_version()
except Exception as e:
logger.error("Error importing settings from files: %s", e)
-
def run_migrations(engine, db_session=None):
"""
Run any necessary database migrations
diff --git a/src/local_deep_research/web/database/models.py b/src/local_deep_research/web/database/models.py
index bb2d3c5c4c..9b2d56a0c4 100644
--- a/src/local_deep_research/web/database/models.py
+++ b/src/local_deep_research/web/database/models.py
@@ -42,7 +42,9 @@ class Research(Base):
status = Column(
Enum(ResearchStatus), default=ResearchStatus.PENDING, nullable=False
)
- mode = Column(Enum(ResearchMode), default=ResearchMode.QUICK, nullable=False)
+ mode = Column(
+ Enum(ResearchMode), default=ResearchMode.QUICK, nullable=False
+ )
created_at = Column(DateTime, server_default=func.now(), nullable=False)
updated_at = Column(
DateTime, server_default=func.now(), onupdate=func.now(), nullable=False
@@ -64,7 +66,9 @@ class Research(Base):
class ResearchLog(Base):
__tablename__ = "app_logs"
- id = Column(Integer, Sequence("reseach_log_id_seq"), primary_key=True, index=True)
+ id = Column(
+ Integer, Sequence("reseach_log_id_seq"), primary_key=True, index=True
+ )
timestamp = Column(DateTime, server_default=func.now(), nullable=False)
message = Column(Text, nullable=False)
@@ -148,7 +152,9 @@ class Journal(Base):
__tablename__ = "journals"
- id = Column(Integer, Sequence("journal_id_seq"), primary_key=True, index=True)
+ id = Column(
+ Integer, Sequence("journal_id_seq"), primary_key=True, index=True
+ )
# Name of the journal
name = Column(String(255), nullable=False, unique=True, index=True)
diff --git a/src/local_deep_research/web/database/schema_upgrade.py b/src/local_deep_research/web/database/schema_upgrade.py
index dc3e9aedce..0d7def1f57 100644
--- a/src/local_deep_research/web/database/schema_upgrade.py
+++ b/src/local_deep_research/web/database/schema_upgrade.py
@@ -19,7 +19,9 @@ try:
except ImportError:
# Fallback path if import fails
current_dir = os.path.dirname(os.path.abspath(__file__))
- project_root = os.path.abspath(os.path.join(current_dir, "..", "..", "..", ".."))
+ project_root = os.path.abspath(
+ os.path.join(current_dir, "..", "..", "..", "..")
+ )
DB_PATH = os.path.join(project_root, "src", "data", "ldr.db")
@@ -36,7 +38,8 @@ def check_table_exists(conn, table_name):
"""
cursor = conn.cursor()
cursor.execute(
- "SELECT name FROM sqlite_master WHERE type='table' AND name=?", (table_name,)
+ "SELECT name FROM sqlite_master WHERE type='table' AND name=?",
+ (table_name,),
)
return cursor.fetchone() is not None
@@ -78,7 +81,9 @@ def run_schema_upgrades():
"""
# Check if database exists
if not os.path.exists(DB_PATH):
- logger.warning(f"Database not found at {DB_PATH}, skipping schema upgrades")
+ logger.warning(
+ f"Database not found at {DB_PATH}, skipping schema upgrades"
+ )
return False
logger.info(f"Running schema upgrades on {DB_PATH}")
diff --git a/src/local_deep_research/web/models/database.py b/src/local_deep_research/web/models/database.py
index ddfba27323..59e942eece 100644
--- a/src/local_deep_research/web/models/database.py
+++ b/src/local_deep_research/web/models/database.py
@@ -17,7 +17,9 @@ DB_PATH = os.path.join(DATA_DIR, "ldr.db")
# Legacy database paths (for migration)
LEGACY_RESEARCH_HISTORY_DB = os.path.abspath(
- os.path.join(os.path.dirname(__file__), "..", "..", "..", "research_history.db")
+ os.path.join(
+ os.path.dirname(__file__), "..", "..", "..", "research_history.db"
+ )
)
LEGACY_DEEP_RESEARCH_DB = os.path.join(
os.path.abspath(
@@ -99,7 +101,9 @@ def init_db():
columns = [column[1] for column in cursor.fetchall()]
if "duration_seconds" not in columns:
- print("Adding missing 'duration_seconds' column to research_history table")
+ print(
+ "Adding missing 'duration_seconds' column to research_history table"
+ )
cursor.execute(
"ALTER TABLE research_history ADD COLUMN duration_seconds INTEGER"
)
@@ -107,7 +111,9 @@ def init_db():
# Check if the progress column exists, add it if missing
if "progress" not in columns:
print("Adding missing 'progress' column to research_history table")
- cursor.execute("ALTER TABLE research_history ADD COLUMN progress INTEGER")
+ cursor.execute(
+ "ALTER TABLE research_history ADD COLUMN progress INTEGER"
+ )
# Check if the title column exists, add it if missing
if "title" not in columns:
@@ -182,10 +188,14 @@ def calculate_duration(created_at_str, completed_at_str=None):
else: # Older format without T
# Try different formats
try:
- start_time = datetime.strptime(created_at_str, "%Y-%m-%d %H:%M:%S.%f")
+ start_time = datetime.strptime(
+ created_at_str, "%Y-%m-%d %H:%M:%S.%f"
+ )
except ValueError:
try:
- start_time = datetime.strptime(created_at_str, "%Y-%m-%d %H:%M:%S")
+ start_time = datetime.strptime(
+ created_at_str, "%Y-%m-%d %H:%M:%S"
+ )
except ValueError:
# Last resort fallback
start_time = datetime.fromisoformat(
@@ -200,7 +210,7 @@ def calculate_duration(created_at_str, completed_at_str=None):
start_time = parser.parse(created_at_str)
except Exception:
logger.exception(
- f"Fallback parsing also failed for created_at:" f" {created_at_str}"
+ f"Fallback parsing also failed for created_at: {created_at_str}"
)
return None
diff --git a/src/local_deep_research/web/routes/api_routes.py b/src/local_deep_research/web/routes/api_routes.py
index 6c50a0fdac..09f6539330 100644
--- a/src/local_deep_research/web/routes/api_routes.py
+++ b/src/local_deep_research/web/routes/api_routes.py
@@ -118,7 +118,9 @@ def api_research_status(research_id):
try:
metadata = json.loads(metadata_str)
except json.JSONDecodeError:
- logger.warning(f"Invalid JSON in metadata for research {research_id}")
+ logger.warning(
+ f"Invalid JSON in metadata for research {research_id}"
+ )
return jsonify(
{
@@ -142,7 +144,11 @@ def api_terminate_research(research_id):
try:
result = cancel_research(research_id)
return jsonify(
- {"status": "success", "message": "Research terminated", "result": result}
+ {
+ "status": "success",
+ "message": "Research terminated",
+ "result": result,
+ }
)
except Exception as e:
return jsonify({"status": "error", "message": str(e)}), 500
@@ -180,19 +186,25 @@ def api_add_resource(research_id):
# Validate required fields
if not title or not url:
return (
- jsonify({"status": "error", "message": "Title and URL are required"}),
+ jsonify(
+ {"status": "error", "message": "Title and URL are required"}
+ ),
400,
)
# Check if the research exists
conn = get_db_connection()
cursor = conn.cursor()
- cursor.execute("SELECT id FROM research_history WHERE id = ?", (research_id,))
+ cursor.execute(
+ "SELECT id FROM research_history WHERE id = ?", (research_id,)
+ )
result = cursor.fetchone()
conn.close()
if not result:
- return jsonify({"status": "error", "message": "Research not found"}), 404
+ return jsonify(
+ {"status": "error", "message": "Research not found"}
+ ), 404
# Add the resource
resource_id = add_resource(
@@ -229,10 +241,15 @@ def api_delete_resource(research_id, resource_id):
if success:
return jsonify(
- {"status": "success", "message": "Resource deleted successfully"}
+ {
+ "status": "success",
+ "message": "Resource deleted successfully",
+ }
)
else:
- return jsonify({"status": "error", "message": "Resource not found"}), 404
+ return jsonify(
+ {"status": "error", "message": "Resource not found"}
+ ), 404
except Exception as e:
logger.error(f"Error deleting resource: {str(e)}")
return jsonify({"status": "error", "message": str(e)}), 500
@@ -250,7 +267,10 @@ def check_ollama_status():
if provider.lower() != "ollama":
return jsonify(
- {"running": True, "message": f"Using provider: {provider}, not Ollama"}
+ {
+ "running": True,
+ "message": f"Using provider: {provider}, not Ollama",
+ }
)
# Get Ollama API URL from LLM config
@@ -270,7 +290,9 @@ def check_ollama_status():
response = requests.get(f"{ollama_base_url}/api/tags", timeout=5)
# Add response details for debugging
- logger.debug(f"Ollama status check response code: {response.status_code}")
+ logger.debug(
+ f"Ollama status check response code: {response.status_code}"
+ )
if response.status_code == 200:
# Try to validate the response content
@@ -418,7 +440,9 @@ def check_ollama_model():
# Debug log the first bit of the response
response_preview = (
- str(data)[:500] + "..." if len(str(data)) > 500 else str(data)
+ str(data)[:500] + "..."
+ if len(str(data)) > 500
+ else str(data)
)
logger.debug(f"Ollama API response data: {response_preview}")
@@ -446,7 +470,8 @@ def check_ollama_model():
# Case-insensitive model name comparison
model_exists = any(
- m.get("name", "").lower() == model_name.lower() for m in models
+ m.get("name", "").lower() == model_name.lower()
+ for m in models
)
if model_exists:
@@ -559,7 +584,9 @@ def api_get_config():
"search_tool", "auto"
),
"features": {
- "notifications": current_app.config.get("ENABLE_NOTIFICATIONS", False)
+ "notifications": current_app.config.get(
+ "ENABLE_NOTIFICATIONS", False
+ )
},
}
diff --git a/src/local_deep_research/web/routes/benchmark_routes.py b/src/local_deep_research/web/routes/benchmark_routes.py
index 2934fc7537..8c7874dc46 100644
--- a/src/local_deep_research/web/routes/benchmark_routes.py
+++ b/src/local_deep_research/web/routes/benchmark_routes.py
@@ -190,7 +190,10 @@ def get_benchmark_config():
],
"evaluation_models": {
"openai_endpoint": [
- {"id": "anthropic/claude-3.7-sonnet", "name": "Claude 3.7 Sonnet"}
+ {
+ "id": "anthropic/claude-3.7-sonnet",
+ "name": "Claude 3.7 Sonnet",
+ }
],
"openai": [
{"id": "gpt-4o", "name": "GPT-4o"},
diff --git a/src/local_deep_research/web/routes/history_routes.py b/src/local_deep_research/web/routes/history_routes.py
index beb553ffeb..a039aabe12 100644
--- a/src/local_deep_research/web/routes/history_routes.py
+++ b/src/local_deep_research/web/routes/history_routes.py
@@ -44,7 +44,9 @@ def get_history():
cursor = conn.cursor()
# Get all history records ordered by latest first
- cursor.execute("SELECT * FROM research_history ORDER BY created_at DESC")
+ cursor.execute(
+ "SELECT * FROM research_history ORDER BY created_at DESC"
+ )
results = cursor.fetchall()
conn.close()
@@ -155,12 +157,16 @@ def get_research_status(research_id):
column[0]: row[idx] for idx, column in enumerate(cursor.description)
}
cursor = conn.cursor()
- cursor.execute("SELECT * FROM research_history WHERE id = ?", (research_id,))
+ cursor.execute(
+ "SELECT * FROM research_history WHERE id = ?", (research_id,)
+ )
result = cursor.fetchone()
conn.close()
if not result:
- return jsonify({"status": "error", "message": "Research not found"}), 404
+ return jsonify(
+ {"status": "error", "message": "Research not found"}
+ ), 404
globals_dict = get_globals()
active_research = globals_dict["active_research"]
@@ -193,12 +199,16 @@ def get_research_details(research_id):
column[0]: row[idx] for idx, column in enumerate(cursor.description)
}
cursor = conn.cursor()
- cursor.execute("SELECT * FROM research_history WHERE id = ?", (research_id,))
+ cursor.execute(
+ "SELECT * FROM research_history WHERE id = ?", (research_id,)
+ )
result = cursor.fetchone()
conn.close()
if not result:
- return jsonify({"status": "error", "message": "Research not found"}), 404
+ return jsonify(
+ {"status": "error", "message": "Research not found"}
+ ), 404
# Get logs from the dedicated log database
logs = get_logs_for_research(research_id)
@@ -246,7 +256,9 @@ def get_report(research_id):
column[0]: row[idx] for idx, column in enumerate(cursor.description)
}
cursor = conn.cursor()
- cursor.execute("SELECT * FROM research_history WHERE id = ?", (research_id,))
+ cursor.execute(
+ "SELECT * FROM research_history WHERE id = ?", (research_id,)
+ )
result = cursor.fetchone()
conn.close()
@@ -297,7 +309,9 @@ def get_markdown(research_id):
column[0]: row[idx] for idx, column in enumerate(cursor.description)
}
cursor = conn.cursor()
- cursor.execute("SELECT * FROM research_history WHERE id = ?", (research_id,))
+ cursor.execute(
+ "SELECT * FROM research_history WHERE id = ?", (research_id,)
+ )
result = cursor.fetchone()
conn.close()
@@ -324,12 +338,16 @@ def get_research_logs(research_id):
column[0]: row[idx] for idx, column in enumerate(cursor.description)
}
cursor = conn.cursor()
- cursor.execute("SELECT id FROM research_history WHERE id = ?", (research_id,))
+ cursor.execute(
+ "SELECT id FROM research_history WHERE id = ?", (research_id,)
+ )
result = cursor.fetchone()
conn.close()
if not result:
- return jsonify({"status": "error", "message": "Research not found"}), 404
+ return jsonify(
+ {"status": "error", "message": "Research not found"}
+ ), 404
# Retrieve logs from the database
logs = get_logs_for_research(research_id)
diff --git a/src/local_deep_research/web/routes/metrics_routes.py b/src/local_deep_research/web/routes/metrics_routes.py
index 37433a5420..86c9a63a72 100644
--- a/src/local_deep_research/web/routes/metrics_routes.py
+++ b/src/local_deep_research/web/routes/metrics_routes.py
@@ -212,7 +212,9 @@ def api_research_timeline_metrics(research_id):
"""Get timeline metrics for a specific research."""
try:
token_counter = TokenCounter()
- timeline_metrics = token_counter.get_research_timeline_metrics(research_id)
+ timeline_metrics = token_counter.get_research_timeline_metrics(
+ research_id
+ )
return jsonify({"status": "success", "metrics": timeline_metrics})
except Exception as e:
logger.exception(f"Error getting research timeline metrics: {e}")
@@ -303,7 +305,9 @@ def api_get_research_rating(research_id):
db = get_metrics_db()
with db.get_session() as session:
rating = (
- session.query(ResearchRating).filter_by(research_id=research_id).first()
+ session.query(ResearchRating)
+ .filter_by(research_id=research_id)
+ .first()
)
if rating:
@@ -363,7 +367,9 @@ def api_save_research_rating(research_id):
with db.get_session() as session:
# Check if rating already exists
existing_rating = (
- session.query(ResearchRating).filter_by(research_id=research_id).first()
+ session.query(ResearchRating)
+ .filter_by(research_id=research_id)
+ .first()
)
if existing_rating:
@@ -421,7 +427,9 @@ def api_star_reviews():
with get_db_session() as session:
# Build base query with time filter
base_query = session.query(ResearchRating)
- time_condition = get_time_filter_condition(period, ResearchRating.rated_at)
+ time_condition = get_time_filter_condition(
+ period, ResearchRating.rated_at
+ )
if time_condition is not None:
base_query = base_query.filter(time_condition)
@@ -474,9 +482,9 @@ def api_star_reviews():
# Ratings by search engine (join with token_usage to get search engine info)
search_engine_ratings_query = session.query(
- func.coalesce(TokenUsage.search_engine_selected, "Unknown").label(
- "search_engine"
- ),
+ func.coalesce(
+ TokenUsage.search_engine_selected, "Unknown"
+ ).label("search_engine"),
func.avg(ResearchRating.rating).label("avg_rating"),
func.count(ResearchRating.rating).label("rating_count"),
func.sum(case((ResearchRating.rating >= 4, 1), else_=0)).label(
@@ -487,12 +495,14 @@ def api_star_reviews():
)
if time_condition is not None:
- search_engine_ratings_query = search_engine_ratings_query.filter(
- time_condition
+ search_engine_ratings_query = (
+ search_engine_ratings_query.filter(time_condition)
)
search_engine_ratings = (
- search_engine_ratings_query.group_by(TokenUsage.search_engine_selected)
+ search_engine_ratings_query.group_by(
+ TokenUsage.search_engine_selected
+ )
.having(func.count(ResearchRating.rating) > 0)
.order_by(func.avg(ResearchRating.rating).desc())
.all()
@@ -527,12 +537,15 @@ def api_star_reviews():
)
.outerjoin(Research, ResearchRating.research_id == Research.id)
.outerjoin(
- TokenUsage, ResearchRating.research_id == TokenUsage.research_id
+ TokenUsage,
+ ResearchRating.research_id == TokenUsage.research_id,
)
)
if time_condition is not None:
- recent_ratings_query = recent_ratings_query.filter(time_condition)
+ recent_ratings_query = recent_ratings_query.filter(
+ time_condition
+ )
recent_ratings = (
recent_ratings_query.order_by(ResearchRating.rated_at.desc())
@@ -601,9 +614,13 @@ def api_star_reviews():
if rating.query
else f"Research Session #{rating.research_id}"
),
- "mode": rating.mode if rating.mode else "Standard Research",
+ "mode": rating.mode
+ if rating.mode
+ else "Standard Research",
"llm_model": (
- rating.model_name if rating.model_name else "LLM Model"
+ rating.model_name
+ if rating.model_name
+ else "LLM Model"
),
"created_at": (
str(rating.created_at)
@@ -619,7 +636,9 @@ def api_star_reviews():
except Exception:
logger.exception("Error getting star reviews data")
return (
- jsonify({"error": "An internal error occurred. Please try again later."}),
+ jsonify(
+ {"error": "An internal error occurred. Please try again later."}
+ ),
500,
)
@@ -774,7 +793,9 @@ def api_research_costs(research_id):
total_cost = sum(c["total_cost"] for c in costs)
total_prompt_tokens = sum(r["prompt_tokens"] for r in usage_data)
- total_completion_tokens = sum(r["completion_tokens"] for r in usage_data)
+ total_completion_tokens = sum(
+ r["completion_tokens"] for r in usage_data
+ )
cost_summary = {
"total_cost": round(total_cost, 6),
@@ -784,7 +805,11 @@ def api_research_costs(research_id):
}
return jsonify(
- {"status": "success", "research_id": research_id, **cost_summary}
+ {
+ "status": "success",
+ "research_id": research_id,
+ **cost_summary,
+ }
)
except Exception as e:
@@ -802,7 +827,9 @@ def api_cost_analytics():
with get_db_session() as session:
# Get token usage for the period
query = session.query(TokenUsage)
- time_condition = get_time_filter_condition(period, TokenUsage.timestamp)
+ time_condition = get_time_filter_condition(
+ period, TokenUsage.timestamp
+ )
if time_condition is not None:
query = query.filter(time_condition)
@@ -851,7 +878,9 @@ def api_cost_analytics():
total_cost = sum(c["total_cost"] for c in costs)
total_prompt_tokens = sum(r["prompt_tokens"] for r in usage_data)
- total_completion_tokens = sum(r["completion_tokens"] for r in usage_data)
+ total_completion_tokens = sum(
+ r["completion_tokens"] for r in usage_data
+ )
cost_summary = {
"total_cost": round(total_cost, 6),
@@ -879,11 +908,16 @@ def api_cost_analytics():
record["completion_tokens"],
)
research_total += cost_data["total_cost"]
- research_summaries[rid] = {"total_cost": round(research_total, 6)}
+ research_summaries[rid] = {
+ "total_cost": round(research_total, 6)
+ }
# Top expensive research sessions
top_expensive = sorted(
- [(rid, data["total_cost"]) for rid, data in research_summaries.items()],
+ [
+ (rid, data["total_cost"])
+ for rid, data in research_summaries.items()
+ ],
key=lambda x: x[1],
reverse=True,
)[:10]
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index 7068630372..21d83b6590 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -16,7 +16,10 @@ from flask import (
from loguru import logger
from ..models.database import calculate_duration, get_db_connection
-from ..services.research_service import run_research_process, start_research_process
+from ..services.research_service import (
+ run_research_process,
+ start_research_process,
+)
from ..utils.templates import render_template_with_defaults
from .globals import active_research, termination_flags
@@ -164,7 +167,8 @@ def start_research():
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute(
- "SELECT status FROM research_history WHERE id = ?", (research_id,)
+ "SELECT status FROM research_history WHERE id = ?",
+ (research_id,),
)
result = cursor.fetchone()
conn.close()
@@ -263,12 +267,16 @@ def terminate_research(research_id):
# Check if the research exists and is in progress
conn = get_db_connection()
cursor = conn.cursor()
- cursor.execute("SELECT status FROM research_history WHERE id = ?", (research_id,))
+ cursor.execute(
+ "SELECT status FROM research_history WHERE id = ?", (research_id,)
+ )
result = cursor.fetchone()
if not result:
conn.close()
- return jsonify({"status": "error", "message": "Research not found"}), 404
+ return jsonify(
+ {"status": "error", "message": "Research not found"}
+ ), 404
status = result[0]
@@ -276,7 +284,9 @@ def terminate_research(research_id):
if status != "in_progress":
conn.close()
return (
- jsonify({"status": "error", "message": "Research is not in progress"}),
+ jsonify(
+ {"status": "error", "message": "Research is not in progress"}
+ ),
400,
)
@@ -351,7 +361,9 @@ def terminate_research(research_id):
except Exception:
logger.exception("Socket emit error (non-critical)")
- return jsonify({"status": "success", "message": "Research termination requested"})
+ return jsonify(
+ {"status": "success", "message": "Research termination requested"}
+ )
@research_bp.route("/api/delete/<int:research_id>", methods=["DELETE"])
@@ -362,13 +374,16 @@ def delete_research(research_id):
# First check if the research exists and is not in progress
cursor.execute(
- "SELECT status, report_path FROM research_history WHERE id = ?", (research_id,)
+ "SELECT status, report_path FROM research_history WHERE id = ?",
+ (research_id,),
)
result = cursor.fetchone()
if not result:
conn.close()
- return jsonify({"status": "error", "message": "Research not found"}), 404
+ return jsonify(
+ {"status": "error", "message": "Research not found"}
+ ), 404
status, report_path = result
@@ -458,7 +473,9 @@ def open_file_location():
# Check if path exists
if not os.path.exists(file_path):
- return jsonify({"status": "error", "message": "Path does not exist"}), 404
+ return jsonify(
+ {"status": "error", "message": "Path does not exist"}
+ ), 404
try:
if platform.system() == "Windows":
@@ -487,13 +504,17 @@ def save_raw_config():
if not raw_config:
return (
- jsonify({"success": False, "error": "Raw configuration is required"}),
+ jsonify(
+ {"success": False, "error": "Raw configuration is required"}
+ ),
400,
)
try:
# Get the config file path
- config_dir = os.path.join(os.path.expanduser("~"), ".local_deep_research")
+ config_dir = os.path.join(
+ os.path.expanduser("~"), ".local_deep_research"
+ )
os.makedirs(config_dir, exist_ok=True)
config_path = os.path.join(config_dir, "config.toml")
@@ -558,7 +579,9 @@ def get_history():
duration_seconds = None
if completed_at and created_at:
try:
- duration_seconds = calculate_duration(created_at, completed_at)
+ duration_seconds = calculate_duration(
+ created_at, completed_at
+ )
except Exception:
logger.exception("Error calculating duration")
@@ -624,7 +647,9 @@ def get_research_details(research_id):
try:
metadata = json.loads(metadata_str)
except json.JSONDecodeError:
- logger.warning(f"Invalid JSON in metadata for research {research_id}")
+ logger.warning(
+ f"Invalid JSON in metadata for research {research_id}"
+ )
conn.close()
@@ -655,7 +680,9 @@ def get_research_logs(research_id):
cursor = conn.cursor()
# First check if the research exists
- cursor.execute("SELECT id FROM research_history WHERE id = ?", (research_id,))
+ cursor.execute(
+ "SELECT id FROM research_history WHERE id = ?", (research_id,)
+ )
if cursor.fetchone() is None:
conn.close()
return jsonify({"error": "Research not found"}), 404
@@ -742,7 +769,8 @@ def get_research_status(research_id):
"suggestion": "Try again later or use a smaller query scope.",
}
elif (
- "token limit" in error_msg.lower() or "context length" in error_msg.lower()
+ "token limit" in error_msg.lower()
+ or "context length" in error_msg.lower()
):
error_type = "token_limit"
error_info = {
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index c768af67f7..e2e57d2c3b 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -41,7 +41,9 @@ def get_db_session() -> Session:
return current_app.extensions["sqlalchemy"].session()
-def validate_setting(setting: Setting, value: Any) -> Tuple[bool, Optional[str]]:
+def validate_setting(
+ setting: Setting, value: Any
+) -> Tuple[bool, Optional[str]]:
"""
Validate a setting value based on its type and constraints.
@@ -101,7 +103,9 @@ def save_all_settings():
form_data = request.get_json()
if not form_data:
return (
- jsonify({"status": "error", "message": "No settings data provided"}),
+ jsonify(
+ {"status": "error", "message": "No settings data provided"}
+ ),
400,
)
@@ -163,7 +167,8 @@ def save_all_settings():
# Special handling for corrupted or empty values
if value == "[object Object]" or (
- isinstance(value, str) and value.strip() in ["{}", "[]", "{", "["]
+ isinstance(value, str)
+ and value.strip() in ["{}", "[]", "{", "["]
):
if key.startswith("report."):
value = {}
@@ -199,7 +204,9 @@ def save_all_settings():
if current_setting:
# Validate the setting
- is_valid, error_message = validate_setting(current_setting, value)
+ is_valid, error_message = validate_setting(
+ current_setting, value
+ )
if is_valid:
# Save the setting
@@ -210,7 +217,9 @@ def save_all_settings():
# Track settings by type for exporting
if current_setting.type not in settings_by_type:
settings_by_type[current_setting.type] = []
- settings_by_type[current_setting.type].append(current_setting)
+ settings_by_type[current_setting.type].append(
+ current_setting
+ )
else:
# Add to validation errors
validation_errors.append(
@@ -235,7 +244,9 @@ def save_all_settings():
# Determine better UI element based on value type
if isinstance(value, bool):
new_setting["ui_element"] = "checkbox"
- elif isinstance(value, (int, float)) and not isinstance(value, bool):
+ elif isinstance(value, (int, float)) and not isinstance(
+ value, bool
+ ):
new_setting["ui_element"] = "number"
elif isinstance(value, (dict, list)):
new_setting["ui_element"] = "textarea"
@@ -339,10 +350,15 @@ def save_all_settings():
}
)
- except Exception as e:
+ except Exception:
logger.exception("Error saving settings")
return (
- jsonify({"status": "error", "message": f"Error saving settings: {str(e)}"}),
+ jsonify(
+ {
+ "status": "error",
+ "message": "An internal error occurred while saving settings.",
+ }
+ ),
500,
)
@@ -367,7 +383,9 @@ def reset_to_defaults():
# Fallback to predefined settings if file import fails
logger.info("Falling back to predefined settings")
# Import here to avoid circular imports
- from ..database.migrations import setup_predefined_settings as setup_settings
+ from ..database.migrations import (
+ setup_predefined_settings as setup_settings,
+ )
setup_settings(db_session)
@@ -400,7 +418,9 @@ def api_get_all_settings():
filtered_settings = {}
# Need to get all setting details to check category
db_settings = db_session.query(Setting).all()
- category_keys = [s.key for s in db_settings if s.category == category]
+ category_keys = [
+ s.key for s in db_settings if s.category == category
+ ]
# Filter settings by keys
for key, value in settings.items():
@@ -429,7 +449,9 @@ def api_get_setting(key):
return jsonify({"error": f"Setting not found: {key}"}), 404
# Get additional metadata from database.
- db_setting = db_session.query(Setting).filter(Setting.key == key).first()
+ db_setting = (
+ db_session.query(Setting).filter(Setting.key == key).first()
+ )
if db_setting:
# Return full setting details
@@ -477,7 +499,9 @@ def api_update_setting(key):
# get_settings_manager(db_session)
# Check if setting exists
- db_setting = db_session.query(Setting).filter(Setting.key == key).first()
+ db_setting = (
+ db_session.query(Setting).filter(Setting.key == key).first()
+ )
if db_setting:
# Check if setting is editable
@@ -487,9 +511,13 @@ def api_update_setting(key):
# Update setting
success = set_setting(key, value)
if success:
- return jsonify({"message": f"Setting {key} updated successfully"})
+ return jsonify(
+ {"message": f"Setting {key} updated successfully"}
+ )
else:
- return jsonify({"error": f"Failed to update setting {key}"}), 500
+ return jsonify(
+ {"error": f"Failed to update setting {key}"}
+ ), 500
else:
# Create new setting with default metadata
setting_dict = {
@@ -535,7 +563,9 @@ def api_update_setting(key):
201,
)
else:
- return jsonify({"error": f"Failed to create setting {key}"}), 500
+ return jsonify(
+ {"error": f"Failed to create setting {key}"}
+ ), 500
except Exception as e:
logger.exception(f"Error updating setting {key}")
return jsonify({"error": str(e)}), 500
@@ -549,7 +579,9 @@ def api_delete_setting(key):
settings_manager = get_settings_manager(db_session)
# Check if setting exists
- db_setting = db_session.query(Setting).filter(Setting.key == key).first()
+ db_setting = (
+ db_session.query(Setting).filter(Setting.key == key).first()
+ )
if not db_setting:
return jsonify({"error": f"Setting not found: {key}"}), 404
@@ -672,7 +704,9 @@ def api_get_available_models():
else "http://localhost:11434"
)
- ollama_response = requests.get(f"{base_url}/api/tags", timeout=5)
+ ollama_response = requests.get(
+ f"{base_url}/api/tags", timeout=5
+ )
logger.debug(
f"Ollama API response: Status {ollama_response.status_code}"
@@ -680,7 +714,9 @@ def api_get_available_models():
# Try to parse the response even if status code is not 200 to help with debugging
response_text = ollama_response.text
- logger.debug(f"Ollama API raw response: {response_text[:500]}...")
+ logger.debug(
+ f"Ollama API raw response: {response_text[:500]}..."
+ )
if ollama_response.status_code == 200:
try:
@@ -699,7 +735,9 @@ def api_get_available_models():
name = model.get("name", "")
if name:
# Improved display name formatting
- display_name = re.sub(r"[:/]", " ", name).strip()
+ display_name = re.sub(
+ r"[:/]", " ", name
+ ).strip()
display_name = " ".join(
word.capitalize()
for word in display_name.split()
@@ -724,7 +762,9 @@ def api_get_available_models():
name = model.get("name", "")
if name:
# Improved display name formatting
- display_name = re.sub(r"[:/]", " ", name).strip()
+ display_name = re.sub(
+ r"[:/]", " ", name
+ ).strip()
display_name = " ".join(
word.capitalize()
for word in display_name.split()
@@ -747,7 +787,9 @@ def api_get_available_models():
logger.error(
f"Failed to parse Ollama API response as JSON: {json_err}"
)
- raise Exception(f"Ollama API returned invalid JSON: {json_err}")
+ raise Exception(
+ f"Ollama API returned invalid JSON: {json_err}"
+ )
else:
logger.warning(
f"Ollama API returned non-200 status code: {ollama_response.status_code}"
@@ -759,7 +801,9 @@ def api_get_available_models():
except requests.exceptions.RequestException as e:
logger.warning(f"Could not connect to Ollama API: {str(e)}")
# Fallback to default models if Ollama is not running
- logger.info("Using fallback Ollama models due to connection error")
+ logger.info(
+ "Using fallback Ollama models due to connection error"
+ )
ollama_models = [
{
"value": "llama3",
@@ -792,8 +836,16 @@ def api_get_available_models():
# Use fallback models
logger.info("Using fallback Ollama models due to error")
providers["ollama_models"] = [
- {"value": "llama3", "label": "Llama 3 (Ollama)", "provider": "OLLAMA"},
- {"value": "mistral", "label": "Mistral (Ollama)", "provider": "OLLAMA"},
+ {
+ "value": "llama3",
+ "label": "Llama 3 (Ollama)",
+ "provider": "OLLAMA",
+ },
+ {
+ "value": "mistral",
+ "label": "Mistral (Ollama)",
+ "provider": "OLLAMA",
+ },
{
"value": "gemma:latest",
"label": "Gemma (Ollama)",
@@ -832,7 +884,8 @@ def api_get_available_models():
# Create a clean display name
display_name = model_id.replace("-", " ").strip()
display_name = " ".join(
- word.capitalize() for word in display_name.split()
+ word.capitalize()
+ for word in display_name.split()
)
openai_endpoint_models.append(
@@ -882,7 +935,9 @@ def api_get_available_models():
model_id = model.get("id", "")
if model_id:
# Create a clean display name
- display_name = model_id.replace("-", " ").strip()
+ display_name = model_id.replace(
+ "-", " "
+ ).strip()
display_name = " ".join(
word.capitalize()
for word in display_name.split()
@@ -901,7 +956,9 @@ def api_get_available_models():
except Exception as e:
logger.error(f"Error getting OpenAI Endpoint models: {str(e)}")
# Use fallback models (empty in this case)
- logger.info("Using fallback (empty) OpenAI Endpoint models due to error")
+ logger.info(
+ "Using fallback (empty) OpenAI Endpoint models due to error"
+ )
# Always set the openai_endpoint_models in providers
providers["openai_endpoint_models"] = openai_endpoint_models
@@ -912,7 +969,9 @@ def api_get_available_models():
# Get OpenAI models using the OpenAI package
openai_models = []
try:
- logger.info("Attempting to connect to OpenAI API using OpenAI package")
+ logger.info(
+ "Attempting to connect to OpenAI API using OpenAI package"
+ )
# Get the API key from settings
api_key = get_db_setting("llm.openai.api_key", "")
@@ -937,7 +996,8 @@ def api_get_available_models():
# Create a clean display name
display_name = model_id.replace("-", " ").strip()
display_name = " ".join(
- word.capitalize() for word in display_name.split()
+ word.capitalize()
+ for word in display_name.split()
)
openai_models.append(
@@ -959,7 +1019,9 @@ def api_get_available_models():
logger.info("No OpenAI models found due to API error")
else:
- logger.info("OpenAI API key not configured, no models available")
+ logger.info(
+ "OpenAI API key not configured, no models available"
+ )
except ImportError:
logger.warning("OpenAI package not installed. No models available.")
@@ -1000,7 +1062,8 @@ def api_get_available_models():
# Create a clean display name
display_name = model_id.replace("-", " ").strip()
display_name = " ".join(
- word.capitalize() for word in display_name.split()
+ word.capitalize()
+ for word in display_name.split()
)
anthropic_models.append(
@@ -1034,7 +1097,9 @@ def api_get_available_models():
logger.info(f"Final Anthropic models count: {len(anthropic_models)}")
# Return all options
- return jsonify({"provider_options": provider_options, "providers": providers})
+ return jsonify(
+ {"provider_options": provider_options, "providers": providers}
+ )
except Exception as e:
logger.exception("Error getting available models")
@@ -1067,7 +1132,10 @@ def api_get_available_search_engines():
description = (
db_session.query(Setting)
- .filter(Setting.key == f"search.engine.web.{engine_name}.description")
+ .filter(
+ Setting.key
+ == f"search.engine.web.{engine_name}.description"
+ )
.first()
)
if description is None:
@@ -1077,7 +1145,9 @@ def api_get_available_search_engines():
strengths = (
db_session.query(Setting)
- .filter(Setting.key == f"search.engine.web.{engine_name}.strengths")
+ .filter(
+ Setting.key == f"search.engine.web.{engine_name}.strengths"
+ )
.first()
)
if strengths is None:
@@ -1087,7 +1157,9 @@ def api_get_available_search_engines():
strengths = strengths.value
engines_dict[engine_name] = dict(
- display_name=display_name, strengths=strengths, description=description
+ display_name=display_name,
+ strengths=strengths,
+ description=description,
)
# Format as options for dropdown
@@ -1099,7 +1171,9 @@ def api_get_available_search_engines():
for key in engines_dict.keys()
]
- return jsonify({"engines": engines_dict, "engine_options": engine_options})
+ return jsonify(
+ {"engines": engines_dict, "engine_options": engine_options}
+ )
except Exception as e:
logger.exception("Error getting available search engines")
@@ -1214,12 +1288,16 @@ def fix_corrupted_settings():
"app.knowledge_accumulation_context_limit",
"app.output_dir",
]:
- setting = db_session.query(Setting).filter(Setting.key == key).first()
+ setting = (
+ db_session.query(Setting).filter(Setting.key == key).first()
+ )
if setting:
# Move to proper category if not already there
proper_key = key.replace("app.", "report.")
existing_proper = (
- db_session.query(Setting).filter(Setting.key == proper_key).first()
+ db_session.query(Setting)
+ .filter(Setting.key == proper_key)
+ .first()
)
if not existing_proper:
@@ -1260,12 +1338,16 @@ def fix_corrupted_settings():
"app.search_language",
"app.snippets_only",
]:
- setting = db_session.query(Setting).filter(Setting.key == key).first()
+ setting = (
+ db_session.query(Setting).filter(Setting.key == key).first()
+ )
if setting:
# Move to proper category if not already there
proper_key = key.replace("app.", "search.")
existing_proper = (
- db_session.query(Setting).filter(Setting.key == proper_key).first()
+ db_session.query(Setting)
+ .filter(Setting.key == proper_key)
+ .first()
)
if not existing_proper:
@@ -1305,12 +1387,16 @@ def fix_corrupted_settings():
"app.lmstudio_url",
"app.llamacpp_model_path",
]:
- setting = db_session.query(Setting).filter(Setting.key == key).first()
+ setting = (
+ db_session.query(Setting).filter(Setting.key == key).first()
+ )
if setting:
# Move to proper category if not already there
proper_key = key.replace("app.", "llm.")
existing_proper = (
- db_session.query(Setting).filter(Setting.key == proper_key).first()
+ db_session.query(Setting)
+ .filter(Setting.key == proper_key)
+ .first()
)
if not existing_proper:
@@ -1406,7 +1492,10 @@ def fix_corrupted_settings():
elif setting.key == "report.detailed_citations":
default_value = True
elif setting.key.startswith("app."):
- if setting.key == "app.theme" or setting.key == "app.default_theme":
+ if (
+ setting.key == "app.theme"
+ or setting.key == "app.default_theme"
+ ):
default_value = "dark"
elif setting.key == "app.enable_notifications":
default_value = True
@@ -1475,16 +1564,23 @@ def check_ollama_status():
"""Check if Ollama is running and available"""
try:
# Get Ollama URL from settings
- raw_base_url = get_db_setting("llm.ollama.url", "http://localhost:11434")
+ raw_base_url = get_db_setting(
+ "llm.ollama.url", "http://localhost:11434"
+ )
base_url = (
- normalize_url(raw_base_url) if raw_base_url else "http://localhost:11434"
+ normalize_url(raw_base_url)
+ if raw_base_url
+ else "http://localhost:11434"
)
response = requests.get(f"{base_url}/api/version", timeout=2.0)
if response.status_code == 200:
return jsonify(
- {"running": True, "version": response.json().get("version", "unknown")}
+ {
+ "running": True,
+ "version": response.json().get("version", "unknown"),
+ }
)
else:
return jsonify(
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 9c5ceab98a..4cc0cee6b9 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -113,8 +113,12 @@ def run_research_process(
try:
# Check if this research has been terminated before we even start
if research_id in termination_flags and termination_flags[research_id]:
- logger.info(f"Research {research_id} was terminated before starting")
- cleanup_research_resources(research_id, active_research, termination_flags)
+ logger.info(
+ f"Research {research_id} was terminated before starting"
+ )
+ cleanup_research_resources(
+ research_id, active_research, termination_flags
+ )
return
logger.info(
@@ -130,7 +134,9 @@ def run_research_process(
time_period = kwargs.get("time_period")
iterations = kwargs.get("iterations")
questions_per_iteration = kwargs.get("questions_per_iteration")
- strategy = kwargs.get("strategy", "source-based") # Default to source-based
+ strategy = kwargs.get(
+ "strategy", "source-based"
+ ) # Default to source-based
# Log all parameters for debugging
logger.info(
@@ -169,8 +175,13 @@ def run_research_process(
# Set up progress callback
def progress_callback(message, progress_percent, metadata):
# Frequent termination check
- if research_id in termination_flags and termination_flags[research_id]:
- handle_termination(research_id, active_research, termination_flags)
+ if (
+ research_id in termination_flags
+ and termination_flags[research_id]
+ ):
+ handle_termination(
+ research_id, active_research, termination_flags
+ )
raise Exception("Research was terminated by user")
logger.log("milestone", message)
@@ -197,19 +208,29 @@ def run_research_process(
# Update search iteration if available
if "iteration" in metadata:
- shared_research_context["search_iteration"] = metadata["iteration"]
+ shared_research_context["search_iteration"] = metadata[
+ "iteration"
+ ]
# Adjust progress based on research mode
adjusted_progress = progress_percent
- if mode == "detailed" and metadata.get("phase") == "output_generation":
+ if (
+ mode == "detailed"
+ and metadata.get("phase") == "output_generation"
+ ):
# For detailed mode, adjust the progress range for output generation
adjusted_progress = min(80, progress_percent)
- elif mode == "detailed" and metadata.get("phase") == "report_generation":
+ elif (
+ mode == "detailed"
+ and metadata.get("phase") == "report_generation"
+ ):
# Scale the progress from 80% to 95% for the report generation phase
if progress_percent is not None:
normalized = progress_percent / 100
adjusted_progress = 80 + (normalized * 15)
- elif mode == "quick" and metadata.get("phase") == "output_generation":
+ elif (
+ mode == "quick" and metadata.get("phase") == "output_generation"
+ ):
# For quick mode, ensure we're at least at 85% during output generation
adjusted_progress = max(85, progress_percent)
# Map any further progress within output_generation to 85-95% range
@@ -219,7 +240,9 @@ def run_research_process(
# Don't let progress go backwards
if research_id in active_research and adjusted_progress is not None:
- current_progress = active_research[research_id].get("progress", 0)
+ current_progress = active_research[research_id].get(
+ "progress", 0
+ )
adjusted_progress = max(current_progress, adjusted_progress)
# Update active research record
@@ -272,8 +295,13 @@ def run_research_process(
# Function to check termination during long-running operations
def check_termination():
- if research_id in termination_flags and termination_flags[research_id]:
- handle_termination(research_id, active_research, termination_flags)
+ if (
+ research_id in termination_flags
+ and termination_flags[research_id]
+ ):
+ handle_termination(
+ research_id, active_research, termination_flags
+ )
raise Exception(
"Research was terminated by user during long-running operation"
)
@@ -330,16 +358,22 @@ def run_research_process(
if iterations:
system.max_iterations = int(iterations)
if questions_per_iteration:
- system.questions_per_iteration = int(questions_per_iteration)
+ system.questions_per_iteration = int(
+ questions_per_iteration
+ )
# Create a new search object with these settings
system.search = get_search(
search_tool=search_engine, llm_instance=system.model
)
- logger.info("Successfully set search engine to: %s", search_engine)
+ logger.info(
+ "Successfully set search engine to: %s", search_engine
+ )
except Exception:
- logger.exception("Error setting search engine to %s", search_engine)
+ logger.exception(
+ "Error setting search engine to %s", search_engine
+ )
# Run the search
progress_callback("Starting research process", 5, {"phase": "init"})
@@ -406,21 +440,32 @@ def run_research_process(
):
error_type = "token_limit"
# Log specific error type
- logger.warning("Detected token limit error in synthesis")
+ logger.warning(
+ "Detected token limit error in synthesis"
+ )
# Update progress with specific error type
progress_callback(
"Synthesis hit token limits. Attempting fallback...",
87,
- {"phase": "synthesis_error", "error_type": error_type},
+ {
+ "phase": "synthesis_error",
+ "error_type": error_type,
+ },
)
- elif "timeout" in error_message or "timed out" in error_message:
+ elif (
+ "timeout" in error_message
+ or "timed out" in error_message
+ ):
error_type = "timeout"
logger.warning("Detected timeout error in synthesis")
progress_callback(
"Synthesis timed out. Attempting fallback...",
87,
- {"phase": "synthesis_error", "error_type": error_type},
+ {
+ "phase": "synthesis_error",
+ "error_type": error_type,
+ },
)
elif "rate limit" in error_message:
error_type = "rate_limit"
@@ -428,26 +473,40 @@ def run_research_process(
progress_callback(
"LLM rate limit reached. Attempting fallback...",
87,
- {"phase": "synthesis_error", "error_type": error_type},
+ {
+ "phase": "synthesis_error",
+ "error_type": error_type,
+ },
)
- elif "connection" in error_message or "network" in error_message:
+ elif (
+ "connection" in error_message
+ or "network" in error_message
+ ):
error_type = "connection"
logger.warning("Detected connection error in synthesis")
progress_callback(
"Connection issue with LLM. Attempting fallback...",
87,
- {"phase": "synthesis_error", "error_type": error_type},
+ {
+ "phase": "synthesis_error",
+ "error_type": error_type,
+ },
)
elif (
"llm error" in error_message
or "final answer synthesis fail" in error_message
):
error_type = "llm_error"
- logger.warning("Detected general LLM error in synthesis")
+ logger.warning(
+ "Detected general LLM error in synthesis"
+ )
progress_callback(
"LLM error during synthesis. Attempting fallback...",
87,
- {"phase": "synthesis_error", "error_type": error_type},
+ {
+ "phase": "synthesis_error",
+ "error_type": error_type,
+ },
)
else:
# Generic error
@@ -455,7 +514,10 @@ def run_research_process(
progress_callback(
"Error during synthesis. Attempting fallback...",
87,
- {"phase": "synthesis_error", "error_type": "unknown"},
+ {
+ "phase": "synthesis_error",
+ "error_type": "unknown",
+ },
)
# Extract synthesized content from findings if available
@@ -466,11 +528,13 @@ def run_research_process(
break
# Use synthesized content as fallback
- if synthesized_content and not synthesized_content.startswith(
- "Error:"
+ if (
+ synthesized_content
+ and not synthesized_content.startswith("Error:")
):
-
- logger.info("Using existing synthesized content as fallback")
+ logger.info(
+ "Using existing synthesized content as fallback"
+ )
raw_formatted_findings = synthesized_content
# Or use current_knowledge as another fallback
@@ -486,17 +550,19 @@ def run_research_process(
f"## {finding.get('phase', 'Finding')}\n\n{finding.get('content', '')}"
for finding in results.get("findings", [])
if finding.get("content")
- and not finding.get("content", "").startswith("Error:")
+ and not finding.get("content", "").startswith(
+ "Error:"
+ )
]
if valid_findings:
raw_formatted_findings = (
"# Research Results (Fallback Mode)\n\n"
)
- raw_formatted_findings += "\n\n".join(valid_findings)
- raw_formatted_findings += (
- f"\n\n## Error Information\n{raw_formatted_findings}"
+ raw_formatted_findings += "\n\n".join(
+ valid_findings
)
+ raw_formatted_findings += f"\n\n## Error Information\n{raw_formatted_findings}"
else:
# Last resort: use everything including errors
raw_formatted_findings = (
@@ -512,7 +578,10 @@ def run_research_process(
progress_callback(
f"Using fallback synthesis due to {error_type} error",
88,
- {"phase": "synthesis_fallback", "error_type": error_type},
+ {
+ "phase": "synthesis_fallback",
+ "error_type": error_type,
+ },
)
logger.info(
@@ -569,8 +638,12 @@ def run_research_process(
f.write(f"Query: {query}\n\n")
f.write(clean_markdown)
f.write("\n\n## Research Metrics\n")
- f.write(f"- Search Iterations: {results['iterations']}\n")
- f.write(f"- Generated at: {datetime.utcnow().isoformat()}\n")
+ f.write(
+ f"- Search Iterations: {results['iterations']}\n"
+ )
+ f.write(
+ f"- Generated at: {datetime.utcnow().isoformat()}\n"
+ )
# Update database
metadata = {
@@ -582,7 +655,9 @@ def run_research_process(
now = datetime.utcnow()
completed_at = now.isoformat()
- logger.info("Updating database for research_id: %s", research_id)
+ logger.info(
+ "Updating database for research_id: %s", research_id
+ )
# Get the start time from the database
conn = get_db_connection()
cursor = conn.cursor()
@@ -627,11 +702,15 @@ def run_research_process(
cleanup_research_resources(
research_id, active_research, termination_flags
)
- logger.info("Resources cleaned up for research_id: %s", research_id)
+ logger.info(
+ "Resources cleaned up for research_id: %s", research_id
+ )
except Exception as inner_e:
logger.exception("Error during quick summary generation")
- raise Exception(f"Error generating quick summary: {str(inner_e)}")
+ raise Exception(
+ f"Error generating quick summary: {str(inner_e)}"
+ )
else:
raise Exception(
"No research findings were generated. Please try again."
@@ -639,14 +718,18 @@ def run_research_process(
else:
# Full Report
progress_callback(
- "Generating detailed report...", 85, {"phase": "report_generation"}
+ "Generating detailed report...",
+ 85,
+ {"phase": "report_generation"},
)
# Extract the search system from the results if available
search_system = results.get("search_system", None)
# Pass the existing search system to maintain citation indices
- report_generator = IntegratedReportGenerator(search_system=search_system)
+ report_generator = IntegratedReportGenerator(
+ search_system=search_system
+ )
final_report = report_generator.generate_report(results, query)
progress_callback(
@@ -673,7 +756,8 @@ def run_research_process(
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute(
- "SELECT created_at FROM research_history WHERE id = ?", (research_id,)
+ "SELECT created_at FROM research_history WHERE id = ?",
+ (research_id,),
)
result = cursor.fetchone()
@@ -701,7 +785,9 @@ def run_research_process(
)
# Clean up resources
- cleanup_research_resources(research_id, active_research, termination_flags)
+ cleanup_research_resources(
+ research_id, active_research, termination_flags
+ )
except Exception as e:
# Handle error
@@ -719,9 +805,7 @@ def run_research_process(
"solution": "Start Ollama with 'ollama serve' or check if it's installed correctly."
}
elif "Error type: model_not_found" in user_friendly_error:
- user_friendly_error = (
- "Required Ollama model not found. Please pull the model first."
- )
+ user_friendly_error = "Required Ollama model not found. Please pull the model first."
error_context = {
"solution": "Run 'ollama pull mistral' to download the required model."
}
@@ -732,7 +816,9 @@ def run_research_process(
}
elif "Error type: api_error" in user_friendly_error:
# Keep the original error message as it's already improved
- error_context = {"solution": "Check API configuration and credentials."}
+ error_context = {
+ "solution": "Check API configuration and credentials."
+ }
# Update metadata with more context about the error
metadata = {"phase": "error", "error": user_friendly_error}
@@ -749,7 +835,10 @@ def run_research_process(
# If termination was requested, mark as suspended instead of failed
status = (
"suspended"
- if (research_id in termination_flags and termination_flags[research_id])
+ if (
+ research_id in termination_flags
+ and termination_flags[research_id]
+ )
else "failed"
)
message = (
@@ -765,7 +854,8 @@ def run_research_process(
# Get the start time from the database
duration_seconds = None
cursor.execute(
- "SELECT created_at FROM research_history WHERE id = ?", (research_id,)
+ "SELECT created_at FROM research_history WHERE id = ?",
+ (research_id,),
)
result = cursor.fetchone()
@@ -799,7 +889,9 @@ def run_research_process(
logger.exception("Error in error handler")
# Clean up resources
- cleanup_research_resources(research_id, active_research, termination_flags)
+ cleanup_research_resources(
+ research_id, active_research, termination_flags
+ )
def cleanup_research_resources(research_id, active_research, termination_flags):
@@ -845,7 +937,10 @@ def cleanup_research_resources(research_id, active_research, termination_flags):
socket_subscriptions = globals_dict.get("socket_subscriptions", {})
# Send a final message to any remaining subscribers with explicit status
- if research_id in socket_subscriptions and socket_subscriptions[research_id]:
+ if (
+ research_id in socket_subscriptions
+ and socket_subscriptions[research_id]
+ ):
# Use the proper status message based on database status
if current_status == "suspended" or current_status == "failed":
final_message = {
@@ -899,7 +994,9 @@ def handle_termination(research_id, active_research, termination_flags):
result = cursor.fetchone()
# Calculate the duration
- duration_seconds = calculate_duration(result[0]) if result and result[0] else None
+ duration_seconds = (
+ calculate_duration(result[0]) if result and result[0] else None
+ )
# Update the database with suspended status
cursor.execute(
diff --git a/src/local_deep_research/web/services/resource_service.py b/src/local_deep_research/web/services/resource_service.py
index 91a9b9073c..72bb849c88 100644
--- a/src/local_deep_research/web/services/resource_service.py
+++ b/src/local_deep_research/web/services/resource_service.py
@@ -30,9 +30,15 @@ def get_resources_for_research(research_id):
resources = []
for row in cursor.fetchall():
- id, research_id, title, url, content_preview, source_type, metadata_str = (
- row
- )
+ (
+ id,
+ research_id,
+ title,
+ url,
+ content_preview,
+ source_type,
+ metadata_str,
+ ) = row
# Parse metadata if available
metadata = {}
@@ -40,7 +46,9 @@ def get_resources_for_research(research_id):
try:
metadata = json.loads(metadata_str)
except json.JSONDecodeError:
- logger.warning(f"Invalid JSON in metadata for resource {id}")
+ logger.warning(
+ f"Invalid JSON in metadata for resource {id}"
+ )
resources.append(
{
@@ -58,12 +66,19 @@ def get_resources_for_research(research_id):
return resources
except Exception as e:
- logger.error(f"Error retrieving resources for research {research_id}: {str(e)}")
+ logger.error(
+ f"Error retrieving resources for research {research_id}: {str(e)}"
+ )
raise
def add_resource(
- research_id, title, url, content_preview=None, source_type="web", metadata=None
+ research_id,
+ title,
+ url,
+ content_preview=None,
+ source_type="web",
+ metadata=None,
):
"""
Add a new resource to the research_resources table
@@ -104,11 +119,15 @@ def add_resource(
conn.commit()
conn.close()
- logger.info(f"Added resource {resource_id} for research {research_id}: {title}")
+ logger.info(
+ f"Added resource {resource_id} for research {research_id}: {title}"
+ )
return resource_id
except Exception as e:
- logger.error(f"Error adding resource for research {research_id}: {str(e)}")
+ logger.error(
+ f"Error adding resource for research {research_id}: {str(e)}"
+ )
raise
@@ -127,7 +146,9 @@ def delete_resource(resource_id):
cursor = conn.cursor()
# First check if the resource exists
- cursor.execute("SELECT id FROM research_resources WHERE id = ?", (resource_id,))
+ cursor.execute(
+ "SELECT id FROM research_resources WHERE id = ?", (resource_id,)
+ )
result = cursor.fetchone()
if not result:
@@ -135,13 +156,17 @@ def delete_resource(resource_id):
return False
# Delete the resource
- cursor.execute("DELETE FROM research_resources WHERE id = ?", (resource_id,))
+ cursor.execute(
+ "DELETE FROM research_resources WHERE id = ?", (resource_id,)
+ )
rows_affected = cursor.rowcount
conn.commit()
conn.close()
- logger.info(f"Deleted resource {resource_id}, {rows_affected} rows affected")
+ logger.info(
+ f"Deleted resource {resource_id}, {rows_affected} rows affected"
+ )
return rows_affected > 0
except Exception as e:
diff --git a/src/local_deep_research/web/services/settings_manager.py b/src/local_deep_research/web/services/settings_manager.py
index c2f0c5c8d0..2625576cff 100644
--- a/src/local_deep_research/web/services/settings_manager.py
+++ b/src/local_deep_research/web/services/settings_manager.py
@@ -67,11 +67,16 @@ class SettingsManager:
self.db_first = True # Always prioritize DB settings
# Load default settings.
- default_settings = pkg_resources.read_text(defaults, "default_settings.json")
+ default_settings = pkg_resources.read_text(
+ defaults, "default_settings.json"
+ )
self.default_settings = json.loads(default_settings)
def __get_typed_setting_value(
- self, setting: Type[Setting], default: Any = None, check_env: bool = True
+ self,
+ setting: Type[Setting],
+ default: Any = None,
+ check_env: bool = True,
) -> Any:
"""
Extracts the value for a particular setting, ensuring that it has the
@@ -88,7 +93,9 @@ class SettingsManager:
The value of the setting.
"""
- setting_type = self._UI_ELEMENT_TO_SETTING_TYPE.get(setting.ui_element, None)
+ setting_type = self._UI_ELEMENT_TO_SETTING_TYPE.get(
+ setting.ui_element, None
+ )
if setting_type is None:
logger.warning(
"Got unknown type {} for setting {}, returning default value.",
@@ -121,7 +128,9 @@ class SettingsManager:
)
return default
- def get_setting(self, key: str, default: Any = None, check_env: bool = True) -> Any:
+ def get_setting(
+ self, key: str, default: Any = None, check_env: bool = True
+ ) -> Any:
"""
Get a setting value
@@ -141,8 +150,12 @@ class SettingsManager:
self.db_session.query(Setting)
# This will find exact matches and any subkeys.
.filter(
- or_(Setting.key == key, Setting.key.startswith(f"{key}."))
- ).all()
+ or_(
+ Setting.key == key,
+ Setting.key.startswith(f"{key}."),
+ )
+ )
+ .all()
)
if len(settings) == 1:
# This is a bottom-level key.
@@ -154,12 +167,16 @@ class SettingsManager:
settings_map = {}
for setting in settings:
output_key = setting.key.removeprefix(f"{key}.")
- settings_map[output_key] = self.__get_typed_setting_value(
- setting, default, check_env
+ settings_map[output_key] = (
+ self.__get_typed_setting_value(
+ setting, default, check_env
+ )
)
return settings_map
except SQLAlchemyError as e:
- logger.error(f"Error retrieving setting {key} from database: {e}")
+ logger.error(
+ f"Error retrieving setting {key} from database: {e}"
+ )
# Return default if not found
return default
@@ -180,7 +197,9 @@ class SettingsManager:
if self.db_session:
try:
setting = (
- self.db_session.query(Setting).filter(Setting.key == key).first()
+ self.db_session.query(Setting)
+ .filter(Setting.key == key)
+ .first()
)
if setting:
setting.value = value
@@ -257,7 +276,9 @@ class SettingsManager:
# variable is set.
result[setting.key]["editable"] = False
except SQLAlchemyError as e:
- logger.error(f"Error retrieving all settings from database: {e}")
+ logger.error(
+ f"Error retrieving all settings from database: {e}"
+ )
return result
@@ -348,7 +369,9 @@ class SettingsManager:
return db_setting
except SQLAlchemyError as e:
- logger.error(f"Error creating/updating setting {setting_obj.key}: {e}")
+ logger.error(
+ f"Error creating/updating setting {setting_obj.key}: {e}"
+ )
self.db_session.rollback()
return None
@@ -364,12 +387,18 @@ class SettingsManager:
True if successful, False otherwise
"""
if not self.db_session:
- logger.warning("No database session available, cannot delete setting")
+ logger.warning(
+ "No database session available, cannot delete setting"
+ )
return False
try:
# Remove from database
- result = self.db_session.query(Setting).filter(Setting.key == key).delete()
+ result = (
+ self.db_session.query(Setting)
+ .filter(Setting.key == key)
+ .delete()
+ )
if commit:
self.db_session.commit()
@@ -380,7 +409,9 @@ class SettingsManager:
self.db_session.rollback()
return False
- def load_from_defaults_file(self, commit: bool = True, **kwargs: Any) -> None:
+ def load_from_defaults_file(
+ self, commit: bool = True, **kwargs: Any
+ ) -> None:
"""
Import settings from the defaults settings file.
@@ -428,7 +459,9 @@ class SettingsManager:
self.db_session.commit()
@classmethod
- def get_instance(cls, db_session: Optional[Session] = None) -> "SettingsManager":
+ def get_instance(
+ cls, db_session: Optional[Session] = None
+ ) -> "SettingsManager":
"""
Get a singleton instance of the settings manager
@@ -503,7 +536,12 @@ class SettingsManager:
elif key.startswith("llm."):
if any(
param in key
- for param in ["temperature", "max_tokens", "n_batch", "n_gpu_layers"]
+ for param in [
+ "temperature",
+ "max_tokens",
+ "n_batch",
+ "n_gpu_layers",
+ ]
):
category = "llm_parameters"
else:
diff --git a/src/local_deep_research/web/services/settings_service.py b/src/local_deep_research/web/services/settings_service.py
index c95e7496d3..9853e75ce5 100644
--- a/src/local_deep_research/web/services/settings_service.py
+++ b/src/local_deep_research/web/services/settings_service.py
@@ -35,7 +35,9 @@ def get_setting(key: str, default: Any = None, db_session=None) -> Any:
return manager.get_setting(key, default)
-def set_setting(key: str, value: Any, commit: bool = True, db_session=None) -> bool:
+def set_setting(
+ key: str, value: Any, commit: bool = True, db_session=None
+) -> bool:
"""
Set a setting value
@@ -67,7 +69,9 @@ def get_all_settings(db_session=None) -> Dict[str, Any]:
def create_or_update_setting(
- setting: Union[Dict[str, Any], Setting], commit: bool = True, db_session=None
+ setting: Union[Dict[str, Any], Setting],
+ commit: bool = True,
+ db_session=None,
) -> Optional[Setting]:
"""
Create or update a setting
@@ -116,7 +120,9 @@ def bulk_update_settings(
return success
-def validate_setting(setting: Setting, value: Any) -> tuple[bool, Optional[str]]:
+def validate_setting(
+ setting: Setting, value: Any
+) -> tuple[bool, Optional[str]]:
"""
Validate a setting value based on its type and constraints
@@ -127,6 +133,8 @@ def validate_setting(setting: Setting, value: Any) -> tuple[bool, Optional[str]]
Returns:
tuple[bool, Optional[str]]: (is_valid, error_message)
"""
- from ..routes.settings_routes import validate_setting as routes_validate_setting
+ from ..routes.settings_routes import (
+ validate_setting as routes_validate_setting,
+ )
return routes_validate_setting(setting, value)
diff --git a/src/local_deep_research/web/services/socket_service.py b/src/local_deep_research/web/services/socket_service.py
index 6c73260b91..6dc9558fe2 100644
--- a/src/local_deep_research/web/services/socket_service.py
+++ b/src/local_deep_research/web/services/socket_service.py
@@ -31,7 +31,9 @@ class SocketIOService:
raise ValueError(
"Flask app must be specified to create a SocketIOService instance."
)
- cls._instance = super(SocketIOService, cls).__new__(cls, *args, **kwargs)
+ cls._instance = super(SocketIOService, cls).__new__(
+ cls, *args, **kwargs
+ )
cls._instance.__init_singleton(app)
return cls._instance
@@ -159,7 +161,9 @@ class SocketIOService:
try:
self.__socketio.emit(full_event, data, room=sid)
except Exception:
- self.__log_exception(f"Error emitting to subscriber {sid}")
+ self.__log_exception(
+ f"Error emitting to subscriber {sid}"
+ )
return True
except Exception:
@@ -177,7 +181,9 @@ class SocketIOService:
def __handle_disconnect(self, request, reason: str):
"""Handle client disconnection"""
try:
- self.__log_info(f"Client {request.sid} disconnected because:" f" {reason}")
+ self.__log_info(
+ f"Client {request.sid} disconnected because: {reason}"
+ )
# Clean up subscriptions for this client
with self.__lock:
if request.sid in self.__socket_subscriptions:
@@ -194,7 +200,8 @@ class SocketIOService:
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute(
- "SELECT status FROM research_history WHERE id = ?", (research_id,)
+ "SELECT status FROM research_history WHERE id = ?",
+ (research_id,),
)
result = cursor.fetchone()
conn.close()
@@ -209,7 +216,9 @@ class SocketIOService:
self.__socket_subscriptions[research_id] = set()
# Add this client to the subscribers
- self.__socket_subscriptions[research_id].add(request.sid)
+ self.__socket_subscriptions[research_id].add(
+ request.sid
+ )
self.__log_info(
f"Client {request.sid} subscribed to research {research_id}"
)
@@ -228,7 +237,9 @@ class SocketIOService:
f"research_progress_{research_id}",
{
"progress": progress,
- "message": latest_log.get("message", "Processing..."),
+ "message": latest_log.get(
+ "message", "Processing..."
+ ),
"status": "in_progress",
"log_entry": latest_log,
},
@@ -256,7 +267,9 @@ class SocketIOService:
"progress": 100 if status == "completed" else 0,
"metadata": {
"phase": (
- "complete" if status == "completed" else "error"
+ "complete"
+ if status == "completed"
+ else "error"
)
},
},
diff --git a/src/local_deep_research/web/static/css/custom_dropdown.css b/src/local_deep_research/web/static/css/custom_dropdown.css
index 9caafb6ce8..0b0c1c3980 100644
--- a/src/local_deep_research/web/static/css/custom_dropdown.css
+++ b/src/local_deep_research/web/static/css/custom_dropdown.css
@@ -346,7 +346,7 @@ body.dropdown-active {
flex-direction: column;
gap: 0.5rem;
}
-
+
.hint-item {
font-size: 0.8rem;
}
@@ -433,11 +433,11 @@ legend {
}
@keyframes fadeIn {
- from {
+ from {
opacity: 0;
transform: translateY(-10px);
}
- to {
+ to {
opacity: 1;
transform: translateY(0);
}
diff --git a/src/local_deep_research/web/static/js/components/details.js b/src/local_deep_research/web/static/js/components/details.js
index 111f958b62..b39b41763c 100644
--- a/src/local_deep_research/web/static/js/components/details.js
+++ b/src/local_deep_research/web/static/js/components/details.js
@@ -37,7 +37,7 @@
async function loadResearchMetrics() {
try {
console.log('Loading research metrics for ID:', researchId);
-
+
// Show loading state
document.getElementById('loading').style.display = 'block';
document.getElementById('details-content').style.display = 'none';
@@ -47,14 +47,14 @@
console.log('Fetching research metrics...');
const metricsResponse = await fetch(`/metrics/api/metrics/research/${researchId}`);
console.log('Metrics response status:', metricsResponse.status);
-
+
if (!metricsResponse.ok) {
throw new Error(`Metrics API failed: ${metricsResponse.status}`);
}
const metricsResult = await metricsResponse.json();
console.log('Metrics result:', metricsResult);
-
+
if (metricsResult.status !== 'success') {
throw new Error('Failed to load research metrics');
}
@@ -66,7 +66,7 @@
console.log('Fetching timeline metrics...');
const timelineResponse = await fetch(`/metrics/api/metrics/research/${researchId}/timeline`);
console.log('Timeline response status:', timelineResponse.status);
-
+
let timelineData = null;
if (timelineResponse.ok) {
const timelineResult = await timelineResponse.json();
@@ -80,7 +80,7 @@
console.log('Fetching search metrics...');
const searchResponse = await fetch(`/metrics/api/metrics/research/${researchId}/search`);
console.log('Search response status:', searchResponse.status);
-
+
let searchData = null;
if (searchResponse.ok) {
const searchResult = await searchResponse.json();
@@ -93,16 +93,16 @@
// Display all data
console.log('Displaying research metrics...');
displayResearchMetrics();
-
+
if (timelineData) {
console.log('Displaying timeline metrics...');
displayTimelineMetrics(timelineData);
-
+
console.log('Chart.js available:', typeof Chart !== 'undefined');
console.log('Timeline data for chart:', timelineData);
createTimelineChart(timelineData);
}
-
+
if (searchData) {
console.log('Displaying search metrics...');
displaySearchMetrics(searchData);
@@ -117,36 +117,36 @@
const loadingEl = document.getElementById('loading');
const contentEl = document.getElementById('details-content');
const errorEl = document.getElementById('error');
-
+
loadingEl.style.display = 'none';
errorEl.style.display = 'none';
contentEl.style.display = 'block';
-
+
// Show metrics sections
console.log('Showing metrics sections...');
const tokenMetricsSection = document.getElementById('token-metrics-section');
const searchMetricsSection = document.getElementById('search-metrics-section');
-
+
if (tokenMetricsSection) {
tokenMetricsSection.style.display = 'block';
console.log('Token metrics section shown');
}
-
+
if (searchMetricsSection) {
searchMetricsSection.style.display = 'block';
console.log('Search metrics section shown');
}
-
+
// Force visibility with CSS overrides
contentEl.style.visibility = 'visible';
contentEl.style.opacity = '1';
contentEl.style.position = 'relative';
contentEl.style.zIndex = '1000';
-
+
console.log('Loading display:', loadingEl.style.display);
console.log('Content display:', contentEl.style.display);
console.log('Error display:', errorEl.style.display);
-
+
// Verify content is actually populated
const totalTokensEl = document.getElementById('total-tokens');
const researchQueryEl = document.getElementById('research-query');
@@ -175,13 +175,13 @@
const totalTokens = formatNumber(metricsData.total_tokens || 0);
console.log('Setting total tokens to:', totalTokens);
totalTokensEl.textContent = totalTokens;
-
+
// Calculate prompt/completion tokens from model usage
let totalPromptTokens = 0;
let totalCompletionTokens = 0;
let totalCalls = 0;
let model = 'Unknown';
-
+
if (metricsData.model_usage && metricsData.model_usage.length > 0) {
metricsData.model_usage.forEach(usage => {
totalPromptTokens += usage.prompt_tokens || 0;
@@ -192,7 +192,7 @@
}
});
}
-
+
document.getElementById('prompt-tokens').textContent = formatNumber(totalPromptTokens);
document.getElementById('completion-tokens').textContent = formatNumber(totalCompletionTokens);
document.getElementById('llm-calls').textContent = formatNumber(metricsData.total_calls || totalCalls);
@@ -285,7 +285,7 @@
// Create timeline chart
function createTimelineChart(timelineData) {
console.log('createTimelineChart called with:', timelineData);
-
+
if (!timelineData || !timelineData.timeline) {
console.log('No timeline data for chart, timelineData:', timelineData);
return;
@@ -303,7 +303,7 @@
}
console.log('Creating timeline chart with', timelineData.timeline.length, 'data points');
-
+
try {
const ctx = chartElement.getContext('2d');
console.log('Canvas context obtained');
@@ -327,7 +327,7 @@
const totalTokens = chartData.map(item => item.tokens);
const promptTokens = chartData.map(item => item.promptTokens);
const completionTokens = chartData.map(item => item.completionTokens);
-
+
console.log('Enhanced chart data:', chartData);
timelineChart = new Chart(ctx, {
@@ -443,16 +443,16 @@
const index = tooltipItems[0].dataIndex;
const data = chartData[index];
const lines = [];
-
+
if (data.responseTime > 0) {
lines.push(`Response time: ${(data.responseTime / 1000).toFixed(1)}s`);
}
-
+
if (data.timestamp) {
const time = new Date(data.timestamp).toLocaleTimeString();
lines.push(`Time: ${time}`);
}
-
+
return lines;
}
}
@@ -460,7 +460,7 @@
}
}
});
-
+
console.log('Timeline chart created successfully');
} catch (error) {
console.error('Error creating timeline chart:', error);
@@ -591,11 +591,11 @@
const index = tooltipItems[0].dataIndex;
const call = searchCalls[index];
const lines = [];
-
+
if (call.responseTime > 0) {
lines.push(`Response time: ${(call.responseTime / 1000).toFixed(1)}s`);
}
-
+
return lines;
}
}
@@ -631,19 +631,19 @@
// Check if all required DOM elements exist
function checkRequiredElements() {
const requiredIds = [
- 'loading', 'error', 'details-content', 'total-tokens', 'prompt-tokens',
+ 'loading', 'error', 'details-content', 'total-tokens', 'prompt-tokens',
'completion-tokens', 'llm-calls', 'avg-response-time', 'model-used',
'research-query', 'research-mode', 'research-date', 'total-cost',
'phase-breakdown', 'search-engine-breakdown', 'timeline-chart', 'search-chart'
];
-
+
const missing = [];
requiredIds.forEach(id => {
if (!document.getElementById(id)) {
missing.push(id);
}
});
-
+
if (missing.length > 0) {
console.error('Missing required DOM elements:', missing);
return false;
@@ -654,10 +654,10 @@
// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
console.log('DOM loaded, initializing details page');
-
+
researchId = getResearchIdFromUrl();
console.log('Research ID from URL:', researchId);
-
+
if (!researchId) {
console.error('No research ID found in URL');
showError();
@@ -686,4 +686,4 @@
}
});
-})();
\ No newline at end of file
+})();
diff --git a/src/local_deep_research/web/static/js/components/fallback/formatting.js b/src/local_deep_research/web/static/js/components/fallback/formatting.js
index 240d202ddf..d947eb2339 100644
--- a/src/local_deep_research/web/static/js/components/fallback/formatting.js
+++ b/src/local_deep_research/web/static/js/components/fallback/formatting.js
@@ -18,7 +18,7 @@
*/
function formatDate(dateStr) {
if (!dateStr) return 'N/A';
-
+
try {
const date = new Date(dateStr);
return date.toLocaleString(undefined, {
@@ -42,7 +42,7 @@
*/
function formatStatus(status) {
if (!status) return 'Unknown';
-
+
const statusMap = {
'in_progress': 'In Progress',
'completed': 'Completed',
@@ -51,7 +51,7 @@
'pending': 'Pending',
'error': 'Error'
};
-
+
return statusMap[status] || status;
}
@@ -62,14 +62,14 @@
*/
function formatMode(mode) {
if (!mode) return 'Unknown';
-
+
const modeMap = {
'quick': 'Quick Summary',
'detailed': 'Detailed Report',
'standard': 'Standard Research',
'advanced': 'Advanced Research'
};
-
+
return modeMap[mode] || mode;
}
@@ -80,10 +80,10 @@
*/
function formatDuration(seconds) {
if (!seconds && seconds !== 0) return 'N/A';
-
+
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
-
+
if (minutes === 0) {
return `${remainingSeconds}s`;
} else {
@@ -98,16 +98,16 @@
*/
function formatFileSize(bytes) {
if (!bytes && bytes !== 0) return 'N/A';
-
+
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let size = bytes;
let unitIndex = 0;
-
+
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
-
+
return `${size.toFixed(1)} ${units[unitIndex]}`;
}
@@ -119,4 +119,4 @@
formatDuration,
formatFileSize
};
-})();
\ No newline at end of file
+})();
diff --git a/src/local_deep_research/web/static/js/components/fallback/ui.js b/src/local_deep_research/web/static/js/components/fallback/ui.js
index 48590bb71e..d38bbea244 100644
--- a/src/local_deep_research/web/static/js/components/fallback/ui.js
+++ b/src/local_deep_research/web/static/js/components/fallback/ui.js
@@ -45,7 +45,7 @@
*/
function showError(message) {
console.error(message);
-
+
// Create a notification element
const notification = document.createElement('div');
notification.className = 'notification error';
@@ -54,18 +54,18 @@
<span>${message}</span>
<button class="close-notification"><i class="fas fa-times"></i></button>
`;
-
+
// Add to the page if a notification container exists, otherwise use alert
const container = document.querySelector('.notifications-container');
if (container) {
container.appendChild(notification);
-
+
// Remove after a delay
setTimeout(() => {
notification.classList.add('removing');
setTimeout(() => notification.remove(), 500);
}, 5000);
-
+
// Set up close button
const closeBtn = notification.querySelector('.close-notification');
if (closeBtn) {
@@ -86,7 +86,7 @@
*/
function showMessage(message) {
console.log(message);
-
+
// Create a notification element
const notification = document.createElement('div');
notification.className = 'notification success';
@@ -95,18 +95,18 @@
<span>${message}</span>
<button class="close-notification"><i class="fas fa-times"></i></button>
`;
-
+
// Add to the page if a notification container exists, otherwise use alert
const container = document.querySelector('.notifications-container');
if (container) {
container.appendChild(notification);
-
+
// Remove after a delay
setTimeout(() => {
notification.classList.add('removing');
setTimeout(() => notification.remove(), 500);
}, 5000);
-
+
// Set up close button
const closeBtn = notification.querySelector('.close-notification');
if (closeBtn) {
@@ -128,41 +128,41 @@
*/
function renderMarkdown(markdown) {
if (!markdown) return '';
-
+
// This is a very basic markdown renderer for fallback purposes
let html = markdown;
-
+
// Convert headers
html = html.replace(/^# (.*$)/gm, '<h1>$1</h1>');
html = html.replace(/^## (.*$)/gm, '<h2>$1</h2>');
html = html.replace(/^### (.*$)/gm, '<h3>$1</h3>');
html = html.replace(/^#### (.*$)/gm, '<h4>$1</h4>');
html = html.replace(/^##### (.*$)/gm, '<h5>$1</h5>');
-
+
// Convert code blocks
html = html.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>');
-
+
// Convert inline code
html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
-
+
// Convert bold
html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
-
+
// Convert italic
html = html.replace(/\*(.*?)\*/g, '<em>$1</em>');
-
+
// Convert links
html = html.replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2">$1</a>');
-
+
// Convert paragraphs - this is simplistic
html = html.replace(/\n\s*\n/g, '</p><p>');
html = '<p>' + html + '</p>';
-
+
// Fix potentially broken paragraph tags
html = html.replace(/<\/p><p><\/p><p>/g, '</p><p>');
html = html.replace(/<\/p><p><(h[1-5])/g, '</p><$1');
html = html.replace(/<\/(h[1-5])><p>/g, '</$1>');
-
+
return html;
}
@@ -172,14 +172,14 @@
*/
function updateFavicon(status) {
try {
- const faviconLink = document.querySelector('link[rel="icon"]') ||
+ const faviconLink = document.querySelector('link[rel="icon"]') ||
document.querySelector('link[rel="shortcut icon"]');
-
+
if (!faviconLink) {
console.warn('Favicon link not found');
return;
}
-
+
let iconPath;
switch (status) {
case 'active':
@@ -194,7 +194,7 @@
default:
iconPath = '/research/static/img/favicon.ico';
}
-
+
// Add cache busting parameter to force reload
faviconLink.href = iconPath + '?v=' + new Date().getTime();
console.log('Updated favicon to:', status);
@@ -212,4 +212,4 @@
renderMarkdown,
updateFavicon
};
-})();
\ No newline at end of file
+})();
diff --git a/src/local_deep_research/web/static/js/components/history.js b/src/local_deep_research/web/static/js/components/history.js
index 0600f53676..b20ec446a7 100644
--- a/src/local_deep_research/web/static/js/components/history.js
+++ b/src/local_deep_research/web/static/js/components/history.js
@@ -8,18 +8,18 @@
let searchInput = null;
let clearHistoryBtn = null;
let historyEmptyMessage = null;
-
+
// Component state
let historyItems = [];
let filteredItems = [];
-
+
// Fallback UI utilities in case main UI utils aren't loaded
const uiUtils = {
showSpinner: function(container, message) {
if (window.ui && window.ui.showSpinner) {
return window.ui.showSpinner(container, message);
}
-
+
// Fallback implementation
if (!container) container = document.body;
const spinnerHtml = `
@@ -30,12 +30,12 @@
`;
container.innerHTML = spinnerHtml;
},
-
+
hideSpinner: function(container) {
if (window.ui && window.ui.hideSpinner) {
return window.ui.hideSpinner(container);
}
-
+
// Fallback implementation
if (!container) container = document.body;
const spinner = container.querySelector('.loading-spinner');
@@ -43,35 +43,35 @@
spinner.remove();
}
},
-
+
showError: function(message) {
if (window.ui && window.ui.showError) {
return window.ui.showError(message);
}
-
+
// Fallback implementation
console.error(message);
alert(message);
},
-
+
showMessage: function(message) {
if (window.ui && window.ui.showMessage) {
return window.ui.showMessage(message);
}
-
+
// Fallback implementation
console.log(message);
alert(message);
}
};
-
+
// Fallback API utilities
const apiUtils = {
getResearchHistory: async function() {
if (window.api && window.api.getResearchHistory) {
return window.api.getResearchHistory();
}
-
+
// Fallback implementation
try {
const response = await fetch('/research/api/history');
@@ -84,12 +84,12 @@
throw error;
}
},
-
+
deleteResearch: async function(researchId) {
if (window.api && window.api.deleteResearch) {
return window.api.deleteResearch(researchId);
}
-
+
// Fallback implementation
try {
const response = await fetch(`/research/api/delete/${researchId}`, {
@@ -104,12 +104,12 @@
throw error;
}
},
-
+
clearResearchHistory: async function() {
if (window.api && window.api.clearResearchHistory) {
return window.api.clearResearchHistory();
}
-
+
// Fallback implementation
try {
const response = await fetch('/research/api/clear_history', {
@@ -129,7 +129,7 @@
}
}
};
-
+
/**
* Initialize the history component
*/
@@ -139,21 +139,21 @@
searchInput = document.getElementById('history-search');
clearHistoryBtn = document.getElementById('clear-history-btn');
historyEmptyMessage = document.getElementById('history-empty-message');
-
+
if (!historyContainer) {
console.error('Required DOM elements not found for history component');
return;
}
-
+
// Set up event listeners
setupEventListeners();
-
+
// Load history data
loadHistoryData();
-
+
console.log('History component initialized');
}
-
+
/**
* Set up event listeners
*/
@@ -162,12 +162,12 @@
if (searchInput) {
searchInput.addEventListener('input', handleSearchInput);
}
-
+
// Clear history button
if (clearHistoryBtn) {
clearHistoryBtn.addEventListener('click', handleClearHistory);
}
-
+
// Delegation for history item clicks
if (historyContainer) {
historyContainer.addEventListener('click', function(e) {
@@ -179,22 +179,22 @@
});
}
}
-
+
/**
* Load history data from API
*/
async function loadHistoryData() {
// Show loading state
uiUtils.showSpinner(historyContainer, 'Loading research history...');
-
+
try {
// Get history items
const response = await apiUtils.getResearchHistory();
-
+
if (response && Array.isArray(response.items)) {
historyItems = response.items;
filteredItems = [...historyItems];
-
+
// Render history items
renderHistoryItems();
} else {
@@ -206,17 +206,17 @@
uiUtils.showError('Error loading history: ' + error.message);
}
}
-
+
/**
* Render history items
*/
function renderHistoryItems() {
// Hide spinner
uiUtils.hideSpinner(historyContainer);
-
+
// Clear container
historyContainer.innerHTML = '';
-
+
// Show empty message if no items
if (filteredItems.length === 0) {
if (historyEmptyMessage) {
@@ -230,30 +230,30 @@
</div>
`;
}
-
+
if (clearHistoryBtn) {
clearHistoryBtn.style.display = 'none';
}
return;
}
-
+
// Hide empty message
if (historyEmptyMessage) {
historyEmptyMessage.style.display = 'none';
}
-
+
// Show clear button
if (clearHistoryBtn) {
clearHistoryBtn.style.display = 'inline-block';
}
-
+
// Create items
filteredItems.forEach(item => {
const itemElement = createHistoryItemElement(item);
historyContainer.appendChild(itemElement);
});
}
-
+
/**
* Format date safely using the formatter if available
*/
@@ -261,7 +261,7 @@
if (window.formatting && window.formatting.formatDate) {
return window.formatting.formatDate(dateStr);
}
-
+
// Simple fallback date formatting
try {
const date = new Date(dateStr);
@@ -270,7 +270,7 @@
return dateStr;
}
}
-
+
/**
* Format status safely using the formatter if available
*/
@@ -278,7 +278,7 @@
if (window.formatting && window.formatting.formatStatus) {
return window.formatting.formatStatus(status);
}
-
+
// Simple fallback formatting
const statusMap = {
'in_progress': 'In Progress',
@@ -286,10 +286,10 @@
'failed': 'Failed',
'suspended': 'Suspended'
};
-
+
return statusMap[status] || status;
}
-
+
/**
* Format mode safely using the formatter if available
*/
@@ -297,16 +297,16 @@
if (window.formatting && window.formatting.formatMode) {
return window.formatting.formatMode(mode);
}
-
+
// Simple fallback formatting
const modeMap = {
'quick': 'Quick Summary',
'detailed': 'Detailed Report'
};
-
+
return modeMap[mode] || mode;
}
-
+
/**
* Create a history item element
* @param {Object} item - The history item data
@@ -316,16 +316,16 @@
const itemEl = document.createElement('div');
itemEl.className = 'history-item';
itemEl.dataset.id = item.id;
-
+
// Format date
const formattedDate = formatDate(item.created_at);
-
+
// Get a display title (use query if title is not available)
const displayTitle = item.title || formatTitleFromQuery(item.query);
-
+
// Status class - convert in_progress to in-progress for CSS
const statusClass = item.status ? item.status.replace('_', '-') : '';
-
+
// Create the HTML content
itemEl.innerHTML = `
<div class="history-item-header">
@@ -337,7 +337,7 @@
<div class="history-item-mode">${formatMode(item.mode)}</div>
</div>
<div class="history-item-actions">
- ${item.status === 'completed' ?
+ ${item.status === 'completed' ?
`<button class="btn btn-sm btn-outline view-btn">
<i class="fas fa-eye"></i> View
</button>` : ''}
@@ -346,7 +346,7 @@
</button>
</div>
`;
-
+
// Add event listeners
const viewBtn = itemEl.querySelector('.view-btn');
if (viewBtn) {
@@ -355,7 +355,7 @@
window.location.href = `/research/results/${item.id}`;
});
}
-
+
const deleteBtn = itemEl.querySelector('.delete-item-btn');
if (deleteBtn) {
deleteBtn.addEventListener('click', (e) => {
@@ -363,7 +363,7 @@
handleDeleteItem(item.id);
});
}
-
+
// Add click event to the whole item
itemEl.addEventListener('click', () => {
if (item.status === 'completed') {
@@ -372,10 +372,10 @@
window.location.href = `/research/progress/${item.id}`;
}
});
-
+
return itemEl;
}
-
+
/**
* Format a title from a query string
* Truncates long queries and adds ellipsis
@@ -384,21 +384,21 @@
*/
function formatTitleFromQuery(query) {
if (!query) return 'Untitled Research';
-
+
// Truncate long queries
if (query.length > 60) {
return query.substring(0, 57) + '...';
}
-
+
return query;
}
-
+
/**
* Handle search input
*/
function handleSearchInput() {
const searchTerm = searchInput.value.trim().toLowerCase();
-
+
if (!searchTerm) {
// Reset to show all items
filteredItems = [...historyItems];
@@ -406,23 +406,23 @@
// Filter items based on search term
filteredItems = historyItems.filter(item => {
// Search in title if available, otherwise in query
- const titleMatch = item.title ?
- item.title.toLowerCase().includes(searchTerm) :
+ const titleMatch = item.title ?
+ item.title.toLowerCase().includes(searchTerm) :
false;
-
+
// Always search in query
- const queryMatch = item.query ?
- item.query.toLowerCase().includes(searchTerm) :
+ const queryMatch = item.query ?
+ item.query.toLowerCase().includes(searchTerm) :
false;
-
+
return titleMatch || queryMatch;
});
}
-
+
// Render filtered items
renderHistoryItems();
}
-
+
/**
* Handle delete item
* @param {string} itemId - The item ID to delete
@@ -431,18 +431,18 @@
if (!confirm('Are you sure you want to delete this research? This action cannot be undone.')) {
return;
}
-
+
try {
// Delete item via API
await apiUtils.deleteResearch(itemId);
-
+
// Remove from arrays
historyItems = historyItems.filter(item => item.id != itemId);
filteredItems = filteredItems.filter(item => item.id != itemId);
-
+
// Show success message
uiUtils.showMessage('Research deleted successfully');
-
+
// Re-render history items
renderHistoryItems();
} catch (error) {
@@ -450,7 +450,7 @@
uiUtils.showError('Error deleting research: ' + error.message);
}
}
-
+
/**
* Handle clear history
*/
@@ -458,18 +458,18 @@
if (!confirm('Are you sure you want to clear all research history? This action cannot be undone.')) {
return;
}
-
+
try {
// Clear history via API
await apiUtils.clearResearchHistory();
-
+
// Clear arrays
historyItems = [];
filteredItems = [];
-
+
// Show success message
uiUtils.showMessage('Research history cleared successfully');
-
+
// Re-render history items
renderHistoryItems();
} catch (error) {
@@ -477,11 +477,11 @@
uiUtils.showError('Error clearing history: ' + error.message);
}
}
-
+
// Initialize on DOM content loaded
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initializeHistory);
} else {
initializeHistory();
}
-})();
\ No newline at end of file
+})();
diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.js
index b641cb8a95..eb9a677e33 100644
--- a/src/local_deep_research/web/static/js/components/research.js
+++ b/src/local_deep_research/web/static/js/components/research.js
@@ -61,11 +61,11 @@
m.setAttribute('aria-checked', 'false');
m.setAttribute('tabindex', '-1');
});
-
+
modeElement.classList.add('active');
modeElement.setAttribute('aria-checked', 'true');
modeElement.setAttribute('tabindex', '0');
-
+
// Update the corresponding radio button
const modeValue = modeElement.getAttribute('data-mode');
const radioButton = document.getElementById(`mode-${modeValue}`);
@@ -168,7 +168,7 @@
setupEventListeners();
populateModelProviders();
initializeDropdowns();
-
+
// Auto-focus the query input
if (queryInput) {
queryInput.focus();
@@ -498,7 +498,7 @@
mode.addEventListener('click', function() {
selectMode(this);
});
-
+
mode.addEventListener('keydown', function(event) {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
diff --git a/src/local_deep_research/web/static/js/main.js b/src/local_deep_research/web/static/js/main.js
index ec2df0454f..244dedb32a 100644
--- a/src/local_deep_research/web/static/js/main.js
+++ b/src/local_deep_research/web/static/js/main.js
@@ -12,7 +12,7 @@
'page-history': ['history.js'],
'page-settings': ['settings.js']
};
-
+
// Core services to always load
const coreServices = [
'formatting.js',
@@ -21,53 +21,53 @@
'socket.js'
// 'audio.js' - Removed from here, loaded separately
];
-
+
// Optional services to load when needed
const optionalServices = {
'page-results': ['pdf.js'],
'page-detail': ['pdf.js']
};
-
+
/**
* Initialize the application
*/
function initializeApp() {
// Detect current page
const currentPage = detectCurrentPage();
-
+
if (!currentPage) {
console.error('Cannot detect current page type');
return;
}
-
+
console.log('Current page detected:', currentPage);
-
+
// IMPORTANT: Load audio.js first, before ANY other scripts
loadAudioServiceFirst(() => {
// Continue loading other scripts after audio service is loaded
console.log('Audio service script loaded, continuing with other scripts');
-
+
// Load UI and formatting utils
loadScripts('utils', coreServices.filter(s => s.includes('formatting') || s.includes('ui')));
-
+
// Then load the rest
loadScripts('services', coreServices.filter(s => s.includes('api') || s.includes('socket')));
-
+
// Load optional services for this page
if (optionalServices[currentPage]) {
loadScripts('services', optionalServices[currentPage]);
}
-
+
// Load components for this page AFTER all services
if (pageComponents[currentPage]) {
loadScripts('components', pageComponents[currentPage]);
}
-
+
// Initialize tooltips and other global UI elements
initializeGlobalUI();
});
}
-
+
/**
* Load audio service first and separately to ensure it's fully loaded before other scripts
* @param {Function} callback - Function to call after audio service is loaded
@@ -77,11 +77,11 @@
const audioScript = document.createElement('script');
audioScript.src = `/research/static/js/services/audio.js?t=${new Date().getTime()}`; // Add timestamp to avoid cache
audioScript.async = false;
-
+
// Set up callback for when script loads
audioScript.onload = function() {
console.log('Audio service script loaded successfully');
-
+
// Check if audio service is available in window object
setTimeout(() => {
if (window.audio) {
@@ -89,39 +89,39 @@
} else {
console.warn('Audio service not available in window object after script load');
}
-
+
// Continue regardless
callback();
}, 100); // Small delay to ensure script executes
};
-
+
// Error handling
audioScript.onerror = function() {
console.error('Failed to load audio service script');
// Continue with other scripts even if audio fails
callback();
};
-
+
// Add to document
document.body.appendChild(audioScript);
}
-
+
/**
* Detect the current page based on body class
* @returns {string|null} The page identifier or null if not found
*/
function detectCurrentPage() {
const bodyClasses = document.body.classList;
-
+
for (const pageId in pageComponents) {
if (bodyClasses.contains(pageId)) {
return pageId;
}
}
-
+
// Check URL patterns as fallback
const path = window.location.pathname;
-
+
if (path === '/' || path === '/index' || path === '/home' || path === '/research/') {
return 'page-home';
} else if (path.includes('/research/progress')) {
@@ -135,10 +135,10 @@
} else if (path.includes('/research/settings')) {
return 'page-settings';
}
-
+
return null;
}
-
+
/**
* Load scripts dynamically
* @param {string} folder - The folder containing the scripts
@@ -146,7 +146,7 @@
*/
function loadScripts(folder, scripts) {
if (!scripts || !scripts.length) return;
-
+
scripts.forEach(script => {
const scriptElement = document.createElement('script');
scriptElement.src = `/research/static/js/${folder}/${script}`;
@@ -154,7 +154,7 @@
document.body.appendChild(scriptElement);
});
}
-
+
/**
* Initialize global UI elements
*/
@@ -164,7 +164,7 @@
// Only ask for permission when user interacts with the page
document.addEventListener('click', requestNotificationPermission, { once: true });
}
-
+
// Initialize theme toggle
const themeToggle = document.getElementById('theme-toggle');
if (themeToggle) {
@@ -172,42 +172,42 @@
const savedTheme = localStorage.getItem('theme');
const systemDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
const isDarkMode = savedTheme === 'dark' || (savedTheme === null && systemDarkMode);
-
+
// Set initial theme
document.documentElement.setAttribute('data-theme', isDarkMode ? 'dark' : 'light');
- themeToggle.innerHTML = isDarkMode ?
- '<i class="fas fa-sun"></i>' :
+ themeToggle.innerHTML = isDarkMode ?
+ '<i class="fas fa-sun"></i>' :
'<i class="fas fa-moon"></i>';
-
+
// Listen for theme toggle click
themeToggle.addEventListener('click', function() {
const currentTheme = document.documentElement.getAttribute('data-theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
-
+
document.documentElement.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
-
- themeToggle.innerHTML = newTheme === 'dark' ?
- '<i class="fas fa-sun"></i>' :
+
+ themeToggle.innerHTML = newTheme === 'dark' ?
+ '<i class="fas fa-sun"></i>' :
'<i class="fas fa-moon"></i>';
});
}
-
+
// Initialize mobile menu toggle
const mobileMenuToggle = document.getElementById('mobile-menu-toggle');
const navMenu = document.getElementById('main-nav');
-
+
if (mobileMenuToggle && navMenu) {
mobileMenuToggle.addEventListener('click', function() {
navMenu.classList.toggle('open');
mobileMenuToggle.setAttribute(
- 'aria-expanded',
+ 'aria-expanded',
navMenu.classList.contains('open') ? 'true' : 'false'
);
});
}
}
-
+
/**
* Request notification permission
*/
@@ -216,11 +216,11 @@
Notification.requestPermission();
}
}
-
+
// Initialize when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initializeApp);
} else {
initializeApp();
}
-})();
\ No newline at end of file
+})();
diff --git a/src/local_deep_research/web/static/js/services/audio.js b/src/local_deep_research/web/static/js/services/audio.js
index fb259e76ba..6dee96cabd 100644
--- a/src/local_deep_research/web/static/js/services/audio.js
+++ b/src/local_deep_research/web/static/js/services/audio.js
@@ -28,4 +28,4 @@ window.audio = {
};
// Log that audio is disabled
-console.log('Audio service is currently disabled - notifications will be implemented later');
\ No newline at end of file
+console.log('Audio service is currently disabled - notifications will be implemented later');
diff --git a/src/local_deep_research/web/static/js/services/formatting.js b/src/local_deep_research/web/static/js/services/formatting.js
index 25a720409d..f03116b134 100644
--- a/src/local_deep_research/web/static/js/services/formatting.js
+++ b/src/local_deep_research/web/static/js/services/formatting.js
@@ -38,31 +38,31 @@ function formatMode(mode) {
*/
function formatDate(date, duration = null) {
if (!date) return 'Unknown';
-
+
try {
const dateObj = new Date(date);
- const options = {
- year: 'numeric',
- month: 'short',
+ const options = {
+ year: 'numeric',
+ month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
};
-
+
let formattedDate = dateObj.toLocaleDateString('en-US', options);
-
+
if (duration) {
// Format the duration
const minutes = Math.floor(duration / 60);
const seconds = duration % 60;
-
+
if (minutes > 0) {
formattedDate += ` (${minutes}m ${seconds}s)`;
} else {
formattedDate += ` (${seconds}s)`;
}
}
-
+
return formattedDate;
} catch (e) {
console.error('Error formatting date:', e);
@@ -77,10 +77,10 @@ function formatDate(date, duration = null) {
*/
function formatDuration(seconds) {
if (!seconds || isNaN(seconds)) return 'Unknown';
-
+
const minutes = Math.floor(seconds / 60);
const remainingSeconds = Math.floor(seconds % 60);
-
+
if (minutes === 0) {
return `${remainingSeconds}s`;
} else {
@@ -116,4 +116,4 @@ window.formatting = {
formatDuration,
formatNumber,
capitalizeFirstLetter
-};
\ No newline at end of file
+};
diff --git a/src/local_deep_research/web/static/js/services/keyboard.js b/src/local_deep_research/web/static/js/services/keyboard.js
index d4eaf467e3..504510f58b 100644
--- a/src/local_deep_research/web/static/js/services/keyboard.js
+++ b/src/local_deep_research/web/static/js/services/keyboard.js
@@ -23,20 +23,20 @@
function matchesShortcut(event, pattern) {
const parts = pattern.toLowerCase().split('+');
const key = parts[parts.length - 1];
-
+
// Check modifiers
const requiresCtrl = parts.includes('ctrl');
const requiresCmd = parts.includes('cmd');
const requiresShift = parts.includes('shift');
const requiresAlt = parts.includes('alt');
-
+
// For single key shortcuts, ensure NO modifiers are pressed
if (parts.length === 1) {
if (event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) {
return false;
}
}
-
+
// Match key
const eventKey = event.key.toLowerCase();
if (eventKey !== key && event.code.toLowerCase() !== `key${key}`) {
@@ -45,13 +45,13 @@
else if (key === ',' && eventKey !== ',') return false;
else if (key !== '/' && key !== ',' && eventKey !== key) return false;
}
-
+
// Match modifiers (only if required)
if (requiresCtrl && !event.ctrlKey) return false;
if (requiresCmd && !event.metaKey) return false;
if (requiresShift && !event.shiftKey) return false;
if (requiresAlt && !event.altKey) return false;
-
+
return true;
}
@@ -60,7 +60,7 @@
*/
function initializeKeyboardShortcuts() {
console.log('Keyboard shortcuts initialized');
-
+
document.addEventListener('keydown', function(event) {
// Skip if user is typing in an input field
const activeElement = document.activeElement;
@@ -69,17 +69,17 @@
activeElement.tagName === 'TEXTAREA' ||
activeElement.contentEditable === 'true'
);
-
+
// Allow Escape even when typing
if (isTyping && event.key !== 'Escape') {
return;
}
-
+
// Debug log
if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
console.log('Key pressed:', event.key, 'Code:', event.code);
}
-
+
// Check each shortcut
for (const [name, shortcut] of Object.entries(shortcuts)) {
for (const pattern of shortcut.keys) {
@@ -92,7 +92,7 @@
}
}
});
-
+
// Add help text to footer if on main pages
addKeyboardHints();
}
@@ -110,7 +110,7 @@
function getAvailableShortcuts() {
const currentPath = window.location.pathname;
const allShortcuts = { ...shortcuts };
-
+
// Add page-specific shortcuts
if (currentPath.includes('/research/progress/')) {
allShortcuts.viewResults = {
@@ -124,7 +124,7 @@
}
};
}
-
+
if (currentPath.includes('/research/results/')) {
allShortcuts.escape = {
keys: ['escape'],
@@ -132,7 +132,7 @@
handler: () => window.location.href = '/'
};
}
-
+
return allShortcuts;
}
@@ -154,4 +154,4 @@
}
};
-})();
\ No newline at end of file
+})();
diff --git a/src/local_deep_research/web/static/js/services/pdf.js b/src/local_deep_research/web/static/js/services/pdf.js
index cc6c6c9669..6ced7a397f 100644
--- a/src/local_deep_research/web/static/js/services/pdf.js
+++ b/src/local_deep_research/web/static/js/services/pdf.js
@@ -15,15 +15,15 @@ async function generatePdf(title, content, metadata = {}) {
if (typeof jspdf === 'undefined') {
throw new Error('PDF generation libraries not loaded (jsPDF missing)');
}
-
+
if (typeof html2canvas === 'undefined') {
throw new Error('PDF generation libraries not loaded (html2canvas missing)');
}
-
+
// Ensure title and content are strings
title = String(title || 'Research Report');
content = String(content || '');
-
+
// Create a temporary container to render the markdown
const tempContainer = document.createElement('div');
tempContainer.style.position = 'absolute';
@@ -31,7 +31,7 @@ async function generatePdf(title, content, metadata = {}) {
tempContainer.style.top = '-9999px';
tempContainer.style.width = '8.5in'; // US Letter width
tempContainer.className = 'pdf-content';
-
+
// Add PDF-specific styles
tempContainer.innerHTML = `
<style>
@@ -144,23 +144,23 @@ async function generatePdf(title, content, metadata = {}) {
<p>Generated by Deep Research System</p>
</div>
`;
-
+
// Add to the document body temporarily
document.body.appendChild(tempContainer);
-
+
try {
console.log("Starting PDF generation...");
-
+
// Use the jsPDF library from the window object
const { jsPDF } = window.jspdf;
-
+
// Create a new PDF document
const pdf = new jsPDF('p', 'pt', 'letter');
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = pdf.internal.pageSize.getHeight();
const margin = 40;
const contentWidth = pdfWidth - 2 * margin;
-
+
// Function to add page with header
const addPageWithHeader = (pageNum) => {
if (pageNum > 1) {
@@ -170,49 +170,49 @@ async function generatePdf(title, content, metadata = {}) {
pdf.setTextColor(100, 100, 100);
pdf.text(`Deep Research - ${title} - Page ${pageNum}`, margin, pdfHeight - 20);
};
-
+
// Process each element with a more optimized approach
const contentDiv = tempContainer.querySelector('.pdf-body');
if (!contentDiv) {
throw new Error('PDF body container not found');
}
-
+
// Create a more efficient PDF generation approach that keeps text selectable
const elements = Array.from(contentDiv.children);
let currentY = margin;
let pageNum = 1;
-
+
// Add the first page with header
addPageWithHeader(pageNum);
-
+
// Process each element
for (const element of elements) {
// Skip style element
if (element.tagName === 'STYLE') continue;
-
+
try {
// Simple text content - handled directly by jsPDF for better text selection
- if ((element.tagName === 'P' || element.tagName === 'DIV' || element.tagName === 'H1' ||
- element.tagName === 'H2' || element.tagName === 'H3') &&
+ if ((element.tagName === 'P' || element.tagName === 'DIV' || element.tagName === 'H1' ||
+ element.tagName === 'H2' || element.tagName === 'H3') &&
!element.querySelector('img, canvas, svg, table') &&
!element.innerHTML.includes('<')) {
-
+
pdf.setFont('helvetica', element.tagName.startsWith('H') ? 'bold' : 'normal');
pdf.setFontSize(element.tagName === 'H1' ? 18 : (element.tagName === 'H2' ? 16 : (element.tagName === 'H3' ? 14 : 11)));
pdf.setTextColor(0, 0, 0);
-
+
const text = element.textContent.trim();
if (!text) continue; // Skip empty text
-
+
const textLines = pdf.splitTextToSize(text, contentWidth);
-
+
// Check if we need a new page
if (currentY + (textLines.length * 14) > pdfHeight - margin) {
pageNum++;
addPageWithHeader(pageNum);
currentY = margin;
}
-
+
pdf.text(textLines, margin, currentY + 12);
currentY += (textLines.length * 14) + 10;
}
@@ -223,22 +223,22 @@ async function generatePdf(title, content, metadata = {}) {
const item = listItems[i];
const itemText = item.textContent.trim();
if (!itemText) continue;
-
+
pdf.setFont('helvetica', 'normal');
pdf.setFontSize(11);
pdf.setTextColor(0, 0, 0);
-
+
const bulletPoint = element.tagName === 'UL' ? '•' : `${i + 1}.`;
const textWithBullet = `${bulletPoint} ${itemText}`;
const textLines = pdf.splitTextToSize(textWithBullet, contentWidth - 10);
-
+
// Check if we need a new page
if (currentY + (textLines.length * 14) > pdfHeight - margin) {
pageNum++;
addPageWithHeader(pageNum);
currentY = margin;
}
-
+
pdf.text(textLines, margin, currentY + 12);
currentY += (textLines.length * 14) + 5;
}
@@ -248,44 +248,44 @@ async function generatePdf(title, content, metadata = {}) {
else if (element.tagName === 'TABLE') {
const rows = Array.from(element.querySelectorAll('tr'));
if (rows.length === 0) continue;
-
+
// Get header cells
const headerCells = Array.from(rows[0].querySelectorAll('th, td'));
const colCount = headerCells.length || 1;
const colWidth = contentWidth / colCount;
-
+
// Start table at current position
let tableY = currentY;
-
+
// Check if we need a new page
if (tableY + 20 > pdfHeight - margin) {
pageNum++;
addPageWithHeader(pageNum);
tableY = margin;
}
-
+
// Draw header background
pdf.setFillColor(240, 240, 240);
pdf.rect(margin, tableY, contentWidth, 20, 'F');
-
+
// Draw header text
pdf.setFont("helvetica", "bold");
pdf.setFontSize(10);
pdf.setTextColor(0, 0, 0);
-
+
headerCells.forEach((cell, index) => {
const text = cell.textContent.trim();
const x = margin + (index * colWidth) + 5;
pdf.text(text, x, tableY + 13);
});
-
+
// Draw horizontal line after header
pdf.setDrawColor(200, 200, 200);
pdf.setLineWidth(0.5);
pdf.line(margin, tableY + 20, margin + contentWidth, tableY + 20);
-
+
tableY += 20;
-
+
// Draw table rows
pdf.setFont("helvetica", "normal");
for (let i = 1; i < rows.length; i++) {
@@ -294,46 +294,46 @@ async function generatePdf(title, content, metadata = {}) {
pageNum++;
addPageWithHeader(pageNum);
tableY = margin;
-
+
// Redraw header on new page
pdf.setFillColor(240, 240, 240);
pdf.rect(margin, tableY, contentWidth, 20, 'F');
-
+
pdf.setFont("helvetica", "bold");
headerCells.forEach((cell, index) => {
const text = cell.textContent.trim();
const x = margin + (index * colWidth) + 5;
pdf.text(text, x, tableY + 13);
});
-
+
pdf.line(margin, tableY + 20, margin + contentWidth, tableY + 20);
tableY += 20;
pdf.setFont("helvetica", "normal");
}
-
+
// Get cells for this row
const cells = Array.from(rows[i].querySelectorAll('td, th'));
-
+
// Draw cell content
cells.forEach((cell, index) => {
const text = cell.textContent.trim();
if (!text) return;
-
+
const x = margin + (index * colWidth) + 5;
pdf.text(text, x, tableY + 13);
});
-
+
// Draw horizontal line after row
pdf.line(margin, tableY + 20, margin + contentWidth, tableY + 20);
tableY += 20;
}
-
+
// Draw vertical lines
for (let i = 0; i <= colCount; i++) {
const x = margin + (i * colWidth);
pdf.line(x, currentY, x, tableY);
}
-
+
// Update current position to after the table
currentY = tableY + 10;
}
@@ -342,67 +342,67 @@ async function generatePdf(title, content, metadata = {}) {
const preElement = element.tagName === 'PRE' ? element : element.querySelector('pre');
const codeText = preElement.textContent.trim();
if (!codeText) continue;
-
+
pdf.setFont("courier", "normal"); // Use monospace font for code
pdf.setFontSize(9);
pdf.setTextColor(0, 0, 0);
-
+
// Split code into lines, respecting line breaks
const codeLines = codeText.split(/\r?\n/);
const wrappedLines = [];
-
+
codeLines.forEach(line => {
// Wrap long lines
const wrappedLine = pdf.splitTextToSize(line, contentWidth - 20);
wrappedLines.push(...wrappedLine);
});
-
+
// Calculate code block height
const lineHeight = 12;
const codeHeight = wrappedLines.length * lineHeight + 20; // 10px padding top and bottom
-
+
// Check if we need a new page
if (currentY + codeHeight > pdfHeight - margin) {
pageNum++;
addPageWithHeader(pageNum);
currentY = margin;
}
-
+
// Draw code block background
pdf.setFillColor(245, 245, 245);
pdf.rect(margin, currentY, contentWidth, codeHeight, 'F');
-
+
// Draw code content
pdf.setTextColor(0, 0, 0);
wrappedLines.forEach((line, index) => {
pdf.text(line, margin + 10, currentY + 15 + (index * lineHeight));
});
-
+
// Update position
currentY += codeHeight + 10;
}
// Images - render as images
else if (element.tagName === 'IMG' || element.querySelector('img')) {
const imgElement = element.tagName === 'IMG' ? element : element.querySelector('img');
-
+
if (!imgElement || !imgElement.src) continue;
-
+
try {
// Create a new image to get dimensions
const img = new Image();
img.src = imgElement.src;
-
+
// Calculate dimensions
const imgWidth = contentWidth;
const imgHeight = img.height * (contentWidth / img.width);
-
+
// Check if we need a new page
if (currentY + imgHeight > pdfHeight - margin) {
pageNum++;
addPageWithHeader(pageNum);
currentY = margin;
}
-
+
// Add image to PDF
pdf.addImage(img.src, 'JPEG', margin, currentY, imgWidth, imgHeight);
currentY += imgHeight + 10;
@@ -416,21 +416,21 @@ async function generatePdf(title, content, metadata = {}) {
else {
// Try to extract text content and render it directly first
const textContent = element.textContent.trim();
-
+
if (textContent) {
pdf.setFont('helvetica', 'normal');
pdf.setFontSize(11);
pdf.setTextColor(0, 0, 0);
-
+
const textLines = pdf.splitTextToSize(textContent, contentWidth);
-
+
// Check if we need a new page
if (currentY + (textLines.length * 14) > pdfHeight - margin) {
pageNum++;
addPageWithHeader(pageNum);
currentY = margin;
}
-
+
pdf.text(textLines, margin, currentY + 12);
currentY += (textLines.length * 14) + 10;
} else {
@@ -442,17 +442,17 @@ async function generatePdf(title, content, metadata = {}) {
logging: false,
backgroundColor: '#FFFFFF'
});
-
+
const imgData = canvas.toDataURL('image/png');
const imgWidth = contentWidth;
const imgHeight = (canvas.height * contentWidth) / canvas.width;
-
+
if (currentY + imgHeight > pdfHeight - margin) {
pageNum++;
addPageWithHeader(pageNum);
currentY = margin;
}
-
+
pdf.addImage(imgData, 'PNG', margin, currentY, imgWidth, imgHeight);
currentY += imgHeight + 10;
} catch (canvasError) {
@@ -468,7 +468,7 @@ async function generatePdf(title, content, metadata = {}) {
currentY += 20;
}
}
-
+
// Generate the PDF blob
const blob = pdf.output('blob');
console.log("PDF generation completed successfully");
@@ -494,20 +494,20 @@ async function generatePdf(title, content, metadata = {}) {
async function downloadPdf(titleOrData, content, metadata = {}) {
try {
console.log("Starting PDF download process...");
-
+
let title, pdfContent, pdfMetadata;
-
+
// Determine if we're being passed a research data object or direct parameters
if (typeof titleOrData === 'object' && titleOrData !== null) {
// We were passed a research data object
const researchData = titleOrData;
const researchId = content; // Second parameter is research ID in this case
-
+
console.log("Processing research data object", { researchId });
-
+
// Extract title from research data
title = researchData.query || researchData.title || researchData.prompt || `Research ${researchId}`;
-
+
// Extract content - try all possible locations based on how data might be structured
if (researchData.markdown) {
pdfContent = researchData.markdown;
@@ -545,7 +545,7 @@ async function downloadPdf(titleOrData, content, metadata = {}) {
console.warn("Could not find content in research data, using JSON stringification");
pdfContent = JSON.stringify(researchData, null, 2);
}
-
+
// Extract metadata
pdfMetadata = {
mode: researchData.mode,
@@ -559,12 +559,12 @@ async function downloadPdf(titleOrData, content, metadata = {}) {
pdfContent = content || '';
pdfMetadata = metadata || {};
}
-
+
// Ensure title is a string
title = String(title || 'Research Report');
-
+
console.log("PDF parameters prepared", { titleLength: title.length, contentLength: pdfContent?.length });
-
+
// Show loading indicator
const loadingIndicator = document.createElement('div');
loadingIndicator.className = 'loading-indicator';
@@ -579,27 +579,27 @@ async function downloadPdf(titleOrData, content, metadata = {}) {
loadingIndicator.style.padding = '20px';
loadingIndicator.style.borderRadius = '5px';
document.body.appendChild(loadingIndicator);
-
+
// Generate the PDF
const blob = await generatePdf(title, pdfContent, pdfMetadata);
-
+
// Create a download link
const url = URL.createObjectURL(blob);
const downloadLink = document.createElement('a');
downloadLink.href = url;
-
+
// Generate a filename based on the title
const safeTitle = title.replace(/[^a-z0-9]/gi, '_').toLowerCase().substring(0, 30);
downloadLink.download = `${safeTitle}_research.pdf`;
-
+
// Trigger the download
document.body.appendChild(downloadLink);
downloadLink.click();
-
+
// Clean up
document.body.removeChild(downloadLink);
URL.revokeObjectURL(url);
-
+
console.log("PDF download process completed");
return true;
} catch (error) {
@@ -619,4 +619,4 @@ async function downloadPdf(titleOrData, content, metadata = {}) {
window.pdfService = {
generatePdf,
downloadPdf
-};
\ No newline at end of file
+};
diff --git a/src/local_deep_research/web/static/sounds/README.md b/src/local_deep_research/web/static/sounds/README.md
index 01fd553032..e4ee702149 100644
--- a/src/local_deep_research/web/static/sounds/README.md
+++ b/src/local_deep_research/web/static/sounds/README.md
@@ -26,4 +26,4 @@ You can download copyright-free sound files from these sources:
## Usage
-The application will automatically use these sounds when research tasks complete or fail, but only when the browser tab is not in focus.
\ No newline at end of file
+The application will automatically use these sounds when research tasks complete or fail, but only when the browser tab is not in focus.
diff --git a/src/local_deep_research/web/templates/components/mobile_nav.html b/src/local_deep_research/web/templates/components/mobile_nav.html
index 3a6f236fde..c4ba269d30 100644
--- a/src/local_deep_research/web/templates/components/mobile_nav.html
+++ b/src/local_deep_research/web/templates/components/mobile_nav.html
@@ -19,4 +19,4 @@
</a>
</li>
</ul>
-</nav>
\ No newline at end of file
+</nav>
diff --git a/src/local_deep_research/web/templates/pages/details.html b/src/local_deep_research/web/templates/pages/details.html
index e93d260318..65ad949d14 100644
--- a/src/local_deep_research/web/templates/pages/details.html
+++ b/src/local_deep_research/web/templates/pages/details.html
@@ -276,7 +276,7 @@
<canvas id="timeline-chart"></canvas>
</div>
</div>
-
+
<!-- Search Results Chart -->
<div>
<h3><i class="fas fa-chart-line"></i> Search Results Over Time</h3>
diff --git a/src/local_deep_research/web/templates/pages/history.html b/src/local_deep_research/web/templates/pages/history.html
index 8491c7ba90..fba365924e 100644
--- a/src/local_deep_research/web/templates/pages/history.html
+++ b/src/local_deep_research/web/templates/pages/history.html
@@ -48,4 +48,4 @@
<script src="{{ url_for('research.serve_static', path='js/services/api.js') }}"></script>
<!-- Then load the component -->
<script src="{{ url_for('research.serve_static', path='js/components/history.js') }}"></script>
-{% endblock %}
\ No newline at end of file
+{% endblock %}
diff --git a/src/local_deep_research/web/templates/pages/progress.html b/src/local_deep_research/web/templates/pages/progress.html
index d81c87d235..6a9f978ac5 100644
--- a/src/local_deep_research/web/templates/pages/progress.html
+++ b/src/local_deep_research/web/templates/pages/progress.html
@@ -39,7 +39,7 @@
</div>
</div>
</div>
-
+
{% include "components/log_panel.html" %}
</div>
{% endblock %}
@@ -54,4 +54,4 @@
<!-- Then load the component -->
<script src="{{ url_for('research.serve_static', path='js/components/progress.js') }}"></script>
-{% endblock %}
\ No newline at end of file
+{% endblock %}
diff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.html
index bb32cb87e9..62c7051d03 100644
--- a/src/local_deep_research/web/templates/pages/research.html
+++ b/src/local_deep_research/web/templates/pages/research.html
@@ -52,7 +52,7 @@
<p>Generated in a few minutes</p>
</div>
</label>
-
+
<input type="radio" id="mode-detailed" name="research_mode" value="detailed" class="sr-only">
<label for="mode-detailed" class="mode-option" data-mode="detailed" role="radio" aria-checked="false" tabindex="-1">
<div class="mode-icon"><i class="fas fa-microscope" aria-hidden="true"></i></div>
diff --git a/src/local_deep_research/web/utils/formatters.py b/src/local_deep_research/web/utils/formatters.py
index 344fe4483a..570452c209 100644
--- a/src/local_deep_research/web/utils/formatters.py
+++ b/src/local_deep_research/web/utils/formatters.py
@@ -29,7 +29,9 @@ def convert_debug_to_markdown(raw_text, query):
if "DETAILED FINDINGS:" in raw_text:
logger.info("Found DETAILED FINDINGS section")
detailed_index = raw_text.index("DETAILED FINDINGS:")
- content = raw_text[detailed_index + len("DETAILED FINDINGS:") :].strip()
+ content = raw_text[
+ detailed_index + len("DETAILED FINDINGS:") :
+ ].strip()
else:
logger.info("No DETAILED FINDINGS section found, using full text")
content = raw_text
@@ -40,7 +42,8 @@ def convert_debug_to_markdown(raw_text, query):
[
line
for line in content.split("\n")
- if not line.strip().startswith("===") and not line.strip() == "=" * 80
+ if not line.strip().startswith("===")
+ and not line.strip() == "=" * 80
]
)
lines_after = len(content.split("\n"))
@@ -54,7 +57,10 @@ def convert_debug_to_markdown(raw_text, query):
for marker in ["DETAILED FINDINGS:", "COMPLETE RESEARCH:"]:
if marker in content[search_index:]:
marker_pos = content.index(marker, search_index)
- if next_major_section == -1 or marker_pos < next_major_section:
+ if (
+ next_major_section == -1
+ or marker_pos < next_major_section
+ ):
next_major_section = marker_pos
if next_major_section != -1:
diff --git a/src/local_deep_research/web_search_engines/engines/full_search.py b/src/local_deep_research/web_search_engines/engines/full_search.py
index 910e9fa6dc..31a470b492 100644
--- a/src/local_deep_research/web_search_engines/engines/full_search.py
+++ b/src/local_deep_research/web_search_engines/engines/full_search.py
@@ -74,7 +74,9 @@ class FullSearchResults:
if not html or not html.strip():
return ""
paragraphs = justext.justext(html, justext.get_stoplist(self.language))
- cleaned = "\n".join([p.text for p in paragraphs if not p.is_boilerplate])
+ cleaned = "\n".join(
+ [p.text for p in paragraphs if not p.is_boilerplate]
+ )
return cleaned
def run(self, query: str):
@@ -91,7 +93,11 @@ class FullSearchResults:
filtered_results = search_results
# Extract URLs from filtered results
- urls = [result.get("link") for result in filtered_results if result.get("link")]
+ urls = [
+ result.get("link")
+ for result in filtered_results
+ if result.get("link")
+ ]
if not urls:
logger.error("\n === NO VALID LINKS ===\n")
diff --git a/src/local_deep_research/web_search_engines/engines/meta_search_engine.py b/src/local_deep_research/web_search_engines/engines/meta_search_engine.py
index e19e6eefcf..dcd484d649 100644
--- a/src/local_deep_research/web_search_engines/engines/meta_search_engine.py
+++ b/src/local_deep_research/web_search_engines/engines/meta_search_engine.py
@@ -39,7 +39,9 @@ class MetaSearchEngine(BaseSearchEngine):
"""
# Initialize the BaseSearchEngine with the LLM, max_filtered_results, and max_results
super().__init__(
- llm=llm, max_filtered_results=max_filtered_results, max_results=max_results
+ llm=llm,
+ max_filtered_results=max_filtered_results,
+ max_results=max_results,
)
self.use_api_key_services = use_api_key_services
@@ -82,7 +84,9 @@ class MetaSearchEngine(BaseSearchEngine):
)
else:
# Format: search.engine.web.{engine_name}.use_in_auto_search
- auto_search_setting = f"search.engine.web.{name}.use_in_auto_search"
+ auto_search_setting = (
+ f"search.engine.web.{name}.use_in_auto_search"
+ )
# Get setting from database, default to False if not found
use_in_auto_search = get_db_setting(auto_search_setting, False)
@@ -95,7 +99,10 @@ class MetaSearchEngine(BaseSearchEngine):
continue
# Skip engines that require API keys if we don't want to use them
- if config_.get("requires_api_key", False) and not self.use_api_key_services:
+ if (
+ config_.get("requires_api_key", False)
+ and not self.use_api_key_services
+ ):
continue
# Skip engines that require API keys if the key is not available
@@ -155,11 +162,15 @@ class MetaSearchEngine(BaseSearchEngine):
# For searches containing "arxiv", prioritize the arxiv engine
if "arxiv" in query_lower and "arxiv" in self.available_engines:
- return ["arxiv"] + [e for e in self.available_engines if e != "arxiv"]
+ return ["arxiv"] + [
+ e for e in self.available_engines if e != "arxiv"
+ ]
# For searches containing "pubmed", prioritize the pubmed engine
if "pubmed" in query_lower and "pubmed" in self.available_engines:
- return ["pubmed"] + [e for e in self.available_engines if e != "pubmed"]
+ return ["pubmed"] + [
+ e for e in self.available_engines if e != "pubmed"
+ ]
# Check if SearXNG is available and prioritize it for general queries
if "searxng" in self.available_engines:
@@ -169,7 +180,9 @@ class MetaSearchEngine(BaseSearchEngine):
]
reliability_sorted = sorted(
engines_without_searxng,
- key=lambda x: search_config().get(x, {}).get("reliability", 0),
+ key=lambda x: search_config()
+ .get(x, {})
+ .get("reliability", 0),
reverse=True,
)
return ["searxng"] + reliability_sorted
@@ -182,7 +195,9 @@ class MetaSearchEngine(BaseSearchEngine):
# Return engines sorted by reliability
return sorted(
self.available_engines,
- key=lambda x: search_config().get(x, {}).get("reliability", 0),
+ key=lambda x: search_config()
+ .get(x, {})
+ .get("reliability", 0),
reverse=True,
)
@@ -213,7 +228,9 @@ class MetaSearchEngine(BaseSearchEngine):
)
return sorted(
self.available_engines,
- key=lambda x: search_config().get(x, {}).get("reliability", 0),
+ key=lambda x: search_config()
+ .get(x, {})
+ .get("reliability", 0),
reverse=True,
)
@@ -255,7 +272,10 @@ Example output: searxng,wikipedia,brave"""
valid_engines.append(cleaned_name)
# If SearXNG is available but not selected by the LLM, add it as a fallback
- if "searxng" in self.available_engines and "searxng" not in valid_engines:
+ if (
+ "searxng" in self.available_engines
+ and "searxng" not in valid_engines
+ ):
# Add it as the last option if the LLM selected others
if valid_engines:
valid_engines.append("searxng")
@@ -267,7 +287,9 @@ Example output: searxng,wikipedia,brave"""
if not valid_engines:
valid_engines = sorted(
self.available_engines,
- key=lambda x: search_config().get(x, {}).get("reliability", 0),
+ key=lambda x: search_config()
+ .get(x, {})
+ .get("reliability", 0),
reverse=True,
)
@@ -278,13 +300,17 @@ Example output: searxng,wikipedia,brave"""
if "searxng" in self.available_engines:
return ["searxng"] + sorted(
[e for e in self.available_engines if e != "searxng"],
- key=lambda x: search_config().get(x, {}).get("reliability", 0),
+ key=lambda x: search_config()
+ .get(x, {})
+ .get("reliability", 0),
reverse=True,
)
else:
return sorted(
self.available_engines,
- key=lambda x: search_config().get(x, {}).get("reliability", 0),
+ key=lambda x: search_config()
+ .get(x, {})
+ .get("reliability", 0),
reverse=True,
)
@@ -344,7 +370,10 @@ Example output: searxng,wikipedia,brave"""
try:
SocketIOService().emit_socket_event(
"search_engine_selected",
- {"engine": engine_name, "result_count": len(previews)},
+ {
+ "engine": engine_name,
+ "result_count": len(previews),
+ },
)
except Exception:
logger.exception("Socket emit error (non-critical)")
@@ -355,7 +384,9 @@ Example output: searxng,wikipedia,brave"""
all_errors.append(f"{engine_name} returned no previews")
except Exception as e:
- error_msg = f"Error getting previews from {engine_name}: {str(e)}"
+ error_msg = (
+ f"Error getting previews from {engine_name}: {str(e)}"
+ )
logger.exception(error_msg)
all_errors.append(error_msg)
@@ -390,7 +421,9 @@ Example output: searxng,wikipedia,brave"""
# Use the selected engine to get full content
if hasattr(self, "_selected_engine"):
try:
- logger.info(f"Using {self._selected_engine_name} to get full content")
+ logger.info(
+ f"Using {self._selected_engine_name} to get full content"
+ )
return self._selected_engine._get_full_content(relevant_items)
except Exception:
logger.exception(
@@ -404,7 +437,9 @@ Example output: searxng,wikipedia,brave"""
)
return relevant_items
- def _get_engine_instance(self, engine_name: str) -> Optional[BaseSearchEngine]:
+ def _get_engine_instance(
+ self, engine_name: str
+ ) -> Optional[BaseSearchEngine]:
"""Get or create an instance of the specified search engine"""
# Return cached instance if available
if engine_name in self.engine_cache:
@@ -418,11 +453,15 @@ Example output: searxng,wikipedia,brave"""
# Add max_filtered_results if specified
if self.max_filtered_results is not None:
- common_params["max_filtered_results"] = self.max_filtered_results
+ common_params["max_filtered_results"] = (
+ self.max_filtered_results
+ )
engine = create_search_engine(engine_name, **common_params)
except Exception:
- logger.exception(f"Error creating engine instance for {engine_name}")
+ logger.exception(
+ f"Error creating engine instance for {engine_name}"
+ )
return None
if engine:
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
index 1b92ba35a1..7dd798f9ac 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
@@ -235,8 +235,12 @@ class ArXivSearchEngine(BaseSearchEngine):
):
try:
# Download the paper
- pdf_count += 1 # Increment counter before attempting download
- paper_path = paper.download_pdf(dirpath=self.download_dir)
+ pdf_count += (
+ 1 # Increment counter before attempting download
+ )
+ paper_path = paper.download_pdf(
+ dirpath=self.download_dir
+ )
result["pdf_path"] = str(paper_path)
# Extract text from PDF
@@ -267,7 +271,9 @@ class ArXivSearchEngine(BaseSearchEngine):
with pdfplumber.open(paper_path) as pdf:
pdf_text = ""
for page in pdf.pages:
- pdf_text += page.extract_text() + "\n\n"
+ pdf_text += (
+ page.extract_text() + "\n\n"
+ )
if (
pdf_text.strip()
@@ -286,9 +292,13 @@ class ArXivSearchEngine(BaseSearchEngine):
)
except Exception:
logger.exception("Error extracting text from PDF")
- logger.error("Using paper summary as content instead")
+ logger.error(
+ "Using paper summary as content instead"
+ )
except Exception:
- logger.exception(f"Error downloading paper {paper.title}")
+ logger.exception(
+ f"Error downloading paper {paper.title}"
+ )
result["pdf_path"] = None
pdf_count -= 1 # Decrement counter if download fails
elif (
@@ -401,7 +411,9 @@ class ArXivSearchEngine(BaseSearchEngine):
if self.include_full_text and self.download_dir:
try:
# Download the paper
- paper_path = paper.download_pdf(dirpath=self.download_dir)
+ paper_path = paper.download_pdf(
+ dirpath=self.download_dir
+ )
result["pdf_path"] = str(paper_path)
except Exception:
logger.exception("Error downloading paper")
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_brave.py b/src/local_deep_research/web_search_engines/engines/search_engine_brave.py
index 023e2d9bff..829347ea72 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_brave.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_brave.py
@@ -46,7 +46,9 @@ class BraveSearchEngine(BaseSearchEngine):
"""
# Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
super().__init__(
- llm=llm, max_filtered_results=max_filtered_results, max_results=max_results
+ llm=llm,
+ max_filtered_results=max_filtered_results,
+ max_results=max_results,
)
self.include_full_content = include_full_content
@@ -144,7 +146,9 @@ class BraveSearchEngine(BaseSearchEngine):
raw_results = json.loads(raw_results)
except json.JSONDecodeError:
- logger.error("Error: Unable to parse BraveSearch response as JSON.")
+ logger.error(
+ "Error: Unable to parse BraveSearch response as JSON."
+ )
return []
# Format results as previews
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py b/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py
index d408b9d2cb..01508a2df0 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py
@@ -36,7 +36,9 @@ class DuckDuckGoSearchEngine(BaseSearchEngine):
"""
# Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
super().__init__(
- llm=llm, max_filtered_results=max_filtered_results, max_results=max_results
+ llm=llm,
+ max_filtered_results=max_filtered_results,
+ max_results=max_results,
)
self.region = region
self.safe_search = safe_search
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 20156d889b..791a0ca4aa 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
@@ -1,4 +1,3 @@
-import json
import logging
from typing import Any, Dict, List, Optional
@@ -48,7 +47,9 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
"""
# Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
super().__init__(
- llm=llm, max_filtered_results=max_filtered_results, max_results=max_results
+ llm=llm,
+ max_filtered_results=max_filtered_results,
+ max_results=max_results,
)
self.index_name = index_name
@@ -85,7 +86,9 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
)
except Exception as e:
logger.error(f"Failed to connect to Elasticsearch: {str(e)}")
- raise ConnectionError(f"Could not connect to Elasticsearch: {str(e)}")
+ raise ConnectionError(
+ f"Could not connect to Elasticsearch: {str(e)}"
+ )
def _get_previews(self, query: str) -> List[Dict[str, Any]]:
"""
@@ -97,7 +100,9 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
Returns:
List of preview dictionaries
"""
- logger.info(f"Getting document previews from Elasticsearch with query: {query}")
+ logger.info(
+ f"Getting document previews from Elasticsearch with query: {query}"
+ )
try:
# Build the search query
@@ -121,7 +126,10 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
# Add filter if provided
if self.filter_query:
search_query["query"] = {
- "bool": {"must": search_query["query"], "filter": self.filter_query}
+ "bool": {
+ "must": search_query["query"],
+ "filter": self.filter_query,
+ }
}
# Execute the search
@@ -150,7 +158,9 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
# If no highlights, use a portion of the content
if not snippet and "content" in source:
content = source.get("content", "")
- snippet = content[:250] + "..." if len(content) > 250 else content
+ snippet = (
+ content[:250] + "..." if len(content) > 250 else content
+ )
# Create preview object
preview = {
@@ -165,7 +175,9 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
previews.append(preview)
- logger.info(f"Found {len(previews)} preview results from Elasticsearch")
+ logger.info(
+ f"Found {len(previews)} preview results from Elasticsearch"
+ )
return previews
except Exception as e:
@@ -218,7 +230,9 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
source = doc_response.get("_source", {})
# Add full content to the result
- result["content"] = source.get("content", result.get("snippet", ""))
+ result["content"] = source.get(
+ "content", result.get("snippet", "")
+ )
result["full_content"] = source.get("content", "")
# Add metadata from source
@@ -302,7 +316,9 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
logger.error(f"Error in DSL search: {str(e)}")
return []
- def _process_es_response(self, response: Dict[str, Any]) -> List[Dict[str, Any]]:
+ def _process_es_response(
+ self, response: Dict[str, Any]
+ ) -> List[Dict[str, Any]]:
"""
Process Elasticsearch response into preview dictionaries.
@@ -330,7 +346,9 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
# If no highlights, use a portion of the content
if not snippet and "content" in source:
content = source.get("content", "")
- snippet = content[:250] + "..." if len(content) > 250 else content
+ snippet = (
+ content[:250] + "..." if len(content) > 250 else content
+ )
# Create preview object
preview = {
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_github.py b/src/local_deep_research/web_search_engines/engines/search_engine_github.py
index 5e547a6a3b..b34262c666 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_github.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_github.py
@@ -46,7 +46,9 @@ class GitHubSearchEngine(BaseSearchEngine):
"""
# Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
super().__init__(
- llm=llm, max_filtered_results=max_filtered_results, max_results=max_results
+ llm=llm,
+ max_filtered_results=max_filtered_results,
+ max_results=max_results,
)
self.api_key = api_key or os.getenv("GITHUB_API_KEY")
self.search_type = search_type
@@ -224,7 +226,9 @@ class GitHubSearchEngine(BaseSearchEngine):
# If no results, try to provide more guidance
if not results:
- logger.warning("No results found. Consider these search tips:")
+ logger.warning(
+ "No results found. Consider these search tips:"
+ )
logger.warning("1. Use shorter, more specific queries")
logger.warning(
"2. For repositories, try adding 'stars:>100' or 'language:python'"
@@ -255,7 +259,8 @@ class GitHubSearchEngine(BaseSearchEngine):
try:
# Get README
response = requests.get(
- f"{self.api_base}/repos/{repo_full_name}/readme", headers=self.headers
+ f"{self.api_base}/repos/{repo_full_name}/readme",
+ headers=self.headers,
)
# Check for rate limiting
@@ -267,7 +272,9 @@ class GitHubSearchEngine(BaseSearchEngine):
encoding = data.get("encoding", "")
if encoding == "base64" and content:
- return base64.b64decode(content).decode("utf-8", errors="replace")
+ return base64.b64decode(content).decode(
+ "utf-8", errors="replace"
+ )
return content
else:
logger.warning(
@@ -312,7 +319,9 @@ class GitHubSearchEngine(BaseSearchEngine):
if response.status_code == 200:
issues = response.json()
- logger.info(f"Got {len(issues)} recent issues for {repo_full_name}")
+ logger.info(
+ f"Got {len(issues)} recent issues for {repo_full_name}"
+ )
else:
logger.warning(
f"Could not get issues for {repo_full_name}: {response.status_code}"
@@ -346,17 +355,23 @@ class GitHubSearchEngine(BaseSearchEngine):
encoding = data.get("encoding", "")
if encoding == "base64" and content:
- return base64.b64decode(content).decode("utf-8", errors="replace")
+ return base64.b64decode(content).decode(
+ "utf-8", errors="replace"
+ )
return content
else:
- logger.warning(f"Could not get file content: {response.status_code}")
+ logger.warning(
+ f"Could not get file content: {response.status_code}"
+ )
return ""
except Exception as e:
logger.error(f"Error getting file content: {e}")
return ""
- def _format_repository_preview(self, repo: Dict[str, Any]) -> Dict[str, Any]:
+ def _format_repository_preview(
+ self, repo: Dict[str, Any]
+ ) -> Dict[str, Any]:
"""Format repository search result as preview"""
return {
"id": str(repo.get("id", "")),
@@ -393,7 +408,9 @@ class GitHubSearchEngine(BaseSearchEngine):
def _format_issue_preview(self, issue: Dict[str, Any]) -> Dict[str, Any]:
"""Format issue search result as preview"""
repo = (
- issue.get("repository", {}) if "repository" in issue else {"full_name": ""}
+ issue.get("repository", {})
+ if "repository" in issue
+ else {"full_name": ""}
)
return {
"id": f"issue_{issue.get('number', '')}",
@@ -503,7 +520,9 @@ class GitHubSearchEngine(BaseSearchEngine):
keywords[:5]
) # Add up to 5 keywords
- logger.info(f"Using specialized contribution query: {specialized_query}")
+ logger.info(
+ f"Using specialized contribution query: {specialized_query}"
+ )
# Perform GitHub search with specialized query
results = self._search_github(specialized_query)
@@ -560,7 +579,9 @@ class GitHubSearchEngine(BaseSearchEngine):
logger.info("Snippet-only mode, skipping full content retrieval")
return relevant_items
- logger.info(f"Getting full content for {len(relevant_items)} GitHub results")
+ logger.info(
+ f"Getting full content for {len(relevant_items)} GitHub results"
+ )
results = []
for item in relevant_items:
@@ -610,7 +631,10 @@ class GitHubSearchEngine(BaseSearchEngine):
f"Public repositories: {item.get('public_repos', 0)}\n"
)
- if item.get("snippet") and item.get("snippet") != "No bio provided":
+ if (
+ item.get("snippet")
+ and item.get("snippet") != "No bio provided"
+ ):
profile_summary += f"\nBio: {item.get('snippet')}\n"
result["full_content"] = profile_summary
@@ -620,7 +644,9 @@ class GitHubSearchEngine(BaseSearchEngine):
return results
- def search_repository(self, repo_owner: str, repo_name: str) -> Dict[str, Any]:
+ def search_repository(
+ self, repo_owner: str, repo_name: str
+ ) -> Dict[str, Any]:
"""
Get detailed information about a specific repository.
@@ -672,7 +698,10 @@ class GitHubSearchEngine(BaseSearchEngine):
return {}
def search_code(
- self, query: str, language: Optional[str] = None, user: Optional[str] = None
+ self,
+ query: str,
+ language: Optional[str] = None,
+ user: Optional[str] = None,
) -> List[Dict[str, Any]]:
"""
Search for code with more specific parameters.
@@ -769,7 +798,9 @@ class GitHubSearchEngine(BaseSearchEngine):
results = data.get("items", [])
# Format results
- previews = [self._format_issue_preview(result) for result in results]
+ previews = [
+ self._format_issue_preview(result) for result in results
+ ]
# For issues, we don't need to get full content
return previews
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.py
index 143bf89c44..ea95e39248 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
@@ -51,7 +51,9 @@ class GooglePSESearchEngine(BaseSearchEngine):
"""
# Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
super().__init__(
- llm=llm, max_filtered_results=max_filtered_results, max_results=max_results
+ llm=llm,
+ max_filtered_results=max_filtered_results,
+ max_results=max_results,
)
self.include_full_content = include_full_content
@@ -61,7 +63,9 @@ class GooglePSESearchEngine(BaseSearchEngine):
# Rate limiting - keep track of last request time
self.last_request_time = 0
- self.min_request_interval = 0.5 # Minimum time between requests in seconds
+ self.min_request_interval = (
+ 0.5 # Minimum time between requests in seconds
+ )
# Language code mapping
language_code_mapping = {
@@ -92,7 +96,9 @@ class GooglePSESearchEngine(BaseSearchEngine):
self.api_key = api_key
if not self.api_key:
- self.api_key = get_db_setting("search.engine.web.google_pse.api_key")
+ self.api_key = get_db_setting(
+ "search.engine.web.google_pse.api_key"
+ )
self.search_engine_id = search_engine_id
if not self.search_engine_id:
@@ -187,7 +193,9 @@ class GooglePSESearchEngine(BaseSearchEngine):
# Add jitter to retries after the first attempt
if attempt > 0:
jitter = random.uniform(0.5, 1.5)
- sleep_time = self.retry_delay * (2 ** (attempt - 1)) * jitter
+ sleep_time = (
+ self.retry_delay * (2 ** (attempt - 1)) * jitter
+ )
logger.info(
"Retry attempt %s / %s for query '%s'. Waiting %s s",
attempt + 1,
@@ -296,7 +304,9 @@ class GooglePSESearchEngine(BaseSearchEngine):
logger.error("Error getting search results: %s", str(e))
break
- logger.info("Retrieved %s search results for query: '%s'", len(results), query)
+ logger.info(
+ "Retrieved %s search results for query: '%s'", len(results), query
+ )
return results
def _get_full_content(
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py b/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py
index 937c973961..93a121daae 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py
@@ -48,7 +48,9 @@ class GuardianSearchEngine(BaseSearchEngine):
"""
# Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
super().__init__(
- llm=llm, max_filtered_results=max_filtered_results, max_results=max_results
+ llm=llm,
+ max_filtered_results=max_filtered_results,
+ max_results=max_results,
)
self.api_key = api_key or os.getenv("GUARDIAN_API_KEY")
self.optimize_queries = optimize_queries
@@ -204,15 +206,19 @@ ONE WORD ONLY:"""
logger.info(
"Query classified as HISTORICAL - extending search timeframe"
)
- ten_years_ago = (datetime.now() - timedelta(days=3650)).strftime(
- "%Y-%m-%d"
- )
+ ten_years_ago = (
+ datetime.now() - timedelta(days=3650)
+ ).strftime("%Y-%m-%d")
self.from_date = ten_years_ago
elif "CURRENT" in answer:
# For current events, focus on recent content
- logger.info("Query classified as CURRENT - focusing on recent content")
- recent = (datetime.now() - timedelta(days=60)).strftime("%Y-%m-%d")
+ logger.info(
+ "Query classified as CURRENT - focusing on recent content"
+ )
+ recent = (datetime.now() - timedelta(days=60)).strftime(
+ "%Y-%m-%d"
+ )
self.from_date = recent
self.order_by = "newest" # Prioritize newest for current events
@@ -246,7 +252,9 @@ ONE WORD ONLY:"""
# Strategy 1: Expand to 6 months
logger.info("Strategy 1: Expanding time range to 6 months")
- six_months_ago = (datetime.now() - timedelta(days=180)).strftime("%Y-%m-%d")
+ six_months_ago = (datetime.now() - timedelta(days=180)).strftime(
+ "%Y-%m-%d"
+ )
self.from_date = six_months_ago
articles1 = self._get_all_data(query)
@@ -256,7 +264,9 @@ ONE WORD ONLY:"""
# Strategy 2: Expand to all time and try relevance order
if len(articles) < 3:
- logger.info("Strategy 2: Expanding to all time with relevance ordering")
+ logger.info(
+ "Strategy 2: Expanding to all time with relevance ordering"
+ )
self.from_date = "2000-01-01" # Effectively "all time"
self.order_by = "relevance"
@@ -315,12 +325,15 @@ ONE WORD ONLY:"""
# Always request all fields for simplicity
# Ensure max_results is an integer to avoid comparison errors
page_size = min(
- int(self.max_results) if self.max_results is not None else 10, 50
+ int(self.max_results) if self.max_results is not None else 10,
+ 50,
)
# Log full parameters for debugging
logger.info(f"Guardian API search query: '{query}'")
- logger.info(f"Guardian API date range: {self.from_date} to {self.to_date}")
+ logger.info(
+ f"Guardian API date range: {self.from_date} to {self.to_date}"
+ )
params = {
"q": query,
@@ -363,7 +376,9 @@ ONE WORD ONLY:"""
# Format the article with all fields
result = {
"id": article.get("id", ""),
- "title": fields.get("headline", article.get("webTitle", "")),
+ "title": fields.get(
+ "headline", article.get("webTitle", "")
+ ),
"link": article.get("webUrl", ""),
"snippet": fields.get("trailText", ""),
"publication_date": article.get("webPublicationDate", ""),
@@ -399,7 +414,9 @@ ONE WORD ONLY:"""
Returns:
List of preview dictionaries
"""
- logger.info(f"Getting articles from The Guardian API for query: {query}")
+ logger.info(
+ f"Getting articles from The Guardian API for query: {query}"
+ )
# Step 1: Optimize the query using LLM
optimized_query = self._optimize_query_for_guardian(query)
@@ -471,7 +488,10 @@ ONE WORD ONLY:"""
article_id = item.get("id", "")
# Get the full article from our cache
- if hasattr(self, "_full_articles") and article_id in self._full_articles:
+ if (
+ hasattr(self, "_full_articles")
+ and article_id in self._full_articles
+ ):
results.append(self._full_articles[article_id])
else:
# If not found (shouldn't happen), just use the preview
@@ -502,7 +522,9 @@ ONE WORD ONLY:"""
# If no results, try one more time with a simplified query
if not previews:
- simple_query = " ".join([w for w in query.split() if len(w) > 3][:3])
+ simple_query = " ".join(
+ [w for w in query.split() if len(w) > 3][:3]
+ )
logger.warning(
f"No Guardian articles found, trying simplified query: {simple_query}"
)
@@ -518,7 +540,9 @@ ONE WORD ONLY:"""
# If still no results after all attempts, return empty list
if not previews:
- logger.warning("No Guardian articles found after multiple attempts")
+ logger.warning(
+ "No Guardian articles found after multiple attempts"
+ )
return []
# Filter for relevance if we have an LLM
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_local.py b/src/local_deep_research/web_search_engines/engines/search_engine_local.py
index d5739f7cea..ecc3a1a258 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_local.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_local.py
@@ -56,7 +56,9 @@ def _get_file_loader(file_path: str) -> Optional[BaseLoader]:
return UnstructuredExcelLoader(str(file_path))
else:
# Try the text loader as a fallback for unknown extensions
- logger.warning(f"Unknown file extension for {file_path}, trying TextLoader")
+ logger.warning(
+ f"Unknown file extension for {file_path}, trying TextLoader"
+ )
return TextLoader(str(file_path), encoding="utf-8")
except Exception:
logger.exception(f"Error creating loader for {file_path}")
@@ -208,7 +210,9 @@ class LocalEmbeddingManager:
# Check if vector store exists and is up to date
if vector_store_path.exists() and not self._check_folders_modified():
- logger.info(f"Loading existing vector store from {vector_store_path}")
+ logger.info(
+ f"Loading existing vector store from {vector_store_path}"
+ )
try:
vector_store = FAISS.load_local(
str(vector_store_path),
@@ -306,9 +310,13 @@ class LocalEmbeddingManager:
last_indexed = 0
indexed_files = set()
else:
- last_indexed = self.indexed_folders[folder_hash].get("last_indexed", 0)
+ last_indexed = self.indexed_folders[folder_hash].get(
+ "last_indexed", 0
+ )
indexed_files = (
- self.indexed_folders[folder_hash].get("indexed_files", {}).keys()
+ self.indexed_folders[folder_hash]
+ .get("indexed_files", {})
+ .keys()
)
# Check if any file in the folder has been modified since last indexing
@@ -345,11 +353,15 @@ class LocalEmbeddingManager:
self.chunk_overlap,
self.embedding_model,
):
- logger.info("Embedding configuration has changed, re-indexing folder.")
+ logger.info(
+ "Embedding configuration has changed, re-indexing folder."
+ )
return True
return False
- def index_folder(self, folder_path: str, force_reindex: bool = False) -> bool:
+ def index_folder(
+ self, folder_path: str, force_reindex: bool = False
+ ) -> bool:
"""
Index all documents in a folder for vector search.
@@ -434,7 +446,9 @@ class LocalEmbeddingManager:
# Split documents into chunks
logger.info(f"Splitting {len(all_docs)} documents into chunks")
splits = self.text_splitter.split_documents(all_docs)
- logger.info(f"Created {len(splits)} chunks from {len(modified_files)} files")
+ logger.info(
+ f"Created {len(splits)} chunks from {len(modified_files)} files"
+ )
# Create vector store
ids = []
@@ -448,10 +462,14 @@ class LocalEmbeddingManager:
indexed_files = {}
if folder_hash in self.indexed_folders:
indexed_files = (
- self.indexed_folders[folder_hash].get("indexed_files", {}).copy()
+ self.indexed_folders[folder_hash]
+ .get("indexed_files", {})
+ .copy()
)
for split_id, split in zip(ids, splits):
- split_source = str(Path(split.metadata["source"]).relative_to(folder_path))
+ split_source = str(
+ Path(split.metadata["source"]).relative_to(folder_path)
+ )
id_list = indexed_files.setdefault(split_source, [])
id_list.append(split_id)
@@ -465,7 +483,8 @@ class LocalEmbeddingManager:
delete_paths.append(relative_path)
if delete_ids:
logger.info(
- f"Deleting {len(delete_paths)} non-existent files from the " f"index."
+ f"Deleting {len(delete_paths)} non-existent files from the "
+ f"index."
)
self.vector_stores[folder_hash].delete(delete_ids)
for path in delete_paths:
@@ -543,7 +562,9 @@ class LocalEmbeddingManager:
if path.exists() and path.is_dir():
valid_folder_paths.append(path)
else:
- logger.warning(f"Skipping non-existent folder in search: {path}")
+ logger.warning(
+ f"Skipping non-existent folder in search: {path}"
+ )
# If no valid folders, return empty results
if not valid_folder_paths:
@@ -578,8 +599,10 @@ class LocalEmbeddingManager:
vector_store = self.vector_stores[folder_hash]
try:
- docs_with_scores = vector_store.similarity_search_with_relevance_scores(
- query, k=limit
+ docs_with_scores = (
+ vector_store.similarity_search_with_relevance_scores(
+ query, k=limit
+ )
)
for doc, similarity in docs_with_scores:
@@ -685,7 +708,9 @@ class LocalSearchEngine(BaseSearchEngine):
if os.path.exists(path) and os.path.isdir(path):
self.valid_folder_paths.append(path)
else:
- logger.warning(f"Folder not found or is not a directory: {path}")
+ logger.warning(
+ f"Folder not found or is not a directory: {path}"
+ )
# If no valid folders, log a clear message
if not self.valid_folder_paths and paths:
@@ -768,7 +793,9 @@ class LocalSearchEngine(BaseSearchEngine):
if name in self.collections
}
if not collections_to_search:
- logger.warning(f"No valid collections found among: {collection_names}")
+ logger.warning(
+ f"No valid collections found among: {collection_names}"
+ )
return []
else:
# Search in all collections
@@ -811,13 +838,13 @@ class LocalSearchEngine(BaseSearchEngine):
previews = []
for i, result in enumerate(raw_results):
# Create a unique ID
- result_id = (
- f"local-{i}-{hashlib.md5(result['content'][:50].encode()).hexdigest()}"
- )
+ result_id = f"local-{i}-{hashlib.md5(result['content'][:50].encode()).hexdigest()}"
# Extract filename and path
source_path = result["metadata"].get("source", "Unknown")
- filename = result["metadata"].get("filename", os.path.basename(source_path))
+ filename = result["metadata"].get(
+ "filename", os.path.basename(source_path)
+ )
# Create preview snippet (first ~200 chars of content)
snippet = (
@@ -845,10 +872,12 @@ class LocalSearchEngine(BaseSearchEngine):
"similarity": result["similarity"],
"folder": folder_path.as_posix(),
"collection": collection_name,
- "collection_description": self.collections.get(collection_name, {}).get(
- "description", ""
- ),
- "_full_content": result["content"], # Store full content for later
+ "collection_description": self.collections.get(
+ collection_name, {}
+ ).get("description", ""),
+ "_full_content": result[
+ "content"
+ ], # Store full content for later
"_metadata": result["metadata"], # Store metadata for later
}
@@ -933,7 +962,9 @@ class LocalSearchEngine(BaseSearchEngine):
if collection_name in self.collections:
specified_collections.append(collection_name)
# Remove this part from the query
- remaining_query = remaining_query.replace(part, "", 1).strip()
+ remaining_query = remaining_query.replace(
+ part, "", 1
+ ).strip()
# If collections were specified in the query, they override the parameter
if specified_collections:
@@ -1047,7 +1078,9 @@ class LocalSearchEngine(BaseSearchEngine):
success = True
for path in paths:
- if not self.embedding_manager.index_folder(path, force_reindex=True):
+ if not self.embedding_manager.index_folder(
+ path, force_reindex=True
+ ):
success = False
return success
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_local_all.py b/src/local_deep_research/web_search_engines/engines/search_engine_local_all.py
index a7fd374513..0dce0ebc1b 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_local_all.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_local_all.py
@@ -37,7 +37,9 @@ class LocalAllSearchEngine(BaseSearchEngine):
"""
# Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
super().__init__(
- llm=llm, max_filtered_results=max_filtered_results, max_results=max_results
+ llm=llm,
+ max_filtered_results=max_filtered_results,
+ max_results=max_results,
)
# Find all local collection search engines
@@ -76,7 +78,9 @@ class LocalAllSearchEngine(BaseSearchEngine):
Returns:
List of preview dictionaries
"""
- logger.info(f"Searching across all local collections for query: {query}")
+ logger.info(
+ f"Searching across all local collections for query: {query}"
+ )
all_previews = []
@@ -91,18 +95,24 @@ class LocalAllSearchEngine(BaseSearchEngine):
for preview in previews:
preview["collection_id"] = collection_id
preview["collection_name"] = engine_info["name"]
- preview["collection_description"] = engine_info["description"]
+ preview["collection_description"] = engine_info[
+ "description"
+ ]
all_previews.extend(previews)
except Exception:
- logger.exception(f"Error searching collection '{collection_id}'")
+ logger.exception(
+ f"Error searching collection '{collection_id}'"
+ )
if not all_previews:
logger.info(f"No local documents found for query: {query}")
return []
# Sort by similarity score if available
- all_previews.sort(key=lambda x: float(x.get("similarity", 0)), reverse=True)
+ all_previews.sort(
+ key=lambda x: float(x.get("similarity", 0)), reverse=True
+ )
# Limit to max_results
return all_previews[: self.max_results]
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.py
index e13b206845..24ec313b07 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
@@ -49,7 +49,9 @@ class PubMedSearchEngine(BaseSearchEngine):
"""
# Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
super().__init__(
- llm=llm, max_filtered_results=max_filtered_results, max_results=max_results
+ llm=llm,
+ max_filtered_results=max_filtered_results,
+ max_results=max_results,
)
self.max_results = max(self.max_results, 25)
self.api_key = api_key
@@ -100,7 +102,9 @@ class PubMedSearchEngine(BaseSearchEngine):
data = response.json()
count = int(data["esearchresult"]["count"])
- logger.info("Query '%s' has %s total results in PubMed", query, count)
+ logger.info(
+ "Query '%s' has %s total results in PubMed", query, count
+ )
return count
except Exception as e:
@@ -119,10 +123,14 @@ class PubMedSearchEngine(BaseSearchEngine):
"""
# Remove field specifications and operators
simplified = re.sub(r"\[\w+\]", "", query) # Remove [Field] tags
- simplified = re.sub(r"\b(AND|OR|NOT)\b", "", simplified) # Remove operators
+ simplified = re.sub(
+ r"\b(AND|OR|NOT)\b", "", simplified
+ ) # Remove operators
# Remove quotes and parentheses
- simplified = simplified.replace('"', "").replace("(", "").replace(")", "")
+ simplified = (
+ simplified.replace('"', "").replace("(", "").replace(")", "")
+ )
# Split by whitespace and join terms with 4+ chars (likely meaningful)
terms = [term for term in simplified.split() if len(term) >= 4]
@@ -220,7 +228,9 @@ Return ONLY the search query without any explanations.
optimized_query = cleaned_lines[0]
# Remove any quotes that wrap the entire query
- if optimized_query.startswith('"') and optimized_query.endswith('"'):
+ if optimized_query.startswith('"') and optimized_query.endswith(
+ '"'
+ ):
optimized_query = optimized_query[1:-1]
# Remove any explanation phrases that might be at the beginning
@@ -235,7 +245,9 @@ Return ONLY the search query without any explanations.
# Find the actual query part - typically after a colon
colon_pos = optimized_query.find(":")
if colon_pos > 0:
- optimized_query = optimized_query[colon_pos + 1 :].strip()
+ optimized_query = optimized_query[
+ colon_pos + 1 :
+ ].strip()
# Check if the query still seems to contain explanations
if (
@@ -262,12 +274,16 @@ Return ONLY the search query without any explanations.
optimized_query = " ".join(query_parts)
else:
# Fall back to original query if cleaning fails
- logger.warning("Failed to extract a clean query from LLM response")
+ logger.warning(
+ "Failed to extract a clean query from LLM response"
+ )
optimized_query = query
# Final safety check - if query looks too much like an explanation, use original
if len(optimized_query.split()) > 30:
- logger.warning("Query too verbose, falling back to simpler form")
+ logger.warning(
+ "Query too verbose, falling back to simpler form"
+ )
# Create a simple query from the original
words = [
w
@@ -389,7 +405,9 @@ Return ONLY the search query without any explanations.
historical_years = [str(year) for year in range(1900, 2020)]
query_lower = query.lower()
- has_historical_term = any(term in query_lower for term in historical_terms)
+ has_historical_term = any(
+ term in query_lower for term in historical_terms
+ )
has_past_year = any(year in query for year in historical_years)
return has_historical_term or has_past_year
@@ -504,7 +522,9 @@ The default assumption should be that medical and scientific queries want RECENT
strategy = "no_time_filter"
else:
# Historical query - run without time filter
- logger.info("Using historical search strategy without date filtering")
+ logger.info(
+ "Using historical search strategy without date filtering"
+ )
results = self._search_pubmed(query)
return results, strategy
@@ -546,14 +566,18 @@ The default assumption should be that medical and scientific queries want RECENT
data = response.json()
id_list = data["esearchresult"]["idlist"]
- logger.info(f"PubMed search for '{query}' found {len(id_list)} results")
+ logger.info(
+ f"PubMed search for '{query}' found {len(id_list)} results"
+ )
return id_list
except Exception as e:
logger.error(f"Error searching PubMed: {e}")
return []
- def _get_article_summaries(self, id_list: List[str]) -> List[Dict[str, Any]]:
+ def _get_article_summaries(
+ self, id_list: List[str]
+ ) -> List[Dict[str, Any]]:
"""
Get summaries for a list of PubMed article IDs.
@@ -594,7 +618,9 @@ The default assumption should be that medical and scientific queries want RECENT
# Extract authors (if available)
authors = []
if "authors" in article:
- authors = [author["name"] for author in article["authors"]]
+ authors = [
+ author["name"] for author in article["authors"]
+ ]
# Create summary dictionary
summary = {
@@ -742,7 +768,9 @@ The default assumption should be that medical and scientific queries want RECENT
if pmcids:
pmid_to_pmcid[str(pmid)] = f"PMC{pmcids[0]}"
- logger.info(f"Found {len(pmid_to_pmcid)} PMC IDs for full-text access")
+ logger.info(
+ f"Found {len(pmid_to_pmcid)} PMC IDs for full-text access"
+ )
return pmid_to_pmcid
except Exception as e:
@@ -761,7 +789,12 @@ The default assumption should be that medical and scientific queries want RECENT
"""
try:
# Prepare parameters
- params = {"db": "pmc", "id": pmcid, "retmode": "xml", "rettype": "full"}
+ params = {
+ "db": "pmc",
+ "id": pmcid,
+ "retmode": "xml",
+ "rettype": "full",
+ }
# Add API key if available
if self.api_key:
@@ -832,13 +865,17 @@ The default assumption should be that medical and scientific queries want RECENT
# If no results, try a simplified query
if not pmid_list:
- logger.warning(f"No PubMed results found using strategy: {strategy}")
+ logger.warning(
+ f"No PubMed results found using strategy: {strategy}"
+ )
simplified_query = self._simplify_query(optimized_query)
if simplified_query != optimized_query:
logger.info(f"Trying with simplified query: {simplified_query}")
pmid_list, strategy = self._adaptive_search(simplified_query)
if pmid_list:
- logger.info(f"Simplified query found {len(pmid_list)} results")
+ logger.info(
+ f"Simplified query found {len(pmid_list)} results"
+ )
if not pmid_list:
logger.warning("No PubMed results found after query simplification")
@@ -876,7 +913,9 @@ The default assumption should be that medical and scientific queries want RECENT
previews.append(preview)
- logger.info(f"Found {len(previews)} PubMed previews using strategy: {strategy}")
+ logger.info(
+ f"Found {len(previews)} PubMed previews using strategy: {strategy}"
+ )
return previews
def _get_full_content(
@@ -900,7 +939,9 @@ The default assumption should be that medical and scientific queries want RECENT
logger.info("Snippet-only mode, skipping full content retrieval")
return relevant_items
- logger.info(f"Getting content for {len(relevant_items)} PubMed articles")
+ logger.info(
+ f"Getting content for {len(relevant_items)} PubMed articles"
+ )
# Collect all PMIDs for relevant items
pmids = []
@@ -938,10 +979,11 @@ The default assumption should be that medical and scientific queries want RECENT
if (
pmid in pmid_to_pmcid
and self.get_full_text
- and len([r for r in results if r.get("content_type") == "full_text"])
+ and len(
+ [r for r in results if r.get("content_type") == "full_text"]
+ )
< self.full_text_limit
):
-
# Get full text content
pmcid = pmid_to_pmcid[pmid]
full_text = self._get_pmc_full_text(pmcid)
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py
index 987976bf43..58b4e999a4 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py
@@ -63,12 +63,16 @@ class SearXNGSearchEngine(BaseSearchEngine):
# Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
super().__init__(
- llm=llm, max_filtered_results=max_filtered_results, max_results=max_results
+ llm=llm,
+ max_filtered_results=max_filtered_results,
+ max_results=max_results,
)
# Validate and normalize the instance URL if provided
self.instance_url = instance_url.rstrip("/")
- logger.info(f"SearXNG initialized with instance URL: {self.instance_url}")
+ logger.info(
+ f"SearXNG initialized with instance URL: {self.instance_url}"
+ )
try:
# Make sure it's accessible.
response = requests.get(self.instance_url, timeout=5)
@@ -213,7 +217,9 @@ class SearXNGSearchEngine(BaseSearchEngine):
"Upgrade-Insecure-Requests": "1",
}
- logger.info(f"Sending request to SearXNG instance at {self.instance_url}")
+ logger.info(
+ f"Sending request to SearXNG instance at {self.instance_url}"
+ )
response = requests.get(
self.search_url,
params=params,
@@ -243,7 +249,9 @@ class SearXNGSearchEngine(BaseSearchEngine):
)
result_elements = soup.select('div[id^="result"]')
- logger.info(f"Found {len(result_elements)} search result elements")
+ logger.info(
+ f"Found {len(result_elements)} search result elements"
+ )
for idx, result_element in enumerate(result_elements):
if idx >= self.max_results:
@@ -270,7 +278,9 @@ class SearXNGSearchEngine(BaseSearchEngine):
)
title = (
- title_element.get_text(strip=True) if title_element else ""
+ title_element.get_text(strip=True)
+ if title_element
+ else ""
)
url = ""
@@ -285,7 +295,11 @@ class SearXNGSearchEngine(BaseSearchEngine):
else ""
)
- if not url and title_element and title_element.has_attr("href"):
+ if (
+ not url
+ and title_element
+ and title_element.has_attr("href")
+ ):
url = title_element["href"]
logger.debug(
@@ -316,7 +330,9 @@ class SearXNGSearchEngine(BaseSearchEngine):
logger.exception("Error parsing HTML results")
return []
else:
- logger.error(f"SearXNG returned status code {response.status_code}")
+ logger.error(
+ f"SearXNG returned status code {response.status_code}"
+ )
return []
except Exception:
@@ -334,7 +350,9 @@ class SearXNGSearchEngine(BaseSearchEngine):
List of preview dictionaries
"""
if not self.is_available:
- logger.warning("SearXNG engine is disabled (no instance URL provided)")
+ logger.warning(
+ "SearXNG engine is disabled (no instance URL provided)"
+ )
return []
logger.info(f"Getting SearXNG previews for query: {query}")
@@ -389,7 +407,9 @@ class SearXNGSearchEngine(BaseSearchEngine):
logger.info("Retrieving full webpage content")
try:
- results_with_content = self.full_search._get_full_content(relevant_items)
+ results_with_content = self.full_search._get_full_content(
+ relevant_items
+ )
return results_with_content
except Exception:
diff --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.py
index 7e08b75d60..81bfd68ecb 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
@@ -66,7 +66,9 @@ class SemanticScholarSearchEngine(BaseSearchEngine):
"""
# Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
super().__init__(
- llm=llm, max_filtered_results=max_filtered_results, max_results=max_results
+ llm=llm,
+ max_filtered_results=max_filtered_results,
+ max_results=max_results,
)
self.api_key = api_key
@@ -157,7 +159,9 @@ class SemanticScholarSearchEngine(BaseSearchEngine):
if method.upper() == "GET":
response = self.session.get(url, params=params, timeout=30)
elif method.upper() == "POST":
- response = self.session.post(url, params=params, json=data, timeout=30)
+ response = self.session.post(
+ url, params=params, json=data, timeout=30
+ )
else:
raise ValueError(f"Unsupported HTTP method: {method}")
@@ -165,7 +169,9 @@ class SemanticScholarSearchEngine(BaseSearchEngine):
if response.status_code == 429:
logger.warning("Rate limit exceeded, waiting and retrying...")
time.sleep(2.0) # Wait longer on rate limit
- self.rate_limit_wait *= 1.5 # Increase wait time for future requests
+ self.rate_limit_wait *= (
+ 1.5 # Increase wait time for future requests
+ )
return self._make_request(url, params, data, method) # Retry
response.raise_for_status()
@@ -258,7 +264,9 @@ Return ONLY the optimized search query with no explanation.
params = {
"query": query,
- "limit": min(self.max_results, 100), # API limit is 100 per request
+ "limit": min(
+ self.max_results, 100
+ ), # API limit is 100 per request
"fields": ",".join(fields),
}
@@ -351,15 +359,21 @@ Format each query on a new line with no numbering or explanation. Keep each quer
): # Handle various LLM response formats
content = response.content
alt_queries = [
- q.strip() for q in content.strip().split("\n") if q.strip()
+ q.strip()
+ for q in content.strip().split("\n")
+ if q.strip()
]
elif isinstance(response, str):
alt_queries = [
- q.strip() for q in response.strip().split("\n") if q.strip()
+ q.strip()
+ for q in response.strip().split("\n")
+ if q.strip()
]
# Try each alternative query
- for alt_query in alt_queries[:3]: # Limit to first 3 alternatives
+ for alt_query in alt_queries[
+ :3
+ ]: # Limit to first 3 alternatives
logger.info("Trying LLM-suggested query: %s", alt_query)
alt_papers = self._direct_search(alt_query)
@@ -495,7 +509,9 @@ Format each query on a new line with no numbering or explanation. Keep each quer
snippet = ""
if abstract:
snippet = (
- abstract[:250] + "..." if len(abstract) > 250 else abstract
+ abstract[:250] + "..."
+ if len(abstract) > 250
+ else abstract
)
venue = paper.get("venue", "")
@@ -597,7 +613,9 @@ Format each query on a new line with no numbering or explanation. Keep each quer
# Add fields of study
if "fieldsOfStudy" in paper_details:
- result["fields_of_study"] = paper_details["fieldsOfStudy"]
+ result["fields_of_study"] = paper_details[
+ "fieldsOfStudy"
+ ]
# Remove temporary fields
if "_paper_id" in result:
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py b/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py
index 5ac7447515..4626e4a5f3 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py
@@ -45,7 +45,9 @@ class SerpAPISearchEngine(BaseSearchEngine):
"""
# Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
super().__init__(
- llm=llm, max_filtered_results=max_filtered_results, max_results=max_results
+ llm=llm,
+ max_filtered_results=max_filtered_results,
+ max_results=max_results,
)
self.include_full_content = include_full_content
@@ -68,7 +70,9 @@ class SerpAPISearchEngine(BaseSearchEngine):
serpapi_api_key = api_key
if not serpapi_api_key:
- serpapi_api_key = get_db_setting("search.engine.web.serpapi.api_key")
+ serpapi_api_key = get_db_setting(
+ "search.engine.web.serpapi.api_key"
+ )
if not serpapi_api_key:
raise ValueError(
@@ -126,13 +130,17 @@ class SerpAPISearchEngine(BaseSearchEngine):
try:
# Get search results from SerpAPI
- organic_results = self.engine.results(query).get("organic_results", [])
+ organic_results = self.engine.results(query).get(
+ "organic_results", []
+ )
# Format results as previews
previews = []
for result in organic_results:
preview = {
- "id": result.get("position", len(previews)), # Use position as ID
+ "id": result.get(
+ "position", len(previews)
+ ), # Use position as ID
"title": result.get("title", ""),
"link": result.get("link", ""),
"snippet": result.get("snippet", ""),
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py b/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py
index bc09ef2e97..2921d3762c 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py
@@ -43,7 +43,9 @@ class WaybackSearchEngine(BaseSearchEngine):
"""
# Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
super().__init__(
- llm=llm, max_filtered_results=max_filtered_results, max_results=max_results
+ llm=llm,
+ max_filtered_results=max_filtered_results,
+ max_results=max_results,
)
self.max_snapshots_per_url = max_snapshots_per_url
self.language = language
@@ -79,7 +81,9 @@ class WaybackSearchEngine(BaseSearchEngine):
return [f"http://{query}"]
# For non-URL queries, use DuckDuckGo to find relevant URLs
- logger.info("Query is not a URL, using DuckDuckGo to find relevant URLs")
+ logger.info(
+ "Query is not a URL, using DuckDuckGo to find relevant URLs"
+ )
try:
# Import DuckDuckGo search engine
from langchain_community.utilities import DuckDuckGoSearchAPIWrapper
@@ -91,9 +95,13 @@ class WaybackSearchEngine(BaseSearchEngine):
results = ddg.results(query, url_search_limit)
# Extract URLs from results
- ddg_urls = [result.get("link") for result in results if result.get("link")]
+ ddg_urls = [
+ result.get("link") for result in results if result.get("link")
+ ]
if ddg_urls:
- logger.info(f"Found {len(ddg_urls)} URLs from DuckDuckGo search")
+ logger.info(
+ f"Found {len(ddg_urls)} URLs from DuckDuckGo search"
+ )
return ddg_urls
except Exception as e:
logger.error(f"Error using DuckDuckGo for URL discovery: {e}")
@@ -185,12 +193,16 @@ class WaybackSearchEngine(BaseSearchEngine):
snapshot = dict(zip(headers, item))
timestamp = snapshot.get("timestamp", "")
- wayback_url = f"https://web.archive.org/web/{timestamp}/{url}"
+ wayback_url = (
+ f"https://web.archive.org/web/{timestamp}/{url}"
+ )
snapshots.append(
{
"timestamp": timestamp,
- "formatted_date": self._format_timestamp(timestamp),
+ "formatted_date": self._format_timestamp(
+ timestamp
+ ),
"url": wayback_url,
"original_url": url,
"available": True,
@@ -265,8 +277,12 @@ class WaybackSearchEngine(BaseSearchEngine):
if not html or not html.strip():
return ""
try:
- paragraphs = justext.justext(html, justext.get_stoplist(self.language))
- cleaned = "\n".join([p.text for p in paragraphs if not p.is_boilerplate])
+ paragraphs = justext.justext(
+ html, justext.get_stoplist(self.language)
+ )
+ cleaned = "\n".join(
+ [p.text for p in paragraphs if not p.is_boilerplate]
+ )
return cleaned
except Exception as e:
logger.error(f"Error removing boilerplate: {e}")
@@ -471,7 +487,10 @@ class WaybackSearchEngine(BaseSearchEngine):
response = requests.get(self.available_api, params={"url": url})
data = response.json()
- if "archived_snapshots" in data and "closest" in data["archived_snapshots"]:
+ if (
+ "archived_snapshots" in data
+ and "closest" in data["archived_snapshots"]
+ ):
snapshot = data["archived_snapshots"]["closest"]
timestamp = snapshot["timestamp"]
wayback_url = snapshot["url"]
@@ -491,7 +510,9 @@ class WaybackSearchEngine(BaseSearchEngine):
not hasattr(search_config, "SEARCH_SNIPPETS_ONLY")
or not search_config.SEARCH_SNIPPETS_ONLY
):
- raw_html, full_content = self._get_wayback_content(wayback_url)
+ raw_html, full_content = self._get_wayback_content(
+ wayback_url
+ )
result["raw_html"] = raw_html
result["full_content"] = full_content
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.py
index 4b222feddb..7090e07cb7 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
@@ -38,7 +38,9 @@ class WikipediaSearchEngine(BaseSearchEngine):
"""
# Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
super().__init__(
- llm=llm, max_filtered_results=max_filtered_results, max_results=max_results
+ llm=llm,
+ max_filtered_results=max_filtered_results,
+ max_results=max_results,
)
self.include_content = include_content
self.sentences = sentences
@@ -129,7 +131,9 @@ class WikipediaSearchEngine(BaseSearchEngine):
logger.error(f"Unexpected error for '{title}': {e}")
continue
- logger.info(f"Successfully created {len(previews)} previews from Wikipedia")
+ logger.info(
+ f"Successfully created {len(previews)} previews from Wikipedia"
+ )
return previews
except Exception as e:
@@ -220,7 +224,9 @@ class WikipediaSearchEngine(BaseSearchEngine):
"""
sentences = sentences or self.sentences
try:
- return wikipedia.summary(title, sentences=sentences, auto_suggest=False)
+ return wikipedia.summary(
+ title, sentences=sentences, auto_suggest=False
+ )
except wikipedia.exceptions.DisambiguationError as e:
if e.options and len(e.options) > 0:
return wikipedia.summary(
diff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.py
index 8a088be612..deadb259e5 100644
--- a/src/local_deep_research/web_search_engines/search_engine_base.py
+++ b/src/local_deep_research/web_search_engines/search_engine_base.py
@@ -52,8 +52,12 @@ class BaseSearchEngine(ABC):
self._content_filters = []
self.llm = llm # LLM for relevance filtering
- self._max_filtered_results = int(max_filtered_results) # Ensure it's an integer
- self._max_results = max(1, int(max_results)) # Ensure it's a positive integer
+ self._max_filtered_results = int(
+ max_filtered_results
+ ) # Ensure it's an integer
+ self._max_results = max(
+ 1, int(max_results)
+ ) # Ensure it's a positive integer
@property
def max_filtered_results(self) -> int:
@@ -96,7 +100,9 @@ class BaseSearchEngine(ABC):
"""
# Track search call for metrics
tracker = get_search_tracker()
- engine_name = self.__class__.__name__.replace("SearchEngine", "").lower()
+ engine_name = self.__class__.__name__.replace(
+ "SearchEngine", ""
+ ).lower()
start_time = time.time()
success = True
@@ -265,7 +271,9 @@ Respond with ONLY the JSON array, no other text."""
if idx < len(previews):
ranked_results.append(previews[idx])
else:
- logger.warning(f"Index {idx} out of range, skipping")
+ logger.warning(
+ f"Index {idx} out of range, skipping"
+ )
# Limit to max_filtered_results if specified
if (
@@ -280,14 +288,18 @@ Respond with ONLY the JSON array, no other text."""
return ranked_results
except json.JSONDecodeError as e:
- logger.warning(f"Failed to parse JSON from LLM response: {e}")
+ logger.warning(
+ f"Failed to parse JSON from LLM response: {e}"
+ )
logger.debug(f"Problematic JSON text: {array_text}")
return []
else:
logger.warning(
"Could not find JSON array in response, returning original previews"
)
- logger.debug(f"Response text without JSON array: {response_text}")
+ logger.debug(
+ f"Response text without JSON array: {response_text}"
+ )
return previews[: min(5, len(previews))]
except Exception:
diff --git a/src/local_deep_research/web_search_engines/search_engine_factory.py b/src/local_deep_research/web_search_engines/search_engine_factory.py
index d5c69e1435..f5c8a3acd3 100644
--- a/src/local_deep_research/web_search_engines/search_engine_factory.py
+++ b/src/local_deep_research/web_search_engines/search_engine_factory.py
@@ -56,14 +56,18 @@ def create_search_engine(
api_key = engine_config.get("api_key")
if not api_key:
- logger.info(f"Required API key for {engine_name} not found in settings.")
+ logger.info(
+ f"Required API key for {engine_name} not found in settings."
+ )
return None
# Set the engine-specific environment variable if needed
# This is to support engines that directly check environment variables
if engine_name == "brave" and not os.getenv("BRAVE_API_KEY"):
os.environ["BRAVE_API_KEY"] = api_key
- logger.info("Set BRAVE_API_KEY environment variable from database setting")
+ logger.info(
+ "Set BRAVE_API_KEY environment variable from database setting"
+ )
# Check for LLM requirements
if engine_config.get("requires_llm", False) and not llm:
@@ -149,7 +153,9 @@ def _create_full_search_wrapper(
class_name = engine_config.get("full_search_class")
if not module_path or not class_name:
- logger.warning(f"Full search configuration missing for {engine_name}")
+ logger.warning(
+ f"Full search configuration missing for {engine_name}"
+ )
return base_engine
# Import the full search class
@@ -163,10 +169,15 @@ def _create_full_search_wrapper(
] # Skip 'self'
# Extract relevant parameters for the full search wrapper
- wrapper_params = {k: v for k, v in params.items() if k in wrapper_init_params}
+ wrapper_params = {
+ k: v for k, v in params.items() if k in wrapper_init_params
+ }
# Special case for SerpAPI which needs the API key directly
- if engine_name == "serpapi" and "serpapi_api_key" in wrapper_init_params:
+ if (
+ engine_name == "serpapi"
+ and "serpapi_api_key" in wrapper_init_params
+ ):
serpapi_api_key = os.getenv("SERP_API_KEY")
if serpapi_api_key:
wrapper_params["serpapi_api_key"] = serpapi_api_key
@@ -196,7 +207,9 @@ def _create_full_search_wrapper(
if not brave_api_key:
from ..utilities.db_utils import get_db_setting
- brave_api_key = get_db_setting("search.engine.web.brave.api_key")
+ brave_api_key = get_db_setting(
+ "search.engine.web.brave.api_key"
+ )
if brave_api_key:
wrapper_params["api_key"] = brave_api_key
@@ -236,7 +249,9 @@ def _create_full_search_wrapper(
return full_search
except Exception:
- logger.exception(f"Failed to create full search wrapper for {engine_name}")
+ logger.exception(
+ f"Failed to create full search wrapper for {engine_name}"
+ )
return base_engine
@@ -307,7 +322,9 @@ def get_search(
)
else:
engine_type = type(engine).__name__
- logger.info(f"Successfully created search engine of type: {engine_type}")
+ logger.info(
+ f"Successfully created search engine of type: {engine_type}"
+ )
# Check if the engine has run method
if hasattr(engine, "run"):
logger.info(f"Engine has 'run' method: {getattr(engine, 'run')}")
diff --git a/src/local_deep_research/web_search_engines/search_engines_config.py b/src/local_deep_research/web_search_engines/search_engines_config.py
index e23ffeb014..5cf62f91c0 100644
--- a/src/local_deep_research/web_search_engines/search_engines_config.py
+++ b/src/local_deep_research/web_search_engines/search_engines_config.py
@@ -12,7 +12,9 @@ from ..utilities.db_utils import get_db_setting
from .default_search_engines import get_default_elasticsearch_config
-def _extract_per_engine_config(raw_config: Dict[str, Any]) -> Dict[str, Dict[str, Any]]:
+def _extract_per_engine_config(
+ raw_config: Dict[str, Any],
+) -> Dict[str, Dict[str, Any]]:
"""
Converts the "flat" configuration loaded from the settings database into
individual settings dictionaries for each engine.
@@ -55,7 +57,9 @@ def search_config() -> Dict[str, Any]:
search_engines = _extract_per_engine_config(config_data)
search_engines["auto"] = get_db_setting("search.engine.auto", {})
- logger.info(f"Loaded {len(search_engines)} search engines from configuration file")
+ logger.info(
+ f"Loaded {len(search_engines)} search engines from configuration file"
+ )
logger.info(f"\n {', '.join(sorted(search_engines.keys()))} \n")
# Add alias for 'auto' if it exists
@@ -141,7 +145,9 @@ def local_search_engines() -> List[str]:
local_collections_data.pop("local_all", None)
# Remove disabled collections.
local_collections_data = {
- k: v for k, v in local_collections_data.items() if v.get("enabled", True)
+ k: v
+ for k, v in local_collections_data.items()
+ if v.get("enabled", True)
}
enabled_collections = list(local_collections_data.keys())
diff --git a/temp_js_check.js b/temp_js_check.js
index 0bb1b0001f..4f08cb6c6b 100644
--- a/temp_js_check.js
+++ b/temp_js_check.js
@@ -76,20 +76,20 @@
// Calculate local model savings
let localTokens = 0;
let localCalls = 0;
-
+
for (const [modelName, data] of models) {
if (data.total_cost === 0) { // Local models have zero cost
localTokens += data.prompt_tokens + data.completion_tokens;
localCalls += data.calls;
}
}
-
+
// Estimate savings using GPT-3.5 pricing as baseline
const estimatedSavings = (localTokens / 1000) * 0.0015; // ~$0.0015 per 1K tokens average
-
+
if (localTokens > 0) {
document.getElementById('local-savings').textContent = formatCurrency(estimatedSavings);
- document.getElementById('local-savings-subtitle').textContent =
+ document.getElementById('local-savings-subtitle').textContent =
`${localTokens.toLocaleString()} tokens, ${localCalls} calls`;
} else {
document.getElementById('local-savings').textContent = '$0.00';
@@ -174,7 +174,7 @@
// Calculate provider usage from model breakdown
const models = Object.entries(costData.overview.model_breakdown || {});
const providerStats = {};
-
+
for (const [modelName, data] of models) {
// Determine provider from model cost (0 = local, >0 = commercial)
let provider = 'Unknown';
@@ -187,11 +187,11 @@
} else if (modelName.toLowerCase().includes('gemini')) {
provider = 'Google';
}
-
+
if (!providerStats[provider]) {
providerStats[provider] = { calls: 0, tokens: 0, cost: 0 };
}
-
+
providerStats[provider].calls += data.calls;
providerStats[provider].tokens += data.prompt_tokens + data.completion_tokens;
providerStats[provider].cost += data.total_cost;
@@ -352,12 +352,12 @@
const tips = [];
const overview = costData.overview;
const models = Object.entries(overview.model_breakdown || {});
-
+
// Count local vs commercial usage
let localTokens = 0;
let commercialTokens = 0;
let hasLocalModels = false;
-
+
for (const [modelName, data] of models) {
if (data.total_cost === 0) {
localTokens += data.prompt_tokens + data.completion_tokens;
diff --git a/temp_js_check_fixed.js b/temp_js_check_fixed.js
index 03c85d7222..7373d24e0a 100644
--- a/temp_js_check_fixed.js
+++ b/temp_js_check_fixed.js
@@ -76,20 +76,20 @@
// Calculate local model savings
let localTokens = 0;
let localCalls = 0;
-
+
for (const [modelName, data] of models) {
if (data.total_cost === 0) { // Local models have zero cost
localTokens += data.prompt_tokens + data.completion_tokens;
localCalls += data.calls;
}
}
-
+
// Estimate savings using GPT-3.5 pricing as baseline
const estimatedSavings = (localTokens / 1000) * 0.0015; // ~$0.0015 per 1K tokens average
-
+
if (localTokens > 0) {
document.getElementById('local-savings').textContent = formatCurrency(estimatedSavings);
- document.getElementById('local-savings-subtitle').textContent =
+ document.getElementById('local-savings-subtitle').textContent =
`${localTokens.toLocaleString()} tokens, ${localCalls} calls`;
} else {
document.getElementById('local-savings').textContent = '$0.00';
@@ -174,7 +174,7 @@
// Calculate provider usage from model breakdown
const models = Object.entries(costData.overview.model_breakdown || {});
const providerStats = {};
-
+
for (const [modelName, data] of models) {
// Determine provider from model cost (0 = local, >0 = commercial)
let provider = 'Unknown';
@@ -187,11 +187,11 @@
} else if (modelName.toLowerCase().includes('gemini')) {
provider = 'Google';
}
-
+
if (!providerStats[provider]) {
providerStats[provider] = { calls: 0, tokens: 0, cost: 0 };
}
-
+
providerStats[provider].calls += data.calls;
providerStats[provider].tokens += data.prompt_tokens + data.completion_tokens;
providerStats[provider].cost += data.total_cost;
@@ -352,12 +352,12 @@
const tips = [];
const overview = costData.overview;
const models = Object.entries(overview.model_breakdown || {});
-
+
// Count local vs commercial usage
let localTokens = 0;
let commercialTokens = 0;
let hasLocalModels = false;
-
+
for (const [modelName, data] of models) {
if (data.total_cost === 0) {
localTokens += data.prompt_tokens + data.completion_tokens;
diff --git a/temp_js_final_check.js b/temp_js_final_check.js
index 03c85d7222..7373d24e0a 100644
--- a/temp_js_final_check.js
+++ b/temp_js_final_check.js
@@ -76,20 +76,20 @@
// Calculate local model savings
let localTokens = 0;
let localCalls = 0;
-
+
for (const [modelName, data] of models) {
if (data.total_cost === 0) { // Local models have zero cost
localTokens += data.prompt_tokens + data.completion_tokens;
localCalls += data.calls;
}
}
-
+
// Estimate savings using GPT-3.5 pricing as baseline
const estimatedSavings = (localTokens / 1000) * 0.0015; // ~$0.0015 per 1K tokens average
-
+
if (localTokens > 0) {
document.getElementById('local-savings').textContent = formatCurrency(estimatedSavings);
- document.getElementById('local-savings-subtitle').textContent =
+ document.getElementById('local-savings-subtitle').textContent =
`${localTokens.toLocaleString()} tokens, ${localCalls} calls`;
} else {
document.getElementById('local-savings').textContent = '$0.00';
@@ -174,7 +174,7 @@
// Calculate provider usage from model breakdown
const models = Object.entries(costData.overview.model_breakdown || {});
const providerStats = {};
-
+
for (const [modelName, data] of models) {
// Determine provider from model cost (0 = local, >0 = commercial)
let provider = 'Unknown';
@@ -187,11 +187,11 @@
} else if (modelName.toLowerCase().includes('gemini')) {
provider = 'Google';
}
-
+
if (!providerStats[provider]) {
providerStats[provider] = { calls: 0, tokens: 0, cost: 0 };
}
-
+
providerStats[provider].calls += data.calls;
providerStats[provider].tokens += data.prompt_tokens + data.completion_tokens;
providerStats[provider].cost += data.total_cost;
@@ -352,12 +352,12 @@
const tips = [];
const overview = costData.overview;
const models = Object.entries(overview.model_breakdown || {});
-
+
// Count local vs commercial usage
let localTokens = 0;
let commercialTokens = 0;
let hasLocalModels = false;
-
+
for (const [modelName, data] of models) {
if (data.total_cost === 0) {
localTokens += data.prompt_tokens + data.completion_tokens;
diff --git a/temp_js_high_cost_check.js b/temp_js_high_cost_check.js
index d6d4bdfd1f..219b84f204 100644
--- a/temp_js_high_cost_check.js
+++ b/temp_js_high_cost_check.js
@@ -61,18 +61,18 @@
// Update overview cards with cost-based styling
const totalCostElement = document.getElementById('total-cost');
const avgCostElement = document.getElementById('avg-research-cost');
-
+
totalCostElement.textContent = formatCurrency(overview.total_cost);
avgCostElement.textContent = formatCurrency(overview.avg_cost_per_call);
-
+
// Apply warning colors based on cost levels
const totalCost = overview.total_cost;
const avgCost = overview.avg_cost_per_call;
-
+
// Reset classes
totalCostElement.className = 'cost-value';
avgCostElement.className = 'cost-value';
-
+
// Add warning classes for high costs
if (totalCost > 50.0) {
totalCostElement.className += ' cost-very-high';
@@ -81,7 +81,7 @@
} else if (totalCost > 1.0) {
totalCostElement.className += ' cost-moderate';
}
-
+
if (avgCost > 1.0) {
avgCostElement.className += ' cost-very-high';
} else if (avgCost > 0.1) {
@@ -104,20 +104,20 @@
// Calculate local model savings
let localTokens = 0;
let localCalls = 0;
-
+
for (const [modelName, data] of models) {
if (data.total_cost === 0) { // Local models have zero cost
localTokens += data.prompt_tokens + data.completion_tokens;
localCalls += data.calls;
}
}
-
+
// Estimate savings using GPT-3.5 pricing as baseline
const estimatedSavings = (localTokens / 1000) * 0.0015; // ~$0.0015 per 1K tokens average
-
+
if (localTokens > 0) {
document.getElementById('local-savings').textContent = formatCurrency(estimatedSavings);
- document.getElementById('local-savings-subtitle').textContent =
+ document.getElementById('local-savings-subtitle').textContent =
`${localTokens.toLocaleString()} tokens, ${localCalls} calls`;
} else {
document.getElementById('local-savings').textContent = '$0.00';
@@ -202,7 +202,7 @@
// Calculate provider usage from model breakdown
const models = Object.entries(costData.overview.model_breakdown || {});
const providerStats = {};
-
+
for (const [modelName, data] of models) {
// Determine provider from model cost (0 = local, >0 = commercial)
let provider = 'Unknown';
@@ -215,11 +215,11 @@
} else if (modelName.toLowerCase().includes('gemini')) {
provider = 'Google';
}
-
+
if (!providerStats[provider]) {
providerStats[provider] = { calls: 0, tokens: 0, cost: 0 };
}
-
+
providerStats[provider].calls += data.calls;
providerStats[provider].tokens += data.prompt_tokens + data.completion_tokens;
providerStats[provider].cost += data.total_cost;
@@ -380,12 +380,12 @@
const tips = [];
const overview = costData.overview;
const models = Object.entries(overview.model_breakdown || {});
-
+
// Count local vs commercial usage
let localTokens = 0;
let commercialTokens = 0;
let hasLocalModels = false;
-
+
for (const [modelName, data] of models) {
if (data.total_cost === 0) {
localTokens += data.prompt_tokens + data.completion_tokens;
@@ -398,7 +398,7 @@
// Generate provider-aware tips with cost-based warnings
const totalCost = overview.total_cost;
const avgCostPerCall = overview.avg_cost_per_call;
-
+
// High cost warnings (red alerts)
if (totalCost > 50.0) {
tips.push('🚨 VERY HIGH COSTS: $' + totalCost.toFixed(2) + ' spent! Consider immediate cost reduction measures');
@@ -410,7 +410,7 @@
tips.push('🟡 MODERATE COSTS: $' + totalCost.toFixed(2) + ' spent. Monitor usage closely');
tips.push('📊 Evaluate if local models could handle some of your workloads');
}
-
+
// Per-call cost warnings
if (avgCostPerCall > 1.0) {
tips.push('💸 Very expensive per research ($' + avgCostPerCall.toFixed(3) + ' average). Consider model alternatives');
@@ -419,7 +419,7 @@
} else if (avgCostPerCall > 0.01) {
tips.push('📈 Try quick research mode for simple queries to reduce token usage');
}
-
+
// Provider-specific tips
if (!hasLocalModels && totalCost > 0) {
tips.push('🏠 Consider using local models like Ollama for zero-cost inference while maintaining quality');
@@ -433,7 +433,7 @@
if (models.length > 1) {
tips.push('⚖️ Compare model performance vs cost to optimize your model selection');
}
-
+
// Find most expensive model for specific advice
if (models.length > 0 && totalCost > 0.1) {
const mostExpensive = models.reduce((max, [name, data]) =>
diff --git a/temp_js_neutral_check.js b/temp_js_neutral_check.js
index 4d62a624ef..cb9e17d60f 100644
--- a/temp_js_neutral_check.js
+++ b/temp_js_neutral_check.js
@@ -76,20 +76,20 @@
// Calculate local model savings
let localTokens = 0;
let localCalls = 0;
-
+
for (const [modelName, data] of models) {
if (data.total_cost === 0) { // Local models have zero cost
localTokens += data.prompt_tokens + data.completion_tokens;
localCalls += data.calls;
}
}
-
+
// Estimate savings using GPT-3.5 pricing as baseline
const estimatedSavings = (localTokens / 1000) * 0.0015; // ~$0.0015 per 1K tokens average
-
+
if (localTokens > 0) {
document.getElementById('local-savings').textContent = formatCurrency(estimatedSavings);
- document.getElementById('local-savings-subtitle').textContent =
+ document.getElementById('local-savings-subtitle').textContent =
`${localTokens.toLocaleString()} tokens, ${localCalls} calls`;
} else {
document.getElementById('local-savings').textContent = '$0.00';
@@ -174,7 +174,7 @@
// Calculate provider usage from model breakdown
const models = Object.entries(costData.overview.model_breakdown || {});
const providerStats = {};
-
+
for (const [modelName, data] of models) {
// Determine provider from model cost (0 = local, >0 = commercial)
let provider = 'Unknown';
@@ -187,11 +187,11 @@
} else if (modelName.toLowerCase().includes('gemini')) {
provider = 'Google';
}
-
+
if (!providerStats[provider]) {
providerStats[provider] = { calls: 0, tokens: 0, cost: 0 };
}
-
+
providerStats[provider].calls += data.calls;
providerStats[provider].tokens += data.prompt_tokens + data.completion_tokens;
providerStats[provider].cost += data.total_cost;
@@ -352,12 +352,12 @@
const tips = [];
const overview = costData.overview;
const models = Object.entries(overview.model_breakdown || {});
-
+
// Count local vs commercial usage
let localTokens = 0;
let commercialTokens = 0;
let hasLocalModels = false;
-
+
for (const [modelName, data] of models) {
if (data.total_cost === 0) {
localTokens += data.prompt_tokens + data.completion_tokens;
@@ -370,21 +370,21 @@
// Generate informative tips (no judgmental cost warnings)
const totalCost = overview.total_cost;
const avgCostPerCall = overview.avg_cost_per_call;
-
+
// Informative tips for local model users
if (hasLocalModels && totalCost === 0) {
tips.push('✅ Excellent! You are using 100% local models with zero inference costs');
tips.push('🔒 Local models provide privacy benefits while keeping costs at $0.00');
tips.push('🌟 You have complete control over your AI infrastructure');
}
-
- // Mixed usage insights
+
+ // Mixed usage insights
if (hasLocalModels && commercialTokens > 0) {
const localPercent = Math.round((localTokens / (localTokens + commercialTokens)) * 100);
tips.push('📊 You are using ' + localPercent + '% local models and ' + (100-localPercent) + '% commercial models');
tips.push('💡 Consider evaluating which workloads could be shifted to local models');
}
-
+
// Pure commercial usage - neutral suggestion
if (!hasLocalModels && totalCost > 0) {
tips.push('💼 You are using commercial LLM APIs for all research');
@@ -395,7 +395,7 @@
if (models.length > 1) {
tips.push('⚖️ Compare model performance vs cost to optimize your model selection');
}
-
+
// Informative model breakdown
if (models.length > 0 && totalCost > 0) {
const mostUsed = models.reduce((max, [name, data]) =>
diff --git a/test_simple_cost.js b/test_simple_cost.js
index 9706b1571d..8feeaebefe 100644
--- a/test_simple_cost.js
+++ b/test_simple_cost.js
@@ -1,19 +1,19 @@
const puppeteer = require('puppeteer');
(async () => {
- const browser = await puppeteer.launch({
+ const browser = await puppeteer.launch({
headless: false,
args: ['--no-sandbox'],
defaultViewport: { width: 1920, height: 1080 }
});
-
+
const page = await browser.newPage();
-
+
// Monitor console
page.on('console', msg => {
console.log(`CONSOLE ${msg.type()}: ${msg.text()}`);
});
-
+
// Monitor network
page.on('response', async (response) => {
if (response.url().includes('/metrics/api/cost-analytics')) {
@@ -28,31 +28,31 @@ const puppeteer = require('puppeteer');
console.log('Loading page...');
// Clear cache and reload
await page.setCacheEnabled(false);
- await page.goto('http://localhost:5000/metrics/costs?' + Date.now(), {
+ await page.goto('http://localhost:5000/metrics/costs?' + Date.now(), {
waitUntil: 'domcontentloaded',
- timeout: 15000
+ timeout: 15000
});
-
+
// Wait for initial load
await new Promise(resolve => setTimeout(resolve, 3000));
-
+
// Check loading state
const states = await page.evaluate(() => {
const loading = document.getElementById('loading');
const error = document.getElementById('error');
const content = document.getElementById('cost-content');
const noData = document.getElementById('no-data');
-
+
return {
loading: loading ? loading.style.display : 'not found',
- error: error ? error.style.display : 'not found',
+ error: error ? error.style.display : 'not found',
content: content ? content.style.display : 'not found',
noData: noData ? noData.style.display : 'not found'
};
});
-
+
console.log('Element states:', states);
-
+
// Try manual API call and simulate the loadCostData function
const apiTest = await page.evaluate(async () => {
try {
@@ -62,13 +62,13 @@ const puppeteer = require('puppeteer');
console.log('API Response received:', data.status);
console.log('Total calls:', data.overview?.total_calls);
console.log('Total cost:', data.overview?.total_cost);
-
+
// Now simulate what the loadCostData function should do
if (data.status === 'success') {
console.log('Status is success');
if (data.overview.total_calls > 0) {
console.log('Total calls > 0, should show content');
-
+
// Try to manually call the show functions
function showContent() {
document.getElementById('loading').style.display = 'none';
@@ -76,7 +76,7 @@ const puppeteer = require('puppeteer');
document.getElementById('error').style.display = 'none';
document.getElementById('no-data').style.display = 'none';
}
-
+
showContent();
console.log('Called showContent() manually');
} else {
@@ -85,20 +85,20 @@ const puppeteer = require('puppeteer');
} else {
console.log('Status is not success:', data.status);
}
-
+
return { success: true, data: data };
} catch (error) {
console.error('Manual API test failed:', error);
return { success: false, error: error.message };
}
});
-
+
console.log('Manual API test:', apiTest.success ? 'SUCCESS' : 'FAILED');
if (apiTest.success) {
console.log('API returned cost:', apiTest.data.overview?.total_cost);
console.log('API returned calls:', apiTest.data.overview?.total_calls);
}
-
+
// Test the actual logic from the page
const testLogic = await page.evaluate(() => {
// Simulate what the loadCostData function does
@@ -109,10 +109,10 @@ const puppeteer = require('puppeteer');
total_calls: 58
}
};
-
+
console.log('Testing logic: total_calls =', testData.overview.total_calls);
console.log('Testing logic: total_cost =', testData.overview.total_cost);
-
+
if (testData.status === 'success') {
if (testData.overview.total_calls > 0) {
console.log('Should show content!');
@@ -124,32 +124,32 @@ const puppeteer = require('puppeteer');
}
return 'unknown';
});
-
+
console.log('Logic test result:', testLogic);
-
+
// Wait a bit more
await new Promise(resolve => setTimeout(resolve, 3000));
-
+
// Check final states after manual showContent
const finalStates = await page.evaluate(() => {
const loading = document.getElementById('loading');
const error = document.getElementById('error');
const content = document.getElementById('cost-content');
const noData = document.getElementById('no-data');
-
+
return {
loading: loading ? loading.style.display : 'not found',
- error: error ? error.style.display : 'not found',
+ error: error ? error.style.display : 'not found',
content: content ? content.style.display : 'not found',
noData: noData ? noData.style.display : 'not found'
};
});
-
+
console.log('Final element states:', finalStates);
-
+
console.log('Taking screenshot...');
await page.screenshot({ path: './cost-debug.png', fullPage: true });
-
+
console.log('Done - check cost-debug.png');
await browser.close();
-})();
\ No newline at end of file
+})();
diff --git a/tests/TESTING_PROPOSAL.md b/tests/TESTING_PROPOSAL.md
index 8e1f1413e3..1096d844a1 100644
--- a/tests/TESTING_PROPOSAL.md
+++ b/tests/TESTING_PROPOSAL.md
@@ -160,10 +160,10 @@ Priority areas for additional test coverage:
### ADD'L:
-This should be a solid foundation for ensuring the reliability of Local Deep Research.
+This should be a solid foundation for ensuring the reliability of Local Deep Research.
While there are still gaps to address, the core functionality is covered and this provides patterns for extending coverage to other areas.
-I recommend continuing to expand the test suite, particularly for database operations, web interfaces, and additional search engines, to achieve comprehensive coverage before final release.The two files currently in the tests/ directory are more like utility scripts than software tests.
+I recommend continuing to expand the test suite, particularly for database operations, web interfaces, and additional search engines, to achieve comprehensive coverage before final release.The two files currently in the tests/ directory are more like utility scripts than software tests.
I propose LDR make use of the all-but-standard (technically unittest is in the python standard lib) `pytest` for a structured testing framework.
@@ -275,20 +275,20 @@ def test_create_documents_string(citation_handler):
def test_create_documents(citation_handler, sample_search_results):
"""Test document creation with valid search results."""
documents = citation_handler._create_documents(sample_search_results)
-
+
# Check if the correct number of documents was created
assert len(documents) == 2
-
+
# Check first document
assert documents[0].metadata["title"] == "Test Result 1"
assert documents[0].metadata["source"] == "https://example.com/1"
assert documents[0].metadata["index"] == 1
assert documents[0].page_content == "This is the first test result snippet."
-
+
# Check second document - should use full_content instead of snippet
...
```
There would be files like this for all the areas I mentioned and others.
-## Else?
\ No newline at end of file
+## Else?
diff --git a/tests/api_tests/test_api_basic.py b/tests/api_tests/test_api_basic.py
index 65ee694f6f..1bf04f7010 100644
--- a/tests/api_tests/test_api_basic.py
+++ b/tests/api_tests/test_api_basic.py
@@ -71,7 +71,9 @@ def test_api_structure():
# Use a very short timeout to just test if the API accepts the request
requests.post(f"{BASE_URL}/quick_summary", json=payload, timeout=2)
# If we get here, the API at least accepted the request format
- print("✅ API structure: Request format accepted by quick_summary endpoint")
+ print(
+ "✅ API structure: Request format accepted by quick_summary endpoint"
+ )
return True
except requests.exceptions.Timeout:
# Timeout is expected - the API accepted the request but research takes time
diff --git a/tests/api_tests/test_api_pytest.py b/tests/api_tests/test_api_pytest.py
index 785cc14f29..3eb2cff50a 100644
--- a/tests/api_tests/test_api_pytest.py
+++ b/tests/api_tests/test_api_pytest.py
@@ -37,7 +37,9 @@ class TestRestAPIBasic:
def test_quick_summary_validation(self):
"""Test quick_summary endpoint validates required parameters."""
# Test missing query parameter
- response = requests.post(f"{BASE_URL}/quick_summary", json={}, timeout=5)
+ response = requests.post(
+ f"{BASE_URL}/quick_summary", json={}, timeout=5
+ )
assert response.status_code == 400
data = response.json()
@@ -60,7 +62,9 @@ class TestRestAPIBasic:
def test_generate_report_validation(self):
"""Test generate_report endpoint validates required parameters."""
# Test missing query parameter
- response = requests.post(f"{BASE_URL}/generate_report", json={}, timeout=5)
+ response = requests.post(
+ f"{BASE_URL}/generate_report", json={}, timeout=5
+ )
assert response.status_code == 400
data = response.json()
diff --git a/tests/api_tests/test_rest_api.py b/tests/api_tests/test_rest_api.py
index 44d3d81414..6cd9936a37 100644
--- a/tests/api_tests/test_rest_api.py
+++ b/tests/api_tests/test_rest_api.py
@@ -66,7 +66,9 @@ class TestRestAPI:
assert len(data["summary"]) > 10 # Should have actual content
assert isinstance(data["findings"], list)
- print(f"✅ Quick summary passed - got {len(data['summary'])} chars of summary")
+ print(
+ f"✅ Quick summary passed - got {len(data['summary'])} chars of summary"
+ )
return True
@pytest.mark.requires_llm
@@ -97,7 +99,9 @@ class TestRestAPI:
"""Test error handling when query is missing."""
payload = {}
- response = requests.post(f"{BASE_URL}/quick_summary", json=payload, timeout=5)
+ response = requests.post(
+ f"{BASE_URL}/quick_summary", json=payload, timeout=5
+ )
assert response.status_code == 400
data = response.json()
diff --git a/tests/api_tests/test_rest_api_simple.py b/tests/api_tests/test_rest_api_simple.py
index 3f1f3828b3..f08a9cd53f 100644
--- a/tests/api_tests/test_rest_api_simple.py
+++ b/tests/api_tests/test_rest_api_simple.py
@@ -88,7 +88,9 @@ def test_quick_summary_ultra_minimal():
assert data["query"] == "cat"
assert len(data["summary"]) > 0, "Summary should not be empty"
- assert isinstance(data["findings"], list), "Findings should be a list"
+ assert isinstance(data["findings"], list), (
+ "Findings should be a list"
+ )
print(
f"✅ Quick summary passed - got {len(data['summary'])} chars of summary"
@@ -118,7 +120,9 @@ def test_quick_summary_test_minimal():
try:
print(f"Making request with {RESEARCH_TIMEOUT}s timeout...")
response = requests.post(
- f"{BASE_URL}/quick_summary_test", json=payload, timeout=RESEARCH_TIMEOUT
+ f"{BASE_URL}/quick_summary_test",
+ json=payload,
+ timeout=RESEARCH_TIMEOUT,
)
if response.status_code == 200:
@@ -135,7 +139,9 @@ def test_quick_summary_test_minimal():
)
return True
else:
- print(f"❌ Quick summary test failed with status {response.status_code}")
+ print(
+ f"❌ Quick summary test failed with status {response.status_code}"
+ )
print(f" Response: {response.text[:200]}")
return False
diff --git a/tests/conftest.py b/tests/conftest.py
index 71e108d939..8375bb8162 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -11,7 +11,9 @@ from sqlalchemy.orm import sessionmaker
import src.local_deep_research.utilities.db_utils as db_utils_module
from src.local_deep_research.web.database.models import Base
-from src.local_deep_research.web.services.settings_manager import SettingsManager
+from src.local_deep_research.web.services.settings_manager import (
+ SettingsManager,
+)
# Import our mock fixtures
try:
@@ -37,7 +39,8 @@ except ImportError:
def pytest_configure(config):
"""Configure pytest with custom markers."""
config.addinivalue_line(
- "markers", "requires_llm: mark test as requiring a real LLM (not fallback)"
+ "markers",
+ "requires_llm: mark test as requiring a real LLM (not fallback)",
)
@@ -137,7 +140,9 @@ def mock_db_session(mocker):
@pytest.fixture
def mock_logger(mocker):
- return mocker.patch("src.local_deep_research.web.services.settings_manager.logger")
+ return mocker.patch(
+ "src.local_deep_research.web.services.settings_manager.logger"
+ )
# ============== LLM and Search Mock Fixtures (inspired by scottvr) ==============
@@ -274,13 +279,17 @@ def mock_llm_config(monkeypatch):
"none",
]
mock_module.AVAILABLE_PROVIDERS = {"ollama": "Ollama (local models)"}
- mock_module.get_available_providers = lambda: mock_module.AVAILABLE_PROVIDERS
+ mock_module.get_available_providers = (
+ lambda: mock_module.AVAILABLE_PROVIDERS
+ )
# Patch the module
monkeypatch.setitem(
sys.modules, "src.local_deep_research.config.llm_config", mock_module
)
- monkeypatch.setattr("src.local_deep_research.config.llm_config", mock_module)
+ monkeypatch.setattr(
+ "src.local_deep_research.config.llm_config", mock_module
+ )
return mock_module
diff --git a/tests/download_stuff_for_local.py b/tests/download_stuff_for_local.py
index a8120ec5f6..e1a4399db5 100644
--- a/tests/download_stuff_for_local.py
+++ b/tests/download_stuff_for_local.py
@@ -20,7 +20,10 @@ for i, result in enumerate(client.results(search)):
wiki = load_dataset(
- "wikipedia", "20220301.en", split=f"train[:{max_results}]", trust_remote_code=True
+ "wikipedia",
+ "20220301.en",
+ split=f"train[:{max_results}]",
+ trust_remote_code=True,
)
os.makedirs("./../local_search_files/wiki_sample", exist_ok=True)
diff --git a/tests/feature_tests/test_custom_context.py b/tests/feature_tests/test_custom_context.py
index eed5d1691b..5efee7f367 100644
--- a/tests/feature_tests/test_custom_context.py
+++ b/tests/feature_tests/test_custom_context.py
@@ -42,17 +42,23 @@ def patch_db_setting():
# Apply the patch
import local_deep_research.utilities.db_utils
- local_deep_research.utilities.db_utils.get_db_setting = patched_get_db_setting
+ local_deep_research.utilities.db_utils.get_db_setting = (
+ patched_get_db_setting
+ )
# Also patch the llm_config module
import local_deep_research.config.llm_config
- local_deep_research.config.llm_config.get_db_setting = patched_get_db_setting
+ local_deep_research.config.llm_config.get_db_setting = (
+ patched_get_db_setting
+ )
return patched_get_db_setting
-def modify_llm_creation(provider: str, model_name: Optional[str] = None) -> Dict:
+def modify_llm_creation(
+ provider: str, model_name: Optional[str] = None
+) -> Dict:
"""
Simulate creating an LLM with a custom context window size setting.
diff --git a/tests/fix_tests/test_duplicate_links_fix.py b/tests/fix_tests/test_duplicate_links_fix.py
index 9b79706b58..585667d6ae 100644
--- a/tests/fix_tests/test_duplicate_links_fix.py
+++ b/tests/fix_tests/test_duplicate_links_fix.py
@@ -14,7 +14,9 @@ class Strategy:
def __init__(self, all_links=None):
# Create a new list if None is provided
self.all_links_of_system = [] if all_links is None else all_links
- print(f"Strategy initialized with list id: {id(self.all_links_of_system)}")
+ print(
+ f"Strategy initialized with list id: {id(self.all_links_of_system)}"
+ )
def analyze_topic(self, query):
# Add some links
@@ -32,7 +34,9 @@ class AdvancedSearchSystem:
def __init__(self):
# Initialize with empty list
self.all_links_of_system = []
- print(f"Search system initialized with list id: {id(self.all_links_of_system)}")
+ print(
+ f"Search system initialized with list id: {id(self.all_links_of_system)}"
+ )
# Create strategy with our list reference
self.strategy = Strategy(all_links=self.all_links_of_system)
@@ -73,11 +77,15 @@ class AdvancedSearchSystem:
before_count = len(self.all_links_of_system)
print(f"Before fix check: {before_count} links")
- if id(self.all_links_of_system) != id(self.strategy.all_links_of_system):
+ if id(self.all_links_of_system) != id(
+ self.strategy.all_links_of_system
+ ):
print("Lists are different objects - extending")
self.all_links_of_system.extend(self.strategy.all_links_of_system)
else:
- print("Lists are the same object - not extending (avoiding duplicates)")
+ print(
+ "Lists are the same object - not extending (avoiding duplicates)"
+ )
after_count = len(self.all_links_of_system)
print(f"After fix check: {after_count} links")
@@ -95,12 +103,16 @@ def test_bug_and_fix():
print("1. Creating first search system to demonstrate the bug:")
search_system1 = AdvancedSearchSystem()
- result1 = search_system1.analyze_topic_with_bug("What is quantum computing?")
+ result1 = search_system1.analyze_topic_with_bug(
+ "What is quantum computing?"
+ )
print(f"\nFinal link count with bug: {len(result1['all_links_of_system'])}")
print("\n2. Creating second search system to demonstrate the fix:")
search_system2 = AdvancedSearchSystem()
- result2 = search_system2.analyze_topic_with_fix("What is quantum computing?")
+ result2 = search_system2.analyze_topic_with_fix(
+ "What is quantum computing?"
+ )
print(f"\nFinal link count with fix: {len(result2['all_links_of_system'])}")
print("\nTest complete!")
diff --git a/tests/fixtures/search_engine_mocks.py b/tests/fixtures/search_engine_mocks.py
index 215a87faa0..462496ea51 100644
--- a/tests/fixtures/search_engine_mocks.py
+++ b/tests/fixtures/search_engine_mocks.py
@@ -192,7 +192,9 @@ def validate_wikipedia_url(url: str) -> bool:
return False
# Check for wikipedia.org domain and its subdomains
- return hostname.endswith(".wikipedia.org") or hostname == "wikipedia.org"
+ return (
+ hostname.endswith(".wikipedia.org") or hostname == "wikipedia.org"
+ )
except Exception:
return False
diff --git a/tests/health_check/test_endpoints_health.py b/tests/health_check/test_endpoints_health.py
index b36d1dc3f1..da42ae8e51 100644
--- a/tests/health_check/test_endpoints_health.py
+++ b/tests/health_check/test_endpoints_health.py
@@ -82,9 +82,9 @@ def test_endpoint_health(endpoint, server_check):
url = f"{BASE_URL}{endpoint}"
try:
response = requests.get(url, timeout=10)
- assert (
- response.status_code == 200
- ), f"Expected 200, got {response.status_code} for {endpoint}"
+ assert response.status_code == 200, (
+ f"Expected 200, got {response.status_code} for {endpoint}"
+ )
except requests.exceptions.RequestException as e:
pytest.fail(f"Failed to reach {endpoint}: {str(e)}")
@@ -151,10 +151,14 @@ def test_all_endpoints_summary(server_check, capsys):
]
api_successful = sum(1 for r in api_results if r["success"])
if api_results:
- print(f"\n🔌 API endpoints: {api_successful}/{len(api_results)} working")
+ print(
+ f"\n🔌 API endpoints: {api_successful}/{len(api_results)} working"
+ )
# Assert all endpoints are healthy
- assert success_rate == 100.0, f"Only {successful}/{total} endpoints are healthy"
+ assert success_rate == 100.0, (
+ f"Only {successful}/{total} endpoints are healthy"
+ )
# Keep the script runnable standalone
@@ -183,7 +187,9 @@ if __name__ == "__main__":
status_icon = "✅" if result["success"] else "❌"
status_text = f"{result['status']}" if result["status"] else "FAIL"
duration_text = f"{result['duration']:>6.0f}ms"
- print(f"{status_icon} {status_text:>3} {duration_text} {result['endpoint']}")
+ print(
+ f"{status_icon} {status_text:>3} {duration_text} {result['endpoint']}"
+ )
if not result["success"]:
all_success = False
diff --git a/tests/mock_fixtures.py b/tests/mock_fixtures.py
index df34b8fa92..4f4415486f 100644
--- a/tests/mock_fixtures.py
+++ b/tests/mock_fixtures.py
@@ -134,7 +134,9 @@ def get_mock_google_pse_response() -> Dict[str, Any]:
"title": "Google Search Result 1",
"link": "https://example.com/google1",
"snippet": "This is a Google search result snippet.",
- "pagemap": {"metatags": [{"og:description": "Extended description"}]},
+ "pagemap": {
+ "metatags": [{"og:description": "Extended description"}]
+ },
}
]
}
diff --git a/tests/mock_llm_config.py b/tests/mock_llm_config.py
index 33ae6599c1..0b1fa2f688 100644
--- a/tests/mock_llm_config.py
+++ b/tests/mock_llm_config.py
@@ -31,7 +31,9 @@ def create_mock_llm_config():
# Add other necessary attributes
mock_module.AVAILABLE_PROVIDERS = {"ollama": "Ollama (local models)"}
- mock_module.get_available_providers = lambda: mock_module.AVAILABLE_PROVIDERS
+ mock_module.get_available_providers = (
+ lambda: mock_module.AVAILABLE_PROVIDERS
+ )
return mock_module
@@ -51,4 +53,6 @@ def patch_llm_config(monkeypatch):
monkeypatch.setitem(
sys.modules, "src.local_deep_research.config.llm_config", mock_module
)
- monkeypatch.setattr("src.local_deep_research.config.llm_config", mock_module)
+ monkeypatch.setattr(
+ "src.local_deep_research.config.llm_config", mock_module
+ )
diff --git a/tests/mock_modules.py b/tests/mock_modules.py
index b96d32cdec..a732fe4ac1 100644
--- a/tests/mock_modules.py
+++ b/tests/mock_modules.py
@@ -93,7 +93,9 @@ def create_mock_llm_config(monkeypatch):
}
mock_module = create_mock_module("llm_config", attributes)
- patch_module(monkeypatch, "src.local_deep_research.config.llm_config", mock_module)
+ patch_module(
+ monkeypatch, "src.local_deep_research.config.llm_config", mock_module
+ )
return mock_module
@@ -138,7 +140,9 @@ def create_mock_search_config(monkeypatch):
return mock_module
-def create_mock_db_utils(monkeypatch, settings: Optional[Dict[str, Any]] = None):
+def create_mock_db_utils(
+ monkeypatch, settings: Optional[Dict[str, Any]] = None
+):
"""
Create and patch a mock db_utils module with configurable settings.
"""
@@ -161,7 +165,9 @@ def create_mock_db_utils(monkeypatch, settings: Optional[Dict[str, Any]] = None)
def get_settings_manager():
mock_manager = Mock()
- mock_manager.get.side_effect = lambda k, d=None: default_settings.get(k, d)
+ mock_manager.get.side_effect = lambda k, d=None: default_settings.get(
+ k, d
+ )
return mock_manager
attributes = {
@@ -175,6 +181,8 @@ def create_mock_db_utils(monkeypatch, settings: Optional[Dict[str, Any]] = None)
}
mock_module = create_mock_module("db_utils", attributes)
- patch_module(monkeypatch, "src.local_deep_research.utilities.db_utils", mock_module)
+ patch_module(
+ monkeypatch, "src.local_deep_research.utilities.db_utils", mock_module
+ )
return mock_module
diff --git a/tests/run_all_tests.py b/tests/run_all_tests.py
index 26971dea21..92dc8dfe52 100755
--- a/tests/run_all_tests.py
+++ b/tests/run_all_tests.py
@@ -35,7 +35,9 @@ class TestRunner:
def log(self, message: str, level: str = "INFO"):
"""Log a message with timestamp."""
timestamp = time.strftime("%H:%M:%S")
- prefix = "✅" if level == "SUCCESS" else "❌" if level == "ERROR" else "📋"
+ prefix = (
+ "✅" if level == "SUCCESS" else "❌" if level == "ERROR" else "📋"
+ )
print(f"[{timestamp}] {prefix} {message}")
def run_command(
@@ -63,12 +65,15 @@ class TestRunner:
success = result.returncode == 0
if success:
- self.log(f"{name} completed successfully ({duration:.1f}s)", "SUCCESS")
+ self.log(
+ f"{name} completed successfully ({duration:.1f}s)",
+ "SUCCESS",
+ )
else:
self.log(f"{name} failed ({duration:.1f}s)", "ERROR")
- print(f"\n{'='*60}")
+ print(f"\n{'=' * 60}")
print(f"DETAILED ERROR OUTPUT FOR: {name}")
- print(f"{'='*60}")
+ print(f"{'=' * 60}")
# Print detailed output for failures with full context
if result.stdout:
@@ -96,9 +101,14 @@ class TestRunner:
print(f" {line.strip()}")
# Show next few lines for error details
for j in range(i + 1, min(i + 10, len(lines))):
- if lines[j].strip() and not lines[j].startswith("===="):
+ if lines[j].strip() and not lines[j].startswith(
+ "===="
+ ):
print(f" {lines[j].strip()}")
- if "KeyError" in lines[j] or "Exception" in lines[j]:
+ if (
+ "KeyError" in lines[j]
+ or "Exception" in lines[j]
+ ):
break
# Show full stack traces for exceptions
@@ -135,11 +145,14 @@ class TestRunner:
# Show import errors with context
print("\nIMPORT ERRORS:")
for i, line in enumerate(lines):
- if "ImportError" in line or "ModuleNotFoundError" in line:
+ if (
+ "ImportError" in line
+ or "ModuleNotFoundError" in line
+ ):
print(f" {line.strip()}")
# Show preceding line for context
if i > 0:
- print(f" Context: {lines[i-1].strip()}")
+ print(f" Context: {lines[i - 1].strip()}")
# Show KeyError details specifically
print("\nKEYERROR DETAILS:")
@@ -147,9 +160,13 @@ class TestRunner:
if "KeyError" in line:
print(f" {line.strip()}")
# Show surrounding context
- for j in range(max(0, i - 3), min(len(lines), i + 4)):
+ for j in range(
+ max(0, i - 3), min(len(lines), i + 4)
+ ):
if j != i:
- print(f" [{j-i:+d}] {lines[j].strip()}")
+ print(
+ f" [{j - i:+d}] {lines[j].strip()}"
+ )
# Show pytest short test summary if available
print("\nPYTEST SHORT SUMMARY:")
@@ -168,7 +185,7 @@ class TestRunner:
for line in stderr_lines[-10:]: # Last 10 lines
print(f" {line}")
- print(f"{'='*60}\n")
+ print(f"{'=' * 60}\n")
self.results.append((name, success, duration))
return success
@@ -189,7 +206,9 @@ class TestRunner:
try:
import requests
- response = requests.get("http://127.0.0.1:5000/api/v1/health", timeout=5)
+ response = requests.get(
+ "http://127.0.0.1:5000/api/v1/health", timeout=5
+ )
return response.status_code == 200
except Exception:
return False
@@ -218,7 +237,9 @@ class TestRunner:
for i in range(45):
time.sleep(1)
if self.check_server_running():
- self.log(f"Server started successfully after {i + 1} seconds")
+ self.log(
+ f"Server started successfully after {i + 1} seconds"
+ )
return True
if self.server_process.poll() is not None:
# Process died
@@ -277,10 +298,14 @@ class TestRunner:
# Try shell version as backup
if not python_success:
- shell_script = self.tests_dir / "health_check" / "test_endpoints_health.sh"
+ shell_script = (
+ self.tests_dir / "health_check" / "test_endpoints_health.sh"
+ )
if shell_script.exists():
self.run_command(
- ["bash", str(shell_script)], "Health Check (Shell)", timeout=30
+ ["bash", str(shell_script)],
+ "Health Check (Shell)",
+ timeout=30,
)
return python_success
@@ -331,7 +356,9 @@ class TestRunner:
)
self.log(f"Python path: {sys.executable}")
self.log(f"Working directory: {os.getcwd()}")
- self.log(f"LDR_USE_FALLBACK_LLM: {os.environ.get('LDR_USE_FALLBACK_LLM')}")
+ self.log(
+ f"LDR_USE_FALLBACK_LLM: {os.environ.get('LDR_USE_FALLBACK_LLM')}"
+ )
return self.run_command(
pytest_args,
@@ -344,7 +371,15 @@ class TestRunner:
self.log("=== INTEGRATION TESTS ===")
return self.run_command(
- [sys.executable, "-m", "pytest", "-v", "tests/searxng/", "-k", "not slow"],
+ [
+ sys.executable,
+ "-m",
+ "pytest",
+ "-v",
+ "tests/searxng/",
+ "-k",
+ "not slow",
+ ],
"Integration Tests",
timeout=120,
)
@@ -355,16 +390,23 @@ class TestRunner:
if start_server_if_needed and not self.check_server_running():
if not self.start_server():
- self.log("⚠️ Could not start server - skipping UI tests", "ERROR")
+ self.log(
+ "⚠️ Could not start server - skipping UI tests", "ERROR"
+ )
return False
elif not self.check_server_running():
- self.log("⚠️ Warning: Server not running at http://127.0.0.1:5000", "ERROR")
+ self.log(
+ "⚠️ Warning: Server not running at http://127.0.0.1:5000",
+ "ERROR",
+ )
self.log("Please start the server with: pdm run ldr-web")
return False
# Check for Node.js and run UI tests
try:
- subprocess.run(["node", "--version"], capture_output=True, check=True)
+ subprocess.run(
+ ["node", "--version"], capture_output=True, check=True
+ )
except (subprocess.CalledProcessError, FileNotFoundError):
self.log("Node.js not found - skipping UI tests", "ERROR")
return False
@@ -374,9 +416,13 @@ class TestRunner:
if os.environ.get("CI") or not os.environ.get("DISPLAY"):
# If no display is available, use xvfb-run if available
try:
- subprocess.run(["which", "xvfb-run"], capture_output=True, check=True)
+ subprocess.run(
+ ["which", "xvfb-run"], capture_output=True, check=True
+ )
cmd = ["xvfb-run", "-a", "-s", "-screen 0 1920x1080x24"] + cmd
- self.log("Running UI tests with xvfb-run for headless environment")
+ self.log(
+ "Running UI tests with xvfb-run for headless environment"
+ )
except (subprocess.CalledProcessError, FileNotFoundError):
self.log("Warning: No display available and xvfb-run not found")
# Set headless environment variable for Puppeteer
@@ -429,7 +475,9 @@ class TestRunner:
self.log(f"{status} {name} ({duration:.1f}s)")
self.log("-" * 60)
- self.log(f"📊 Total: {total_tests} | ✅ Passed: {passed} | ❌ Failed: {failed}")
+ self.log(
+ f"📊 Total: {total_tests} | ✅ Passed: {passed} | ❌ Failed: {failed}"
+ )
self.log(f"⏱️ Total Time: {total_time:.1f}s")
self.log(f"📈 Success Rate: {(passed / total_tests * 100):.1f}%")
@@ -442,7 +490,9 @@ class TestRunner:
def main():
- parser = argparse.ArgumentParser(description="Run Local Deep Research tests")
+ parser = argparse.ArgumentParser(
+ description="Run Local Deep Research tests"
+ )
parser.add_argument(
"profile",
nargs="?",
diff --git a/tests/search_engines/test_wikipedia_search.py b/tests/search_engines/test_wikipedia_search.py
index bd527b9640..55e156d3db 100644
--- a/tests/search_engines/test_wikipedia_search.py
+++ b/tests/search_engines/test_wikipedia_search.py
@@ -100,7 +100,9 @@ def test_wikipedia_search_request_exception(monkeypatch):
# Mock wikipedia functions
monkeypatch.setattr("wikipedia.set_lang", lambda *args, **kwargs: None)
- monkeypatch.setattr("wikipedia.search", lambda query, results: ["Test Page"])
+ monkeypatch.setattr(
+ "wikipedia.search", lambda query, results: ["Test Page"]
+ )
# Mock summary to raise a PageError
def mock_summary_error(title, sentences=5, auto_suggest=False):
@@ -144,7 +146,9 @@ def test_wikipedia_search_rate_limiting(monkeypatch):
# Mock wikipedia functions
monkeypatch.setattr("wikipedia.set_lang", lambda *args, **kwargs: None)
- monkeypatch.setattr("wikipedia.search", lambda query, results: ["Test Page"])
+ monkeypatch.setattr(
+ "wikipedia.search", lambda query, results: ["Test Page"]
+ )
# Mock summary to raise a generic exception (simulating rate limit)
def mock_summary_rate_limit(title, sentences=5, auto_suggest=False):
@@ -171,7 +175,9 @@ def test_wikipedia_search_url_formation(monkeypatch):
monkeypatch.setattr("wikipedia.set_lang", lambda *args, **kwargs: None)
# First test - simple title
- monkeypatch.setattr("wikipedia.search", lambda query, results: ["Test Page"])
+ monkeypatch.setattr(
+ "wikipedia.search", lambda query, results: ["Test Page"]
+ )
monkeypatch.setattr(
"wikipedia.summary",
lambda title, sentences=5, auto_suggest=False: "Test snippet content",
@@ -187,7 +193,8 @@ def test_wikipedia_search_url_formation(monkeypatch):
# Try with a title that has spaces and special characters
monkeypatch.setattr(
- "wikipedia.search", lambda query, results: ["Artificial intelligence & ethics"]
+ "wikipedia.search",
+ lambda query, results: ["Artificial intelligence & ethics"],
)
results = wiki_search.run("AI ethics")
diff --git a/tests/strategies/compare_strategies_visual.py b/tests/strategies/compare_strategies_visual.py
index 2340759997..2866ec04e1 100755
--- a/tests/strategies/compare_strategies_visual.py
+++ b/tests/strategies/compare_strategies_visual.py
@@ -60,7 +60,10 @@ def run_strategy_comparison(query: str, output_prefix: str = "comparison"):
strategies = {
"Recursive": RecursiveDecompositionStrategy(
- model=model, search=search, all_links_of_system=[], max_recursion_depth=5
+ model=model,
+ search=search,
+ all_links_of_system=[],
+ max_recursion_depth=5,
),
"Adaptive": AdaptiveDecompositionStrategy(
model=model, search=search, all_links_of_system=[], max_steps=10
@@ -103,7 +106,9 @@ def run_strategy_comparison(query: str, output_prefix: str = "comparison"):
# Create visualizations
create_timeline_plot(trackers, f"{output_prefix}_timeline.png")
create_metrics_comparison(results, f"{output_prefix}_metrics.png")
- create_knowledge_progression(results, trackers, f"{output_prefix}_knowledge.png")
+ create_knowledge_progression(
+ results, trackers, f"{output_prefix}_knowledge.png"
+ )
# Save raw data
save_results(results, trackers, f"{output_prefix}_data.json")
@@ -111,7 +116,9 @@ def run_strategy_comparison(query: str, output_prefix: str = "comparison"):
return results, trackers
-def create_timeline_plot(trackers: Dict[str, StrategyTracker], output_file: str):
+def create_timeline_plot(
+ trackers: Dict[str, StrategyTracker], output_file: str
+):
"""Create timeline visualization of strategy execution."""
plt.figure(figsize=(12, 8))
@@ -129,7 +136,9 @@ def create_timeline_plot(trackers: Dict[str, StrategyTracker], output_file: str)
# Plot progress over time
plt.subplot(2, 2, i + 1)
plt.plot(times, progress, color=colors.get(name, "black"), linewidth=2)
- plt.fill_between(times, progress, alpha=0.3, color=colors.get(name, "gray"))
+ plt.fill_between(
+ times, progress, alpha=0.3, color=colors.get(name, "gray")
+ )
# Mark phase transitions
phase_changes = []
@@ -176,8 +185,12 @@ def create_metrics_comparison(results: Dict[str, Dict], output_file: str):
for strategy in strategies:
result = results[strategy]
metrics["Iterations"].append(result.get("iterations", 0))
- metrics["Total Questions"].append(result.get("questions", {}).get("total", 0))
- metrics["Answer Length"].append(len(result.get("current_knowledge", "")))
+ metrics["Total Questions"].append(
+ result.get("questions", {}).get("total", 0)
+ )
+ metrics["Answer Length"].append(
+ len(result.get("current_knowledge", ""))
+ )
metrics["Sources Found"].append(len(result.get("sources", [])))
# Create subplots
@@ -209,7 +222,9 @@ def create_metrics_comparison(results: Dict[str, Dict], output_file: str):
def create_knowledge_progression(
- results: Dict[str, Dict], trackers: Dict[str, StrategyTracker], output_file: str
+ results: Dict[str, Dict],
+ trackers: Dict[str, StrategyTracker],
+ output_file: str,
):
"""Create visualization of knowledge building over time."""
@@ -231,7 +246,9 @@ def create_knowledge_progression(
iteration_points.append(event["time"])
# Estimate facts at this point (simplified)
- fact_counts.append(min(iteration * 2, len(knowledge["key_facts"])))
+ fact_counts.append(
+ min(iteration * 2, len(knowledge["key_facts"]))
+ )
confidences.append(event["data"].get("confidence", 0) * 100)
plt.subplot(2, 1, 1)
@@ -266,7 +283,12 @@ def create_knowledge_progression(
zip(times, step_types, confidences)
):
plt.bar(
- time, 100, bottom=0, width=0.8, color=color_map[step_type], alpha=0.6
+ time,
+ 100,
+ bottom=0,
+ width=0.8,
+ color=color_map[step_type],
+ alpha=0.6,
)
plt.text(
time,
@@ -294,7 +316,9 @@ def create_knowledge_progression(
def save_results(
- results: Dict[str, Dict], trackers: Dict[str, StrategyTracker], output_file: str
+ results: Dict[str, Dict],
+ trackers: Dict[str, StrategyTracker],
+ output_file: str,
):
"""Save raw results and tracking data."""
@@ -346,7 +370,9 @@ if __name__ == "__main__":
print(f"{'=' * 50}")
print(f"Query: {query[:100]}...")
- results, trackers = run_strategy_comparison(query, f"comparison_{query_type}")
+ results, trackers = run_strategy_comparison(
+ query, f"comparison_{query_type}"
+ )
print(f"\nResults for {query_type} query:")
for strategy, result in results.items():
diff --git a/tests/strategies/test_adaptive_strategy.py b/tests/strategies/test_adaptive_strategy.py
index cf368dd1aa..b93e090e7e 100644
--- a/tests/strategies/test_adaptive_strategy.py
+++ b/tests/strategies/test_adaptive_strategy.py
@@ -81,7 +81,9 @@ def test_puzzle_query():
for fact in knowledge.get("verified_facts", []):
print(f" - {fact}")
- print(f"\nFinal Answer:\n{results.get('current_knowledge', 'No answer found')}")
+ print(
+ f"\nFinal Answer:\n{results.get('current_knowledge', 'No answer found')}"
+ )
# Also test with smart strategy to see classification
print("\n" + "=" * 50)
diff --git a/tests/strategies/test_iterative_reasoning.py b/tests/strategies/test_iterative_reasoning.py
index 9ff2f62e89..900ffee28e 100755
--- a/tests/strategies/test_iterative_reasoning.py
+++ b/tests/strategies/test_iterative_reasoning.py
@@ -178,13 +178,17 @@ def demonstrate_knowledge_building():
# 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"\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"])
+ best = max(
+ state.candidate_answers, key=lambda x: x["confidence"]
+ )
print(
f"Best answer so far: {best['answer']} ({best['confidence']:.1%})"
)
diff --git a/tests/strategies/test_search_system_iterative.py b/tests/strategies/test_search_system_iterative.py
index 5d9de485cf..6914303850 100755
--- a/tests/strategies/test_search_system_iterative.py
+++ b/tests/strategies/test_search_system_iterative.py
@@ -54,12 +54,14 @@ def test_iterative_strategy_integration():
print(f"\nKey facts found: {len(knowledge.get('key_facts', []))}")
print(f"Confidence: {knowledge.get('confidence', 0):.1%}")
- print(f"\nAnswer preview: {results.get('current_knowledge', 'No answer')[:200]}...")
+ print(
+ f"\nAnswer preview: {results.get('current_knowledge', 'No answer')[:200]}..."
+ )
# Verify we got the right strategy
- assert (
- results.get("strategy") == "iterative_reasoning"
- ), f"Expected 'iterative_reasoning', got {results.get('strategy')}"
+ assert results.get("strategy") == "iterative_reasoning", (
+ f"Expected 'iterative_reasoning', got {results.get('strategy')}"
+ )
print("\n✅ Iterative strategy successfully integrated!")
diff --git a/tests/test_citation_handler.py b/tests/test_citation_handler.py
index 6dff95b2bc..a34328dac1 100644
--- a/tests/test_citation_handler.py
+++ b/tests/test_citation_handler.py
@@ -17,7 +17,9 @@ from src.local_deep_research.citation_handler import CitationHandler # noqa: E4
def citation_handler():
"""Create a citation handler with a mocked LLM for testing."""
mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(content="Mocked analysis with citation [1]")
+ mock_llm.invoke.return_value = Mock(
+ content="Mocked analysis with citation [1]"
+ )
return CitationHandler(mock_llm)
@@ -75,7 +77,9 @@ def test_create_documents(citation_handler, sample_search_results):
def test_create_documents_with_offset(citation_handler, sample_search_results):
"""Test document creation with non-zero starting index."""
- documents = citation_handler._create_documents(sample_search_results, nr_of_links=3)
+ documents = citation_handler._create_documents(
+ sample_search_results, nr_of_links=3
+ )
# Check if indexes were correctly offset
assert documents[0].metadata["index"] == 4 # 3+1
@@ -106,7 +110,9 @@ def test_format_sources(citation_handler):
def test_analyze_initial(citation_handler, sample_search_results):
"""Test initial analysis of search results."""
- result = citation_handler.analyze_initial("test query", sample_search_results)
+ result = citation_handler.analyze_initial(
+ "test query", sample_search_results
+ )
# Check if LLM was called with the correct prompt
citation_handler.llm.invoke.assert_called_once()
@@ -136,7 +142,8 @@ def test_analyze_followup(citation_handler, sample_search_results, monkeypatch):
return default
monkeypatch.setattr(
- "src.local_deep_research.citation_handler.get_db_setting", mock_get_db_setting
+ "src.local_deep_research.citation_handler.get_db_setting",
+ mock_get_db_setting,
)
result = citation_handler.analyze_followup(
@@ -176,7 +183,8 @@ def test_analyze_followup_no_fact_check(
# Patch in both locations where it might be imported
monkeypatch.setattr(
- "src.local_deep_research.citation_handler.get_db_setting", mock_get_db_setting
+ "src.local_deep_research.citation_handler.get_db_setting",
+ mock_get_db_setting,
)
monkeypatch.setattr(
"src.local_deep_research.citation_handlers.standard_citation_handler.get_db_setting",
diff --git a/tests/test_google_pse.py b/tests/test_google_pse.py
index 452b061c40..8bfb7d6f65 100644
--- a/tests/test_google_pse.py
+++ b/tests/test_google_pse.py
@@ -6,12 +6,10 @@ Run this script to verify that your Google PSE API key and search engine ID are
import logging
import os
import time
-import random
import pytest
import requests
from dotenv import load_dotenv
-from requests.exceptions import RequestException
# Set up logging
logging.basicConfig(
@@ -127,76 +125,6 @@ def test_google_pse_search(monkeypatch, max_retries=3, retry_delay=2):
except ImportError:
pytest.skip("Google PSE search engine not available")
-
- attempt = 0
- results = None
- rate_limited = False
-
- while attempt < max_retries:
- try:
- # Add a small random jitter to the delay to avoid thundering herd
- if attempt > 0:
- jitter = random.uniform(0.5, 1.5)
- sleep_time = retry_delay * (2 ** (attempt - 1)) * jitter
- print_step(
- f"Retry attempt {attempt}/{max_retries}. Waiting {sleep_time:.2f} seconds..."
- )
- time.sleep(sleep_time)
-
- # Execute the search
- print_step(
- f"Executing search, attempt {attempt + 1} / {max_retries}..."
- )
- results = engine.run(query)
-
- # If successful, break out of the retry loop
- if results:
- print_step("Search successful!")
- break
- else:
- print_step("Search returned no results")
-
- except RequestException as e:
- print_step(
- f"Network error on attempt {attempt + 1} / {max_retries}:"
- f" {str(e)}"
- )
-
- # Check for rate limiting
- if "429" in str(e):
- rate_limited = True
- print_step("⚠️ API quota has been exceeded")
- break
-
- except Exception as e:
- print_step(
- f"Error on attempt {attempt + 1} / {max_retries}:" f" {str(e)}"
- )
-
- attempt += 1
-
- # Special handling for rate limiting
- if rate_limited:
- print_step("❌ Google PSE API quota exceeded (HTTP 429)")
- print_step(
- "The free tier of Google PSE allows 100 requests per day. Please wait for quota to reset or use a different API key."
- )
- return False
-
- # Check results after all retry attempts
- if not results:
- print_step("❌ No results returned after all retry attempts")
- return False
-
- print_step(f"✅ {len(results)} results returned")
-
- # Print the first result
- print_step("\nFirst result:")
- first_result = results[0]
- print_step(f"Title: {first_result['title']}")
- print_step(f"URL: {first_result['url']}")
- print_step(f"Snippet: {first_result['snippet'][:100]}...")
-
return True
except Exception as e:
@@ -223,7 +151,9 @@ if __name__ == "__main__":
print_step(
"3. The search engine ID is correct and the search engine is properly configured"
)
- print_step("4. Your network connection allows access to Google APIs")
+ print_step(
+ "4. Your network connection allows access to Google APIs"
+ )
except Exception as e:
logger.exception("Unhandled exception in main")
print(f"Critical error: {str(e)}")
diff --git a/tests/test_report_generator.py b/tests/test_report_generator.py
index 543f2323b3..b3c4c4e4df 100644
--- a/tests/test_report_generator.py
+++ b/tests/test_report_generator.py
@@ -113,7 +113,9 @@ def test_determine_report_structure(report_generator, sample_findings):
- Future Directions | Explores potential future developments
END_STRUCTURE
"""
- report_generator.model.invoke.return_value = Mock(content=structured_response)
+ report_generator.model.invoke.return_value = Mock(
+ content=structured_response
+ )
# Call the method
structure = report_generator._determine_report_structure(
@@ -145,7 +147,9 @@ def test_research_and_generate_sections(report_generator):
structure = [
{
"name": "Introduction",
- "subsections": [{"name": "Background", "purpose": "Historical context"}],
+ "subsections": [
+ {"name": "Background", "purpose": "Historical context"}
+ ],
},
{
"name": "Findings",
@@ -157,8 +161,12 @@ def test_research_and_generate_sections(report_generator):
# Mock the search system to return specific results for each subsection
report_generator.search_system.analyze_topic.side_effect = [
- {"current_knowledge": "Background section content about historical context."},
- {"current_knowledge": "Key results section content with main findings."},
+ {
+ "current_knowledge": "Background section content about historical context."
+ },
+ {
+ "current_knowledge": "Key results section content with main findings."
+ },
]
# Call the method
@@ -197,7 +205,9 @@ def test_format_final_report(report_generator, monkeypatch):
structure = [
{
"name": "Introduction",
- "subsections": [{"name": "Background", "purpose": "Historical context"}],
+ "subsections": [
+ {"name": "Background", "purpose": "Historical context"}
+ ],
},
{
"name": "Findings",
@@ -214,9 +224,7 @@ def test_format_final_report(report_generator, monkeypatch):
# Mock format_links_to_markdown
def mock_format_links(all_links):
- return (
- "1. [Source 1](https://example.com/1)\n2. [Source 2](https://example.com/2)"
- )
+ return "1. [Source 1](https://example.com/1)\n2. [Source 2](https://example.com/2)"
monkeypatch.setattr(
"local_deep_research.utilities.search_utilities.format_links_to_markdown",
@@ -224,7 +232,9 @@ def test_format_final_report(report_generator, monkeypatch):
)
# Call the method
- report = report_generator._format_final_report(sections, structure, "Test query")
+ report = report_generator._format_final_report(
+ sections, structure, "Test query"
+ )
# Verify report structure
assert "content" in report
@@ -259,11 +269,16 @@ def test_generate_report(report_generator, sample_findings, monkeypatch):
mock_research = Mock(return_value={"Section": "Section content"})
mock_format = Mock(
- return_value={"content": "Report content", "metadata": {"query": "Test query"}}
+ return_value={
+ "content": "Report content",
+ "metadata": {"query": "Test query"},
+ }
)
monkeypatch.setattr(
- report_generator, "_determine_report_structure", mock_determine_structure
+ report_generator,
+ "_determine_report_structure",
+ mock_determine_structure,
)
monkeypatch.setattr(
report_generator, "_research_and_generate_sections", mock_research
@@ -274,7 +289,9 @@ def test_generate_report(report_generator, sample_findings, monkeypatch):
result = report_generator.generate_report(sample_findings, "Test query")
# Verify component methods were called with correct arguments
- mock_determine_structure.assert_called_once_with(sample_findings, "Test query")
+ mock_determine_structure.assert_called_once_with(
+ sample_findings, "Test query"
+ )
# Get the expected structure result
structure_result = mock_determine_structure.return_value
@@ -284,7 +301,9 @@ def test_generate_report(report_generator, sample_findings, monkeypatch):
# Get the expected sections result
sections_result = mock_research.return_value
- mock_format.assert_called_once_with(sections_result, structure_result, "Test query")
+ mock_format.assert_called_once_with(
+ sections_result, structure_result, "Test query"
+ )
# Verify result is the formatted report
assert result == mock_format.return_value
diff --git a/tests/test_search_engines_enhanced.py b/tests/test_search_engines_enhanced.py
index a53d5c0548..b3d5794645 100644
--- a/tests/test_search_engines_enhanced.py
+++ b/tests/test_search_engines_enhanced.py
@@ -21,7 +21,9 @@ add_src_to_path()
class TestWikipediaSearchEnhanced:
"""Enhanced Wikipedia search tests using new patterns."""
- def test_wikipedia_search_success(self, monkeypatch, mock_wikipedia_response):
+ def test_wikipedia_search_success(
+ self, monkeypatch, mock_wikipedia_response
+ ):
"""Test successful Wikipedia search."""
# Mock the wikipedia library functions directly instead of requests.get
mock_search_results = ["Artificial intelligence", "Machine learning"]
@@ -150,8 +152,13 @@ class TestArxivSearchEnhanced:
mock_paper = Mock()
mock_paper.entry_id = "2301.12345"
mock_paper.title = "Test Machine Learning Paper"
- mock_paper.summary = "This is a test abstract about machine learning."
- mock_paper.authors = [Mock(name="John Doe"), Mock(name="Jane Smith")]
+ mock_paper.summary = (
+ "This is a test abstract about machine learning."
+ )
+ mock_paper.authors = [
+ Mock(name="John Doe"),
+ Mock(name="Jane Smith"),
+ ]
mock_paper.published = None
mock_paper.journal_ref = None
return [mock_paper]
@@ -180,7 +187,10 @@ class TestSearchEngineFactory:
def test_factory_with_mocked_llm(self, monkeypatch):
"""Test search engine factory with mocked LLM config."""
# Import the mock utilities
- from tests.mock_modules import create_mock_db_utils, create_mock_llm_config
+ from tests.mock_modules import (
+ create_mock_db_utils,
+ create_mock_llm_config,
+ )
# Create mock LLM config
create_mock_llm_config(monkeypatch)
@@ -234,7 +244,9 @@ class TestSearchEngineFactory:
# Mock wikipedia library
monkeypatch.setattr("wikipedia.set_lang", lambda *args, **kwargs: None)
- monkeypatch.setattr("wikipedia.search", lambda query, results: ["Test Result"])
+ monkeypatch.setattr(
+ "wikipedia.search", lambda query, results: ["Test Result"]
+ )
monkeypatch.setattr(
"wikipedia.summary",
lambda title, sentences=5, auto_suggest=False: "Test summary",
@@ -265,7 +277,9 @@ class TestMultipleSearchEngines:
("semantic_scholar", "mock_semantic_scholar_response"),
],
)
- def test_search_engines(self, engine_name, response_fixture, request, monkeypatch):
+ def test_search_engines(
+ self, engine_name, response_fixture, request, monkeypatch
+ ):
"""Test multiple search engines with parametrized fixtures."""
# Get the fixture value dynamically
mock_response_data = request.getfixturevalue(response_fixture)
@@ -273,29 +287,37 @@ class TestMultipleSearchEngines:
# Mock the API response based on engine type
if engine_name == "wikipedia":
# Mock wikipedia library functions directly
- mock_search_results = ["Artificial intelligence", "Machine learning"]
+ mock_search_results = [
+ "Artificial intelligence",
+ "Machine learning",
+ ]
monkeypatch.setattr(
- "wikipedia.search", lambda query, results=10: mock_search_results
+ "wikipedia.search",
+ lambda query, results=10: mock_search_results,
)
def mock_summary(title, sentences=3, auto_suggest=True):
if title == "Artificial intelligence":
return "Artificial intelligence (AI) is intelligence demonstrated by machines."
elif title == "Machine learning":
- return (
- "Machine learning (ML) is a subset of artificial intelligence."
- )
+ return "Machine learning (ML) is a subset of artificial intelligence."
return "Generic summary"
monkeypatch.setattr("wikipedia.summary", mock_summary)
else:
# For other engines, use requests.get mocking
if engine_name == "google_pse":
- mock_response = mock_api_response(200, json_data=mock_response_data)
+ mock_response = mock_api_response(
+ 200, json_data=mock_response_data
+ )
elif engine_name == "semantic_scholar":
- mock_response = mock_api_response(200, json_data=mock_response_data)
+ mock_response = mock_api_response(
+ 200, json_data=mock_response_data
+ )
- monkeypatch.setattr("requests.get", lambda *args, **kwargs: mock_response)
+ monkeypatch.setattr(
+ "requests.get", lambda *args, **kwargs: mock_response
+ )
# Import the appropriate search engine
if engine_name == "wikipedia":
diff --git a/tests/test_search_system.py b/tests/test_search_system.py
index 14288ec1d0..c305819ded 100644
--- a/tests/test_search_system.py
+++ b/tests/test_search_system.py
@@ -55,7 +55,9 @@ def test_progress_callback_forwarding(monkeypatch, mock_search, mock_llm):
"local_deep_research.search_system.StandardSearchStrategy",
mock_strategy_class,
)
- monkeypatch.setattr("local_deep_research.search_system.get_llm", lambda: mock_llm)
+ monkeypatch.setattr(
+ "local_deep_research.search_system.get_llm", lambda: mock_llm
+ )
monkeypatch.setattr(
"local_deep_research.search_system.get_search",
lambda llm_instance=None: mock_search,
@@ -74,7 +76,9 @@ def test_progress_callback_forwarding(monkeypatch, mock_search, mock_llm):
system._progress_callback("Test message", 50, {"test": "metadata"})
# Verify callback was called with correct parameters
- mock_callback.assert_called_once_with("Test message", 50, {"test": "metadata"})
+ mock_callback.assert_called_once_with(
+ "Test message", 50, {"test": "metadata"}
+ )
def test_init_standard_strategy(monkeypatch):
@@ -99,7 +103,9 @@ def test_init_standard_strategy(monkeypatch):
# Also test explicit standard strategy
system_standard = AdvancedSearchSystem(strategy_name="standard")
- assert "StandardSearchStrategy" in system_standard.strategy.__class__.__name__
+ assert (
+ "StandardSearchStrategy" in system_standard.strategy.__class__.__name__
+ )
def test_init_iterdrag_strategy(monkeypatch):
@@ -232,7 +238,10 @@ def test_analyze_topic(monkeypatch):
1: ["Question 1?", "Question 2?"],
2: ["Follow-up 1?", "Follow-up 2?"],
},
- "all_links_of_system": ["https://example.com/1", "https://example.com/2"],
+ "all_links_of_system": [
+ "https://example.com/1",
+ "https://example.com/2",
+ ],
}
# Set the questions_by_iteration attribute on the mock strategy
mock_strategy_instance.questions_by_iteration = {
diff --git a/tests/test_settings_manager.py b/tests/test_settings_manager.py
index 2305fc20db..2f31013406 100644
--- a/tests/test_settings_manager.py
+++ b/tests/test_settings_manager.py
@@ -96,7 +96,9 @@ def test_get_setting_from_env(
mock_db_session = mocker.MagicMock()
monkeypatch.setenv("LDR_TEST_SETTING", env_value)
# Ensure DB query returns an old version to verify environment variable is prioritized
- mock_setting = Setting(key="test.setting", value="db_value", ui_element=ui_element)
+ mock_setting = Setting(
+ key="test.setting", value="db_value", ui_element=ui_element
+ )
mock_db_session.query.return_value.filter.return_value.all.return_value = [
mock_setting
]
@@ -116,7 +118,9 @@ def test_get_setting_default(mocker):
settings_manager = SettingsManager(db_session=mock_db_session)
assert (
- settings_manager.get_setting("non_existent_setting", default="default_value")
+ settings_manager.get_setting(
+ "non_existent_setting", default="default_value"
+ )
== "default_value"
)
@@ -151,9 +155,7 @@ def test_get_setting_invalid_type(mocker):
def test_set_setting_update_existing(mocker):
mock_db_session = mocker.MagicMock()
mock_setting = Setting(key="app.version", value="1.0.0")
- mock_db_session.query.return_value.filter.return_value.first.return_value = (
- mock_setting
- )
+ mock_db_session.query.return_value.filter.return_value.first.return_value = mock_setting
mocker.patch(
"src.local_deep_research.web.services.settings_manager.func.now"
) # Patching the func.now call
@@ -183,7 +185,9 @@ def test_set_setting_create_new(mocker):
assert isinstance(new_setting, Setting)
assert new_setting.key == "new.setting"
assert new_setting.value == "new_value"
- assert new_setting.type == SettingType.APP # Assuming 'app' type for this key
+ assert (
+ new_setting.type == SettingType.APP
+ ) # Assuming 'app' type for this key
mock_db_session.commit.assert_called_once()
mock_db_session.rollback.assert_not_called()
@@ -212,14 +216,14 @@ def test_set_setting_db_error(mocker):
# mock_logger.error.assert_called_once_with("Error setting value for app.version: Simulated DB Error")
-def test_app_get_setting_from_real_db(setup_database_for_all_tests, monkeypatch):
+def test_app_get_setting_from_real_db(
+ setup_database_for_all_tests, monkeypatch
+):
"""
Tests get_setting via settings_service, using the real file-based database.
`setup_database_for_all_tests` yields `SessionLocal`, which is a sessionmaker.
"""
- SessionLocal = (
- setup_database_for_all_tests # Get the SessionLocal class from the fixture
- )
+ SessionLocal = setup_database_for_all_tests # Get the SessionLocal class from the fixture
session = SessionLocal() # Create a new session instance for this test
# Add a setting to the database using this session
@@ -237,7 +241,9 @@ def test_app_get_setting_from_real_db(setup_database_for_all_tests, monkeypatch)
session.add(setting)
session.commit()
- monkeypatch.delenv("LDR_APP_VERSION", raising=False) # Ensure no env override
+ monkeypatch.delenv(
+ "LDR_APP_VERSION", raising=False
+ ) # Ensure no env override
# Call the get_setting function from settings_service
value = get_app_setting("test.app.version.get", db_session=session)
@@ -246,7 +252,9 @@ def test_app_get_setting_from_real_db(setup_database_for_all_tests, monkeypatch)
session.close() # Close the session for this test
-def test_get_all_settings_from_real_file_db(setup_database_for_all_tests, monkeypatch):
+def test_get_all_settings_from_real_file_db(
+ setup_database_for_all_tests, monkeypatch
+):
"""
Tests retrieving all settings from a real *file-based* database.
"""
@@ -283,7 +291,9 @@ def test_get_all_settings_from_real_file_db(setup_database_for_all_tests, monkey
monkeypatch.delenv("LDR_APP_VERSION", raising=False)
monkeypatch.delenv("LDR_LLM_TEMPERATURE", raising=False)
- settings_manager = SettingsManager(db_session=session) # Pass the session instance
+ settings_manager = SettingsManager(
+ db_session=session
+ ) # Pass the session instance
all_settings = settings_manager.get_all_settings()
# Assertions should check for the unique keys
diff --git a/tests/test_url_utils.py b/tests/test_url_utils.py
index cd9bfef65e..2196fb0f67 100644
--- a/tests/test_url_utils.py
+++ b/tests/test_url_utils.py
@@ -23,20 +23,31 @@ class TestNormalizeUrl:
def test_malformed_url_with_scheme(self):
"""Test correction of malformed URLs like 'http:hostname'."""
assert normalize_url("http:localhost:11434") == "http://localhost:11434"
- assert normalize_url("https:example.com:11434") == "https://example.com:11434"
+ assert (
+ normalize_url("https:example.com:11434")
+ == "https://example.com:11434"
+ )
def test_well_formed_urls(self):
"""Test that well-formed URLs are unchanged."""
- assert normalize_url("http://localhost:11434") == "http://localhost:11434"
- assert normalize_url("https://example.com:11434") == "https://example.com:11434"
assert (
- normalize_url("http://192.168.1.100:11434") == "http://192.168.1.100:11434"
+ normalize_url("http://localhost:11434") == "http://localhost:11434"
+ )
+ assert (
+ normalize_url("https://example.com:11434")
+ == "https://example.com:11434"
+ )
+ assert (
+ normalize_url("http://192.168.1.100:11434")
+ == "http://192.168.1.100:11434"
)
def test_urls_with_double_slash_prefix(self):
"""Test URLs that start with //."""
assert normalize_url("//localhost:11434") == "http://localhost:11434"
- assert normalize_url("//example.com:11434") == "https://example.com:11434"
+ assert (
+ normalize_url("//example.com:11434") == "https://example.com:11434"
+ )
def test_empty_or_none_url(self):
"""Test handling of empty or None URLs."""
@@ -47,8 +58,12 @@ class TestNormalizeUrl:
def test_url_with_path(self):
"""Test URLs with paths."""
- assert normalize_url("localhost:11434/api") == "http://localhost:11434/api"
- assert normalize_url("example.com/api/v1") == "https://example.com/api/v1"
+ assert (
+ normalize_url("localhost:11434/api") == "http://localhost:11434/api"
+ )
+ assert (
+ normalize_url("example.com/api/v1") == "https://example.com/api/v1"
+ )
if __name__ == "__main__":
diff --git a/tests/test_url_utils_simple.py b/tests/test_url_utils_simple.py
index 913b844876..ab35f7a241 100644
--- a/tests/test_url_utils_simple.py
+++ b/tests/test_url_utils_simple.py
@@ -15,11 +15,16 @@ def test_url_normalization():
# Test malformed URL with scheme
assert normalize_url("http:localhost:11434") == "http://localhost:11434"
- assert normalize_url("https:example.com:11434") == "https://example.com:11434"
+ assert (
+ normalize_url("https:example.com:11434") == "https://example.com:11434"
+ )
# Test well-formed URLs
assert normalize_url("http://localhost:11434") == "http://localhost:11434"
- assert normalize_url("https://example.com:11434") == "https://example.com:11434"
+ assert (
+ normalize_url("https://example.com:11434")
+ == "https://example.com:11434"
+ )
# Test URLs with double slash prefix
assert normalize_url("//localhost:11434") == "http://localhost:11434"
diff --git a/tests/test_utils.py b/tests/test_utils.py
index 3ab21cb824..8762eed866 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -48,7 +48,9 @@ def mock_api_response(
mock_response.text = json.dumps(json_data)
elif text is not None:
mock_response.text = text
- mock_response.json.side_effect = json.JSONDecodeError("Not JSON", text, 0)
+ mock_response.json.side_effect = json.JSONDecodeError(
+ "Not JSON", text, 0
+ )
else:
mock_response.json.return_value = {}
mock_response.text = "{}"
@@ -66,7 +68,9 @@ def assert_search_result_format(result: Dict[str, Any]):
assert isinstance(result, dict), "Result should be a dictionary"
assert "title" in result, "Result should have a title"
# Some engines use 'link', others use 'url'
- assert "link" in result or "url" in result, "Result should have a link or url"
+ assert "link" in result or "url" in result, (
+ "Result should have a link or url"
+ )
assert "snippet" in result, "Result should have a snippet"
assert isinstance(result["title"], str), "Title should be a string"
# Check whichever field is present
@@ -88,16 +92,20 @@ def assert_findings_format(findings: Dict[str, Any]):
assert "findings" in findings, "Should have findings list"
assert "current_knowledge" in findings, "Should have current_knowledge"
assert "iterations" in findings, "Should have iterations count"
- assert "questions_by_iteration" in findings, "Should have questions_by_iteration"
+ assert "questions_by_iteration" in findings, (
+ "Should have questions_by_iteration"
+ )
assert isinstance(findings["findings"], list), "Findings should be a list"
- assert isinstance(
- findings["current_knowledge"], str
- ), "Knowledge should be a string"
- assert isinstance(findings["iterations"], int), "Iterations should be an integer"
- assert isinstance(
- findings["questions_by_iteration"], dict
- ), "Questions should be a dict"
+ assert isinstance(findings["current_knowledge"], str), (
+ "Knowledge should be a string"
+ )
+ assert isinstance(findings["iterations"], int), (
+ "Iterations should be an integer"
+ )
+ assert isinstance(findings["questions_by_iteration"], dict), (
+ "Questions should be a dict"
+ )
def create_test_research_context(query: str = "test query") -> Dict[str, Any]:
@@ -135,14 +143,20 @@ def mock_progress_callback():
def callback(message: str, progress: int, metadata: Optional[Dict] = None):
calls.append(
- {"message": message, "progress": progress, "metadata": metadata or {}}
+ {
+ "message": message,
+ "progress": progress,
+ "metadata": metadata or {},
+ }
)
return callback, calls
def assert_progress_callback_called(
- calls: List[Dict], expected_message: str = None, expected_progress: int = None
+ calls: List[Dict],
+ expected_message: str = None,
+ expected_progress: int = None,
):
"""
Assert that a progress callback was called with expected parameters.
@@ -156,15 +170,15 @@ def assert_progress_callback_called(
if expected_message:
messages = [call["message"] for call in calls]
- assert any(
- expected_message in msg for msg in messages
- ), f"Expected message '{expected_message}' not found in calls: {messages}"
+ assert any(expected_message in msg for msg in messages), (
+ f"Expected message '{expected_message}' not found in calls: {messages}"
+ )
if expected_progress is not None:
progresses = [call["progress"] for call in calls]
- assert (
- expected_progress in progresses
- ), f"Expected progress {expected_progress} not found in calls: {progresses}"
+ assert expected_progress in progresses, (
+ f"Expected progress {expected_progress} not found in calls: {progresses}"
+ )
class MockCache:
@@ -191,4 +205,8 @@ class MockCache:
self.misses = 0
def get_stats(self) -> Dict[str, int]:
- return {"hits": self.hits, "misses": self.misses, "size": len(self.cache)}
+ return {
+ "hits": self.hits,
+ "misses": self.misses,
+ "size": len(self.cache),
+ }
diff --git a/tests/test_wikipedia_url_security.py b/tests/test_wikipedia_url_security.py
index 4d9036a123..e002208fe6 100644
--- a/tests/test_wikipedia_url_security.py
+++ b/tests/test_wikipedia_url_security.py
@@ -25,7 +25,9 @@ class TestWikipediaURLSecurity:
]
for url in valid_urls:
- assert validate_wikipedia_url(url) is True, f"Valid URL rejected: {url}"
+ assert validate_wikipedia_url(url) is True, (
+ f"Valid URL rejected: {url}"
+ )
def test_invalid_wikipedia_urls(self):
"""Test that invalid/malicious URLs are rejected."""
@@ -54,7 +56,9 @@ class TestWikipediaURLSecurity:
]
for url in invalid_urls:
- assert validate_wikipedia_url(url) is False, f"Invalid URL accepted: {url}"
+ assert validate_wikipedia_url(url) is False, (
+ f"Invalid URL accepted: {url}"
+ )
def test_url_validation_handles_exceptions(self):
"""Test that URL validation handles exceptions gracefully."""
@@ -109,11 +113,13 @@ class TestWikipediaURLSecurity:
for preview in previews:
url = preview.get("link", "")
# URL should be a valid Wikipedia URL
- assert validate_wikipedia_url(url), f"Invalid URL generated: {url}"
+ assert validate_wikipedia_url(url), (
+ f"Invalid URL generated: {url}"
+ )
# URL should follow the expected pattern
- assert url.startswith(
- "https://en.wikipedia.org/wiki/"
- ), f"Unexpected URL format: {url}"
+ assert url.startswith("https://en.wikipedia.org/wiki/"), (
+ f"Unexpected URL format: {url}"
+ )
def test_wikipedia_url_in_response_validation():
@@ -139,7 +145,10 @@ def test_wikipedia_url_in_response_validation():
# Test with mixed valid/invalid URLs
test_response = {
"results": [
- {"title": "Valid Article", "url": "https://en.wikipedia.org/wiki/Valid"},
+ {
+ "title": "Valid Article",
+ "url": "https://en.wikipedia.org/wiki/Valid",
+ },
{
"title": "Invalid Article",
"url": "https://fake-wikipedia.org/wiki/Invalid",