Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix: correct import paths and output directories

LearningCircuit0135248f881f
diff --git a/.gitignore b/.gitignore
index 45fa8bbbbb..03c58d3526 100644
--- a/.gitignore
+++ b/.gitignore
@@ -75,6 +75,9 @@ data/benchmark_results/
data/optimization_results/
examples/*/benchmark_results/
examples/*/optimization_*/
+examples/benchmarks/results/
+examples/optimization/results/
+tests/import_tests/
# Retain directory structure but ignore contents
!data/benchmark_results/.gitkeep
diff --git a/examples/benchmarks/run_browsecomp.py b/examples/benchmarks/run_browsecomp.py
index 19842419e6..481f592195 100644
--- a/examples/benchmarks/run_browsecomp.py
+++ b/examples/benchmarks/run_browsecomp.py
@@ -3,8 +3,17 @@
BrowseComp benchmark with proper decryption.
This script runs the BrowseComp benchmark with proper decryption using the canary field.
+
+Usage:
+ # Install dependencies with PDM
+ cd /path/to/local-deep-research
+ pdm install
+
+ # Run the script with PDM
+ pdm run python examples/benchmarks/run_browsecomp.py --help
"""
+import argparse
import base64
import hashlib
import json
@@ -13,22 +22,24 @@ import os
import re
import sys
import time
-from typing import Dict, Any, List, Optional
+from typing import Any, Dict, List, Optional
# 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__)
-# Add the project root to the path
-sys.path.insert(0, os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))
+# 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 local_deep_research.benchmarks.datasets import load_dataset
-from local_deep_research.benchmarks.templates import BROWSECOMP_QUERY_TEMPLATE
from local_deep_research.api import quick_summary
+from local_deep_research.benchmarks.datasets import load_dataset
from local_deep_research.benchmarks.graders import grade_results
+from local_deep_research.benchmarks.templates import BROWSECOMP_QUERY_TEMPLATE
def derive_key(password: str, length: int) -> bytes:
@@ -56,64 +67,70 @@ def run_browsecomp_with_canary(
search_iterations: int = 1,
questions_per_iteration: int = 1,
search_tool: str = "searxng",
- output_dir: str = "browsecomp_results"
+ output_dir: str = "browsecomp_results",
) -> Dict[str, Any]:
"""
Run BrowseComp benchmark with proper decryption using canary field.
-
+
Args:
num_examples: Number of examples to evaluate
search_iterations: Number of search iterations per query
questions_per_iteration: Number of questions per iteration
search_tool: Search engine to use
output_dir: Directory to save results
-
+
Returns:
Dictionary with benchmark results
"""
# Ensure output directory exists
os.makedirs(output_dir, exist_ok=True)
-
+
# Load BrowseComp dataset
dataset = load_dataset(
dataset_type="browsecomp",
num_examples=num_examples,
seed=42,
)
-
+
# 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")
- evaluation_file = os.path.join(output_dir, f"browsecomp_{timestamp}_evaluation.jsonl")
-
+ evaluation_file = os.path.join(
+ output_dir, f"browsecomp_{timestamp}_evaluation.jsonl"
+ )
+
# Make sure output files don't exist
for file in [results_file, evaluation_file]:
if os.path.exists(file):
os.remove(file)
-
+
# Process each example
results = []
total_examples = len(dataset)
-
+
for i, example in enumerate(dataset):
# Decrypt the problem and answer using the canary
try:
encrypted_question = example.get("problem", "")
encrypted_answer = example.get("answer", "")
canary = example.get("canary", "")
-
+
# Decrypt question and answer
decrypted_question = decrypt(encrypted_question, canary)
decrypted_answer = decrypt(encrypted_answer, canary)
-
- logger.info(f"Processing {i + 1}/{total_examples}: {decrypted_question[:50]}...")
-
+
+ logger.info(
+ f"Processing {i + 1}/{total_examples}: {decrypted_question[:50]}..."
+ )
+
# Format query for BrowseComp
- formatted_query = BROWSECOMP_QUERY_TEMPLATE.format(question=decrypted_question)
-
+ formatted_query = BROWSECOMP_QUERY_TEMPLATE.format(
+ question=decrypted_question
+ )
+
# Time the search
start_time = time.time()
-
+
# Get response from LDR
search_result = quick_summary(
query=formatted_query,
@@ -121,21 +138,21 @@ def run_browsecomp_with_canary(
questions_per_iteration=questions_per_iteration,
search_tool=search_tool,
)
-
+
end_time = time.time()
processing_time = end_time - start_time
-
+
# Extract response
response = search_result.get("summary", "")
-
+
# 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"
-
+
# Extract confidence from the response
confidence_match = re.search(r"Confidence:\s*(\d+)%", response)
confidence = confidence_match.group(1) if confidence_match else "100"
-
+
# Format result
result = {
"id": example.get("id", f"example_{i}"),
@@ -152,37 +169,45 @@ def run_browsecomp_with_canary(
"search_tool": search_tool,
},
}
-
+
# Add to results list
results.append(result)
-
+
# Write result to file
with open(results_file, "a") as f:
f.write(json.dumps(result) + "\n")
-
+
except Exception as e:
logger.error(f"Error processing example {i + 1}: {str(e)}")
-
+
# Create error result
error_result = {
"id": example.get("id", f"example_{i}"),
- "problem": decrypted_question if 'decrypted_question' in locals() else "Error: Could not decrypt problem",
- "correct_answer": decrypted_answer if 'decrypted_answer' in locals() else "Error: Could not decrypt answer",
+ "problem": (
+ decrypted_question
+ if "decrypted_question" in locals()
+ else "Error: Could not decrypt problem"
+ ),
+ "correct_answer": (
+ decrypted_answer
+ if "decrypted_answer" in locals()
+ else "Error: Could not decrypt answer"
+ ),
"error": str(e),
"processing_time": (
time.time() - start_time if "start_time" in locals() else 0
),
}
-
+
# Add to results list
results.append(error_result)
-
+
# Write error result to file
with open(results_file, "a") as f:
f.write(json.dumps(error_result) + "\n")
-
+
logger.info(f"Completed processing {total_examples} examples")
-
+
# Run evaluation
logger.info("Running automated evaluation...")
try:
@@ -194,12 +219,18 @@ def run_browsecomp_with_canary(
except Exception as e:
logger.error(f"Evaluation failed: {str(e)}")
evaluation_results = []
-
+
# Calculate basic metrics
- correct_count = sum(1 for result in evaluation_results if result.get("is_correct", False))
+ correct_count = sum(
+ 1 for result in evaluation_results if result.get("is_correct", False)
+ )
accuracy = correct_count / len(results) if results else 0
- avg_time = sum(result.get("processing_time", 0) for result in results) / len(results) if results else 0
-
+ avg_time = (
+ sum(result.get("processing_time", 0) for result in results) / len(results)
+ if results
+ else 0
+ )
+
print("\nBrowseComp Benchmark Results:")
print(f" Accuracy: {accuracy:.3f}")
print(f" Total examples: {total_examples}")
@@ -207,7 +238,7 @@ def run_browsecomp_with_canary(
print(f" Average time: {avg_time:.2f}s")
print()
print(f"Report saved to: {evaluation_file}")
-
+
return {
"status": "complete",
"dataset_type": "browsecomp",
@@ -221,15 +252,30 @@ def run_browsecomp_with_canary(
def main():
"""Run the BrowseComp benchmark with command-line arguments."""
- parser = argparse.ArgumentParser(description="Run BrowseComp benchmark with proper decryption")
- parser.add_argument("--examples", type=int, default=2, help="Number of examples to run")
- parser.add_argument("--iterations", type=int, default=1, help="Number of search iterations")
- parser.add_argument("--questions", type=int, default=1, help="Questions per iteration")
- parser.add_argument("--search-tool", type=str, default="searxng", help="Search tool to use")
- parser.add_argument("--output-dir", type=str, default="browsecomp_results", help="Output directory")
-
+ parser = argparse.ArgumentParser(
+ description="Run BrowseComp benchmark with proper decryption"
+ )
+ parser.add_argument(
+ "--examples", type=int, default=2, help="Number of examples to run"
+ )
+ parser.add_argument(
+ "--iterations", type=int, default=1, help="Number of search iterations"
+ )
+ parser.add_argument(
+ "--questions", type=int, default=1, help="Questions per iteration"
+ )
+ parser.add_argument(
+ "--search-tool", type=str, default="searxng", help="Search tool to use"
+ )
+ parser.add_argument(
+ "--output-dir",
+ type=str,
+ default=os.path.join("examples", "benchmarks", "results", "browsecomp"),
+ help="Output directory",
+ )
+
args = parser.parse_args()
-
+
run_browsecomp_with_canary(
num_examples=args.examples,
search_iterations=args.iterations,
@@ -237,9 +283,9 @@ def main():
search_tool=args.search_tool,
output_dir=args.output_dir,
)
-
+
return 0
if __name__ == "__main__":
- sys.exit(main())
\ No newline at end of file
+ sys.exit(main())
diff --git a/examples/benchmarks/run_simpleqa.py b/examples/benchmarks/run_simpleqa.py
index fab3216f85..eff168d243 100644
--- a/examples/benchmarks/run_simpleqa.py
+++ b/examples/benchmarks/run_simpleqa.py
@@ -3,14 +3,25 @@
SimpleQA Benchmark Runner for Local Deep Research.
This script provides a convenient way to run the SimpleQA benchmark.
+
+Usage:
+ # Install dependencies with PDM
+ cd /path/to/local-deep-research
+ pdm install
+
+ # Run the script with PDM
+ pdm run python examples/benchmarks/run_simpleqa.py --help
"""
import argparse
-import sys
import os
+import sys
-# Add the project root to the path
-sys.path.insert(0, os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))
+# 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
@@ -19,22 +30,39 @@ from local_deep_research.benchmarks.benchmark_functions import evaluate_simpleqa
def main():
"""Run the SimpleQA benchmark with the specified parameters."""
parser = argparse.ArgumentParser(description="Run SimpleQA benchmark")
- parser.add_argument("--examples", type=int, default=10, help="Number of examples to run")
- parser.add_argument("--iterations", type=int, default=3, help="Number of search iterations")
- parser.add_argument("--questions", type=int, default=3, help="Questions per iteration")
- parser.add_argument("--search-tool", type=str, default="searxng", help="Search tool to use")
- parser.add_argument("--output-dir", type=str, default="benchmark_results", help="Output directory")
+ parser.add_argument(
+ "--examples", type=int, default=10, help="Number of examples to run"
+ )
+ parser.add_argument(
+ "--iterations", type=int, default=3, help="Number of search iterations"
+ )
+ parser.add_argument(
+ "--questions", type=int, default=3, help="Questions per iteration"
+ )
+ parser.add_argument(
+ "--search-tool", type=str, default="searxng", help="Search tool to use"
+ )
+ parser.add_argument(
+ "--output-dir",
+ type=str,
+ default=os.path.join("examples", "benchmarks", "results", "simpleqa"),
+ help="Output directory",
+ )
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(
+ "--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-provider", type=str, help="Provider to use for evaluation")
-
+ parser.add_argument(
+ "--eval-provider", type=str, help="Provider to use for evaluation"
+ )
+
args = parser.parse_args()
-
+
print(f"Starting SimpleQA benchmark with {args.examples} examples...")
-
+
# Run the benchmark
results = evaluate_simpleqa(
num_examples=args.examples,
@@ -46,15 +74,15 @@ def main():
evaluation_provider=args.eval_provider,
output_dir=args.output_dir,
)
-
+
# Print summary
print("\nSimpleQA Benchmark Results:")
print(f" Accuracy: {results.get('accuracy', 0):.3f}")
print(f" Total examples: {results.get('total_examples', 0)}")
print(f" Report saved to: {results.get('report_path', '')}")
-
+
return 0
if __name__ == "__main__":
- sys.exit(main())
\ No newline at end of file
+ sys.exit(main())
diff --git a/examples/optimization/example_optimization.py b/examples/optimization/example_optimization.py
index 8abba4535e..c9d5c67adf 100644
--- a/examples/optimization/example_optimization.py
+++ b/examples/optimization/example_optimization.py
@@ -1,28 +1,51 @@
# example_optimization.py - Quick Demo Version
+"""
+Full parameter optimization example for Local Deep Research.
+
+This script demonstrates the full parameter optimization functionality.
+
+Usage:
+ # Install dependencies with PDM
+ cd /path/to/local-deep-research
+ pdm install
+
+ # Run the script with PDM
+ pdm run python examples/optimization/example_optimization.py
+"""
+
-import os
-import logging
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_parameters,
+ optimize_for_quality,
optimize_for_speed,
- optimize_for_quality
+ 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"
)
+
def main():
# Create timestamp for unique output directory
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
- output_dir = f"optimization_results_{timestamp}"
+ output_dir = os.path.join(
+ "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}")
@@ -52,11 +75,11 @@ def main():
balanced_params, balanced_score = optimize_parameters(
query="SimpleQA quick demo", # Task descriptor
- search_tool="searxng", # Using SearXNG
- n_trials=2, # Just 2 trials for quick demo
+ search_tool="searxng", # Using SearXNG
+ n_trials=2, # Just 2 trials for quick demo
output_dir=os.path.join(output_dir, "demo"),
- param_space=param_space, # Limited parameter space
- metric_weights={"quality": 0.5, "speed": 0.5}
+ param_space=param_space, # Limited parameter space
+ metric_weights={"quality": 0.5, "speed": 0.5},
)
print(f"Best parameters: {balanced_params}")
@@ -65,10 +88,7 @@ def main():
# Save demo results to a summary file
summary = {
"timestamp": timestamp,
- "demo": {
- "parameters": balanced_params,
- "score": balanced_score
- }
+ "demo": {"parameters": balanced_params, "score": balanced_score},
}
with open(os.path.join(output_dir, "optimization_summary.json"), "w") as f:
@@ -77,5 +97,6 @@ def main():
print(f"\nDemo complete! Results saved to {output_dir}")
print(f"Recommended parameters: {balanced_params}")
+
if __name__ == "__main__":
main()
diff --git a/examples/optimization/example_quick_optimization.py b/examples/optimization/example_quick_optimization.py
index 7319d3e985..580a4f258b 100644
--- a/examples/optimization/example_quick_optimization.py
+++ b/examples/optimization/example_quick_optimization.py
@@ -1,98 +1,117 @@
# example_quick_optimization.py - Simplified Demo
+"""
+Simplified parameter optimization demo for Local Deep Research.
+
+This script demonstrates basic parameter optimization with simulated results.
+
+Usage:
+ # Install dependencies with PDM
+ cd /path/to/local-deep-research
+ pdm install
+
+ # Run the script with PDM
+ pdm run python examples/optimization/example_quick_optimization.py
+"""
+
-import os
-import logging
import json
-import time
+import logging
+import os
import random
+import time
from datetime import datetime
-from typing import Dict, Any, Tuple
+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__)
+
def simulate_optimization(
param_space: Dict[str, Any],
n_trials: int = 5,
- metric_weights: Dict[str, float] = None
+ metric_weights: Dict[str, float] = None,
) -> Tuple[Dict[str, Any], float]:
"""
Simulate an optimization process without actually running benchmarks.
This is just for demonstration purposes.
-
+
Args:
param_space: Dictionary defining parameter search spaces
n_trials: Number of simulated trials
metric_weights: Weights for quality vs speed metrics
-
+
Returns:
Tuple of (best_parameters, best_score)
"""
if metric_weights is None:
metric_weights = {"quality": 0.5, "speed": 0.5}
-
+
logger.info(f"Starting simulated optimization with {n_trials} trials")
logger.info(f"Parameter space: {param_space}")
logger.info(f"Metric weights: {metric_weights}")
-
+
# Generate random trials
best_score = 0.0
best_params = {}
-
+
for i in range(n_trials):
# Generate random parameters
params = {}
for param_name, param_config in param_space.items():
if param_config.get("type") == "int":
params[param_name] = random.randint(
- param_config.get("low", 1),
- param_config.get("high", 5)
+ param_config.get("low", 1), param_config.get("high", 5)
)
elif param_config.get("type") == "categorical":
- params[param_name] = random.choice(param_config.get("choices", ["standard"]))
-
+ params[param_name] = random.choice(
+ param_config.get("choices", ["standard"])
+ )
+
logger.info(f"Trial {i}: Testing parameters: {params}")
-
+
# Simulate execution delay
time.sleep(1)
-
+
# Simulate metrics calculation
quality_score = random.uniform(0.5, 0.9) # Random quality score
- speed_score = 1.0 - (params.get("iterations", 1) * 0.1) # More iterations = slower
-
+ speed_score = 1.0 - (
+ params.get("iterations", 1) * 0.1
+ ) # More iterations = slower
+
# Calculate weighted score
- combined_score = (
- quality_score * metric_weights.get("quality", 0.5) +
- speed_score * metric_weights.get("speed", 0.5)
+ combined_score = quality_score * metric_weights.get(
+ "quality", 0.5
+ ) + speed_score * metric_weights.get("speed", 0.5)
+
+ logger.info(
+ f"Trial {i}: Quality: {quality_score:.2f}, Speed: {speed_score:.2f}, Score: {combined_score:.2f}"
)
-
- logger.info(f"Trial {i}: Quality: {quality_score:.2f}, Speed: {speed_score:.2f}, Score: {combined_score:.2f}")
-
+
# Update best parameters if this trial is better
if combined_score > best_score:
best_score = combined_score
best_params = params.copy()
- logger.info(f"New best parameters found: {best_params} with score: {best_score:.2f}")
-
+ logger.info(
+ f"New best parameters found: {best_params} with score: {best_score:.2f}"
+ )
+
return best_params, best_score
def optimize_for_speed(
- param_space: Dict[str, Any] = None,
- n_trials: int = 3
+ param_space: Dict[str, Any] = None, n_trials: int = 3
) -> Tuple[Dict[str, Any], float]:
"""
Simulate speed-focused optimization.
-
+
Args:
param_space: Parameter space definition (optional)
n_trials: Number of trials
-
+
Returns:
Tuple of (best_parameters, best_score)
"""
@@ -113,31 +132,28 @@ def optimize_for_speed(
"choices": ["rapid", "parallel"],
},
}
-
+
# Speed-focused weights
metric_weights = {
"speed": 0.8,
"quality": 0.2,
}
-
+
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
)
def optimize_for_quality(
- param_space: Dict[str, Any] = None,
- n_trials: int = 3
+ param_space: Dict[str, Any] = None, n_trials: int = 3
) -> Tuple[Dict[str, Any], float]:
"""
Simulate quality-focused optimization.
-
+
Args:
param_space: Parameter space definition (optional)
n_trials: Number of trials
-
+
Returns:
Tuple of (best_parameters, best_score)
"""
@@ -158,28 +174,28 @@ def optimize_for_quality(
"choices": ["standard", "iterdrag", "source_based"],
},
}
-
+
# Quality-focused weights
metric_weights = {
"quality": 0.9,
"speed": 0.1,
}
-
+
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
)
def main():
# Create timestamp for unique output directory
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
- output_dir = f"optimization_demo_{timestamp}"
+ output_dir = os.path.join(
+ "examples", "optimization", "results", f"optimization_demo_{timestamp}"
+ )
os.makedirs(output_dir, exist_ok=True)
-
+
print(f"Starting quick optimization demo - results will be saved to {output_dir}")
-
+
# Create a simple parameter space for demonstration
param_space = {
"iterations": {
@@ -197,61 +213,54 @@ def main():
"choices": ["rapid", "standard", "iterdrag"],
},
}
-
+
# Run a balanced optimization
print("\n=== Running balanced optimization simulation ===")
balanced_params, balanced_score = simulate_optimization(
param_space=param_space,
n_trials=4,
- metric_weights={"quality": 0.6, "speed": 0.4}
+ metric_weights={"quality": 0.6, "speed": 0.4},
)
-
+
print(f"Best balanced parameters: {balanced_params}")
print(f"Best balanced score: {balanced_score:.4f}")
-
+
# Run a speed optimization
print("\n=== Running speed-focused optimization simulation ===")
speed_params, speed_score = optimize_for_speed(n_trials=3)
-
+
print(f"Best speed parameters: {speed_params}")
print(f"Best speed score: {speed_score:.4f}")
-
+
# Run a quality optimization
print("\n=== Running quality-focused optimization simulation ===")
quality_params, quality_score = optimize_for_quality(n_trials=3)
-
+
print(f"Best quality parameters: {quality_params}")
print(f"Best quality score: {quality_score:.4f}")
-
+
# Save results
summary = {
"timestamp": timestamp,
- "balanced": {
- "parameters": balanced_params,
- "score": float(balanced_score)
- },
- "speed": {
- "parameters": speed_params,
- "score": float(speed_score)
- },
- "quality": {
- "parameters": quality_params,
- "score": float(quality_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)},
}
-
+
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("\nRecommended parameters:")
print(f"- For balanced performance: {balanced_params}")
print(f"- For speed: {speed_params}")
print(f"- For quality: {quality_params}")
-
- print("\nNote: This is a simulation for demonstration purposes only. Real optimization")
+
+ print(
+ "\nNote: This is a simulation for demonstration purposes only. Real optimization"
+ )
print("would run actual benchmarks with these parameters to evaluate performance.")
if __name__ == "__main__":
- main()
\ No newline at end of file
+ main()
diff --git a/examples/optimization/run_optimization.py b/examples/optimization/run_optimization.py
index 4e0c9f1f2b..b86e410751 100644
--- a/examples/optimization/run_optimization.py
+++ b/examples/optimization/run_optimization.py
@@ -3,48 +3,76 @@
Parameter Optimization Runner for Local Deep Research.
This script provides a convenient way to run hyperparameter optimization.
+
+Usage:
+ # Install dependencies with PDM
+ cd /path/to/local-deep-research
+ pdm install
+
+ # Run the script with PDM
+ pdm run python examples/optimization/run_optimization.py --help
"""
import argparse
+import json
import os
import sys
-import json
from datetime import datetime
-# Add the project root to the path
-sys.path.insert(0, os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))
+# 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_parameters,
- optimize_for_speed,
+ optimize_for_efficiency,
optimize_for_quality,
- optimize_for_efficiency
+ optimize_for_speed,
+ optimize_parameters,
)
def main():
"""Run parameter optimization with command-line arguments."""
- parser = argparse.ArgumentParser(description="Run parameter optimization for Local Deep Research")
+ parser = argparse.ArgumentParser(
+ description="Run parameter optimization for Local Deep Research"
+ )
parser.add_argument("query", help="Research query to optimize for")
- parser.add_argument("--output-dir", default="optimization_results", help="Directory to save results")
+ parser.add_argument(
+ "--output-dir",
+ 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("--model", help="Model name for the LLM")
parser.add_argument("--provider", help="Provider for the LLM")
- parser.add_argument("--trials", type=int, default=30, help="Number of parameter combinations to try")
- parser.add_argument("--mode", choices=["balanced", "speed", "quality", "efficiency"],
- default="balanced", help="Optimization mode")
- parser.add_argument("--weights", help="Custom weights as JSON string, e.g., '{\"quality\": 0.7, \"speed\": 0.3}'")
-
+ parser.add_argument(
+ "--trials", type=int, default=30, help="Number of parameter combinations to try"
+ )
+ parser.add_argument(
+ "--mode",
+ choices=["balanced", "speed", "quality", "efficiency"],
+ default="balanced",
+ help="Optimization mode",
+ )
+ parser.add_argument(
+ "--weights",
+ help='Custom weights as JSON string, e.g., \'{"quality": 0.7, "speed": 0.3}\'',
+ )
+
args = parser.parse_args()
-
+
# Create timestamp for unique output directory
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_dir = os.path.join(args.output_dir, f"opt_{timestamp}")
os.makedirs(output_dir, exist_ok=True)
-
- print(f"Starting optimization ({args.mode} mode) - results will be saved to {output_dir}")
-
+
+ print(
+ f"Starting optimization ({args.mode} mode) - results will be saved to {output_dir}"
+ )
+
# Parse custom weights if provided
custom_weights = None
if args.weights:
@@ -52,7 +80,7 @@ def main():
custom_weights = json.loads(args.weights)
except json.JSONDecodeError:
print("Error parsing weights JSON. Using default weights.")
-
+
# Run optimization based on mode
if args.mode == "speed":
best_params, best_score = optimize_for_speed(
@@ -61,7 +89,7 @@ def main():
n_trials=args.trials,
model_name=args.model,
provider=args.provider,
- output_dir=output_dir
+ output_dir=output_dir,
)
elif args.mode == "quality":
best_params, best_score = optimize_for_quality(
@@ -70,7 +98,7 @@ def main():
n_trials=args.trials,
model_name=args.model,
provider=args.provider,
- output_dir=output_dir
+ output_dir=output_dir,
)
elif args.mode == "efficiency":
best_params, best_score = optimize_for_efficiency(
@@ -79,7 +107,7 @@ def main():
n_trials=args.trials,
model_name=args.model,
provider=args.provider,
- output_dir=output_dir
+ output_dir=output_dir,
)
else: # balanced
best_params, best_score = optimize_parameters(
@@ -89,13 +117,13 @@ def main():
model_name=args.model,
provider=args.provider,
output_dir=output_dir,
- metric_weights=custom_weights
+ metric_weights=custom_weights,
)
-
+
print(f"\nOptimization complete! Results saved to {output_dir}")
print(f"Best parameters: {best_params}")
print(f"Best score: {best_score:.4f}")
-
+
# Save summary to a JSON file
summary = {
"timestamp": timestamp,
@@ -105,14 +133,14 @@ def main():
"search_tool": args.search_tool,
"best_parameters": best_params,
"best_score": best_score,
- "custom_weights": custom_weights
+ "custom_weights": custom_weights,
}
-
+
with open(os.path.join(output_dir, "optimization_summary.json"), "w") as f:
json.dump(summary, f, indent=2)
-
+
return 0
if __name__ == "__main__":
- sys.exit(main())
\ No newline at end of file
+ sys.exit(main())
diff --git a/pyproject.toml b/pyproject.toml
index 8252fc152d..3e81be2da6 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -60,6 +60,9 @@ dependencies = [
"methodtools>=0.4.7",
"loguru>=0.7.3",
"matplotlib>=3.10.3",
+ "pandas>=2.2.3",
+ "plotly>=6.0.1",
+ "kaleido==0.1.0",
]
[project.urls]
diff --git a/src/local_deep_research/benchmarks/cli.py b/src/local_deep_research/benchmarks/cli.py
index 8d91e0a451..c651265295 100644
--- a/src/local_deep_research/benchmarks/cli.py
+++ b/src/local_deep_research/benchmarks/cli.py
@@ -10,16 +10,15 @@ import logging
import os
import sys
from datetime import datetime
-from typing import List, Dict, Any, Optional
+from typing import Any, Dict, List, Optional
-from local_deep_research.benchmarks.optimization import optimize_parameters
-from local_deep_research.benchmarks.comparison import compare_configurations
-from local_deep_research.benchmarks.efficiency import SpeedProfiler, ResourceMonitor
+from .comparison import compare_configurations
+from .efficiency import ResourceMonitor, SpeedProfiler
+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__)
@@ -27,7 +26,7 @@ logger = logging.getLogger(__name__)
def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
- description='Local Deep Research Benchmarking Tools',
+ description="Local Deep Research Benchmarking Tools",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
@@ -39,75 +38,101 @@ Examples:
# Run efficiency profiling
python -m local_deep_research.benchmarks.cli profile "How do neural networks work?"
-"""
+""",
)
-
- subparsers = parser.add_subparsers(dest='command', help='Command to run')
-
+
+ subparsers = parser.add_subparsers(dest="command", help="Command to run")
+
# Optimizer parser
- 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', default='data/optimization_results',
- help='Directory to save results')
- optimize_parser.add_argument('--model', help='Model name for the LLM')
- optimize_parser.add_argument('--provider', help='Provider for the LLM')
- optimize_parser.add_argument('--search-tool', help='Search tool to use')
- optimize_parser.add_argument('--temperature', type=float, default=0.7,
- help='LLM temperature')
- optimize_parser.add_argument('--n-trials', type=int, default=30,
- help='Number of parameter combinations to try')
- optimize_parser.add_argument('--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')
- 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')
-
+ 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",
+ default="data/optimization_results",
+ help="Directory to save results",
+ )
+ optimize_parser.add_argument("--model", help="Model name for the LLM")
+ optimize_parser.add_argument("--provider", help="Provider for the LLM")
+ optimize_parser.add_argument("--search-tool", help="Search tool to use")
+ optimize_parser.add_argument(
+ "--temperature", type=float, default=0.7, help="LLM temperature"
+ )
+ optimize_parser.add_argument(
+ "--n-trials",
+ type=int,
+ default=30,
+ help="Number of parameter combinations to try",
+ )
+ optimize_parser.add_argument(
+ "--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"
+ )
+ 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"
+ )
+
# Comparison parser
- 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')
- compare_parser.add_argument('--output-dir', default='data/benchmark_results/comparison',
- help='Directory to save results')
- compare_parser.add_argument('--model', help='Model name for the LLM')
- compare_parser.add_argument('--provider', help='Provider for the LLM')
- compare_parser.add_argument('--search-tool', help='Search tool to use')
- compare_parser.add_argument('--repetitions', type=int, default=1,
- help='Number of repetitions for each configuration')
-
+ 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"
+ )
+ compare_parser.add_argument(
+ "--output-dir",
+ default="data/benchmark_results/comparison",
+ help="Directory to save results",
+ )
+ compare_parser.add_argument("--model", help="Model name for the LLM")
+ compare_parser.add_argument("--provider", help="Provider for the LLM")
+ compare_parser.add_argument("--search-tool", help="Search tool to use")
+ compare_parser.add_argument(
+ "--repetitions",
+ type=int,
+ default=1,
+ help="Number of repetitions for each configuration",
+ )
+
# Profiling parser
- 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', default='data/benchmark_results/profiling',
- help='Directory to save results')
- profile_parser.add_argument('--model', help='Model name for the LLM')
- profile_parser.add_argument('--provider', help='Provider for the LLM')
- profile_parser.add_argument('--search-tool', help='Search tool to use')
- profile_parser.add_argument('--iterations', type=int, default=2,
- help='Number of search iterations')
- profile_parser.add_argument('--questions', type=int, default=2,
- help='Questions per iteration')
- profile_parser.add_argument('--strategy', default='iterdrag',
- help='Search strategy to use')
-
+ 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",
+ default="data/benchmark_results/profiling",
+ help="Directory to save results",
+ )
+ profile_parser.add_argument("--model", help="Model name for the LLM")
+ profile_parser.add_argument("--provider", help="Provider for the LLM")
+ profile_parser.add_argument("--search-tool", help="Search tool to use")
+ profile_parser.add_argument(
+ "--iterations", type=int, default=2, help="Number of search iterations"
+ )
+ profile_parser.add_argument(
+ "--questions", type=int, default=2, help="Questions per iteration"
+ )
+ profile_parser.add_argument(
+ "--strategy", default="iterdrag", help="Search strategy to use"
+ )
+
return parser.parse_args()
def run_optimization(args):
"""Run parameter optimization."""
logger.info(f"Starting parameter optimization for query: {args.query}")
-
+
# Determine metric weights based on focus
metric_weights = None
if args.speed_focus:
metric_weights = {"speed": 0.8, "quality": 0.2}
elif args.quality_focus:
metric_weights = {"quality": 0.8, "speed": 0.2}
-
+
# Run optimization
best_params, best_score = optimize_parameters(
query=args.query,
@@ -120,41 +145,41 @@ def run_optimization(args):
timeout=args.timeout,
n_jobs=args.n_jobs,
study_name=args.study_name,
- metric_weights=metric_weights
+ metric_weights=metric_weights,
)
-
+
# Print results
print("\nOptimization Results:")
print("====================")
print(f"Best Parameters: {best_params}")
print(f"Best Score: {best_score:.4f}")
print(f"Results saved to: {args.output_dir}")
-
+
return 0
def run_comparison(args):
"""Run configuration comparison."""
import json
-
+
logger.info(f"Comparing configurations for query: {args.query}")
-
+
# Load configurations from file
try:
- with open(args.configs, 'r') as f:
+ with open(args.configs, "r") as f:
configurations = json.load(f)
-
+
if not isinstance(configurations, list):
logger.error("Configurations file must contain a JSON array")
return 1
-
+
if not configurations:
logger.error("No configurations found in the file")
return 1
except Exception as e:
logger.error(f"Error loading configurations file: {str(e)}")
return 1
-
+
# Run comparison
results = compare_configurations(
query=args.query,
@@ -163,87 +188,87 @@ def run_comparison(args):
model_name=args.model,
provider=args.provider,
search_tool=args.search_tool,
- repetitions=args.repetitions
+ repetitions=args.repetitions,
)
-
+
# Print summary
print("\nComparison Results:")
print("==================")
print(f"Configurations tested: {results['configurations_tested']}")
print(f"Successful configurations: {results['successful_configurations']}")
print(f"Failed configurations: {results['failed_configurations']}")
-
+
# Print ranking
print("\nRanking by Overall Score:")
- for i, result in enumerate([r for r in results['results'] if r.get('success', False)]):
+ 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"\nResults saved to: {results.get('report_path', args.output_dir)}")
-
+
return 0
def run_profiling(args):
"""Run resource profiling."""
+ import json
+
from local_deep_research.config.llm_config import get_llm
from local_deep_research.config.search_config import get_search
from local_deep_research.search_system import AdvancedSearchSystem
- import json
-
+
logger.info(f"Profiling resource usage for query: {args.query}")
-
+
# Create output directory
os.makedirs(args.output_dir, exist_ok=True)
-
+
# Initialize profiling tools
speed_profiler = SpeedProfiler()
resource_monitor = ResourceMonitor(sampling_interval=0.5)
-
+
# Start profiling
speed_profiler.start()
resource_monitor.start()
-
+
try:
# Initialize system
with speed_profiler.timer("initialization"):
# Get LLM
- llm = get_llm(
- model_name=args.model,
- provider=args.provider
- )
-
+ llm = get_llm(model_name=args.model, provider=args.provider)
+
# Get search engine
search = None
if args.search_tool:
search = get_search(args.search_tool, llm_instance=llm)
-
+
# Create search system
system = AdvancedSearchSystem(llm=llm, search=search)
system.max_iterations = args.iterations
system.questions_per_iteration = args.questions
system.strategy_name = args.strategy
-
+
# Run analysis
with speed_profiler.timer("analysis"):
results = system.analyze_topic(args.query)
-
+
# Stop profiling
speed_profiler.stop()
resource_monitor.stop()
-
+
# Get profiling results
timing_results = speed_profiler.get_summary()
resource_results = resource_monitor.get_combined_stats()
-
+
# Print summary
print("\nProfiling Results:")
print("=================")
-
+
# Timing summary
print("\nTiming Summary:")
total_duration = timing_results.get("total_duration", 0)
print(f"Total execution time: {total_duration:.2f} seconds")
-
+
# Component breakdown
print("\nComponent Breakdown:")
for name, value in timing_results.items():
@@ -252,45 +277,53 @@ def run_profiling(args):
duration = value
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"Average memory: {resource_results.get('process_memory_avg_mb', 0):.1f} MB")
+ print(
+ f"Average memory: {resource_results.get('process_memory_avg_mb', 0):.1f} MB"
+ )
print(f"Peak CPU: {resource_results.get('process_cpu_max', 0):.1f}%")
print(f"Average CPU: {resource_results.get('process_cpu_avg', 0):.1f}%")
-
+
# Save results
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
- results_file = os.path.join(args.output_dir, f"profiling_results_{timestamp}.json")
-
- with open(results_file, 'w') as f:
- json.dump({
- "query": args.query,
- "configuration": {
- "model": args.model,
- "provider": args.provider,
- "search_tool": args.search_tool,
- "iterations": args.iterations,
- "questions_per_iteration": args.questions,
- "strategy": args.strategy
+ results_file = os.path.join(
+ args.output_dir, f"profiling_results_{timestamp}.json"
+ )
+
+ with open(results_file, "w") as f:
+ json.dump(
+ {
+ "query": args.query,
+ "configuration": {
+ "model": args.model,
+ "provider": args.provider,
+ "search_tool": args.search_tool,
+ "iterations": args.iterations,
+ "questions_per_iteration": args.questions,
+ "strategy": args.strategy,
+ },
+ "timing_results": timing_results,
+ "resource_results": resource_results,
+ "findings_count": len(results.get("findings", [])),
+ "knowledge_length": len(results.get("current_knowledge", "")),
+ "timestamp": timestamp,
},
- "timing_results": timing_results,
- "resource_results": resource_results,
- "findings_count": len(results.get("findings", [])),
- "knowledge_length": len(results.get("current_knowledge", "")),
- "timestamp": timestamp
- }, f, indent=2)
-
+ f,
+ indent=2,
+ )
+
print(f"\nDetailed results saved to: {results_file}")
-
+
return 0
-
+
except Exception as e:
# Stop profiling on error
speed_profiler.stop()
resource_monitor.stop()
-
+
logger.error(f"Error during profiling: {str(e)}")
return 1
@@ -298,17 +331,17 @@ def run_profiling(args):
def main():
"""Main entry point for the CLI."""
args = parse_args()
-
- if args.command == 'optimize':
+
+ if args.command == "optimize":
return run_optimization(args)
- elif args.command == 'compare':
+ elif args.command == "compare":
return run_comparison(args)
- elif args.command == 'profile':
+ elif args.command == "profile":
return run_profiling(args)
else:
print("Please specify a command. Use --help for more information.")
return 1
-if __name__ == '__main__':
+if __name__ == "__main__":
sys.exit(main())
diff --git a/src/local_deep_research/benchmarks/optimization/api.py b/src/local_deep_research/benchmarks/optimization/api.py
index 5ca002e836..df541f94f3 100644
--- a/src/local_deep_research/benchmarks/optimization/api.py
+++ b/src/local_deep_research/benchmarks/optimization/api.py
@@ -17,7 +17,7 @@ logger = logging.getLogger(__name__)
def optimize_parameters(
query: str,
param_space: Optional[Dict[str, Any]] = None,
- output_dir: str = "data/optimization_results",
+ output_dir: str = os.path.join("data", "optimization_results"),
model_name: Optional[str] = None,
provider: Optional[str] = None,
search_tool: Optional[str] = None,
@@ -76,7 +76,7 @@ def optimize_parameters(
def optimize_for_speed(
query: str,
n_trials: int = 20,
- output_dir: str = "data/optimization_results",
+ output_dir: str = os.path.join("data", "optimization_results"),
model_name: Optional[str] = None,
provider: Optional[str] = None,
search_tool: Optional[str] = None,
@@ -137,7 +137,7 @@ def optimize_for_speed(
def optimize_for_quality(
query: str,
n_trials: int = 30,
- output_dir: str = "data/optimization_results",
+ output_dir: str = os.path.join("data", "optimization_results"),
model_name: Optional[str] = None,
provider: Optional[str] = None,
search_tool: Optional[str] = None,
@@ -177,7 +177,7 @@ def optimize_for_quality(
def optimize_for_efficiency(
query: str,
n_trials: int = 25,
- output_dir: str = "data/optimization_results",
+ output_dir: str = os.path.join("data", "optimization_results"),
model_name: Optional[str] = None,
provider: Optional[str] = None,
search_tool: Optional[str] = None,