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.

Add multi-benchmark optimization with weighted scores

LearningCircuit7cad85d5adac
diff --git a/examples/optimization/browsecomp_optimization.py b/examples/optimization/browsecomp_optimization.py
index b25eddc5d4..c44fa54b8c 100755
--- a/examples/optimization/browsecomp_optimization.py
+++ b/examples/optimization/browsecomp_optimization.py
@@ -14,36 +14,35 @@ Usage:
pdm run python examples/optimization/browsecomp_optimization.py
"""
-import os
-import sys
import json
import logging
+import os
+import sys
from datetime import datetime
+from local_deep_research.benchmarks.optimization import optimize_parameters
+
# Add the src directory to the Python path
-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,
+project_root = os.path.abspath(
+ os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
)
+sys.path.insert(0, os.path.join(project_root, "src"))
# Configure logging 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__)
+
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"browsecomp_opt_{timestamp}")
+ output_dir = os.path.join(
+ "examples", "optimization", "results", f"browsecomp_opt_{timestamp}"
+ )
os.makedirs(output_dir, exist_ok=True)
-
+
print(f"Starting BrowseComp optimization - results will be saved to {output_dir}")
# Define a simple parameter space for demonstration
@@ -65,7 +64,7 @@ def main():
"choices": ["rapid", "standard", "parallel"],
},
}
-
+
# Run optimization with BrowseComp benchmark
# Using a small number of trials and examples for demonstration
print("\n=== Running balanced optimization with BrowseComp benchmark ===")
@@ -75,30 +74,36 @@ def main():
output_dir=output_dir,
n_trials=3, # Small number for demo purposes
search_tool="searxng",
- benchmark_type="browsecomp", # Specify BrowseComp benchmark
+ benchmark_weights={"browsecomp": 1.0}, # Specify BrowseComp benchmark only
)
-
+
print(f"Best balanced parameters: {balanced_params}")
print(f"Best balanced score: {balanced_score:.4f}")
-
+
# Save optimization results
summary = {
"timestamp": timestamp,
- "benchmark_type": "browsecomp",
- "balanced": {
- "parameters": balanced_params,
- "score": float(balanced_score)
- }
+ "benchmark_weights": {"browsecomp": 1.0},
+ "balanced": {"parameters": balanced_params, "score": float(balanced_score)},
}
-
- with open(os.path.join(output_dir, "browsecomp_optimization_summary.json"), "w") as f:
+
+ with open(
+ os.path.join(output_dir, "browsecomp_optimization_summary.json"), "w"
+ ) as f:
json.dump(summary, f, indent=2)
-
- print(f"\nDemo complete! Results saved to {output_dir}/browsecomp_optimization_summary.json")
+
+ print(
+ f"\nDemo complete! Results saved to {output_dir}/browsecomp_optimization_summary.json"
+ )
print(f"Recommended parameters for BrowseComp: {balanced_params}")
-
- print("\nNote: For actual optimizations, we recommend increasing n_trials to at least 20.")
- print("This demo runs with minimal trials to demonstrate the functionality quickly.")
+
+ print(
+ "\nNote: For actual optimizations, we recommend increasing n_trials to at least 20."
+ )
+ print(
+ "This demo runs with minimal trials to demonstrate the functionality quickly."
+ )
+
if __name__ == "__main__":
- main()
\ No newline at end of file
+ main()
diff --git a/examples/optimization/example_multi_benchmark.py b/examples/optimization/example_multi_benchmark.py
new file mode 100644
index 0000000000..7692a1ff85
--- /dev/null
+++ b/examples/optimization/example_multi_benchmark.py
@@ -0,0 +1,188 @@
+"""
+Example of multi-benchmark optimization using weighted benchmarks.
+
+This script demonstrates how to use the optimization system with both
+SimpleQA and BrowseComp benchmarks with custom weights.
+"""
+
+import logging
+import os
+import sys
+from datetime import datetime
+from typing import Any, Dict
+
+# Print current directory and python path for debugging
+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__), "../..")))
+
+try:
+ # Try to import from the local module structure
+ from src.local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ optimize_for_quality,
+ optimize_for_speed,
+ optimize_parameters,
+ )
+
+ print("Successfully imported using src.local_deep_research path")
+except ImportError:
+ print("First import attempt failed, trying with direct import...")
+ try:
+ # Try to import directly
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ optimize_for_quality,
+ optimize_for_speed,
+ optimize_parameters,
+ )
+
+ print("Successfully imported using local_deep_research path")
+ except ImportError as e:
+ print(f"Import error: {e}")
+ print("Creating simulation functions for demonstration only...")
+
+ # Create simulation functions if imports fail
+ def optimize_parameters(*args, **kwargs):
+ benchmark_weights = kwargs.get("benchmark_weights", {"simpleqa": 1.0})
+ print(
+ f"SIMULATION: optimize_parameters called with benchmark_weights={benchmark_weights}"
+ )
+
+ # Return different results based on the benchmark weights
+ if (
+ "browsecomp" in benchmark_weights
+ and benchmark_weights["browsecomp"] >= 1.0
+ ):
+ # BrowseComp only
+ return {
+ "iterations": 4,
+ "questions_per_iteration": 5,
+ "search_strategy": "parallel",
+ }, 0.78
+ elif (
+ "browsecomp" in benchmark_weights
+ and benchmark_weights["browsecomp"] > 0
+ ):
+ # Mixed weights
+ return {
+ "iterations": 2,
+ "questions_per_iteration": 2,
+ "search_strategy": "iterdrag",
+ }, 0.81
+ else:
+ # SimpleQA only (default)
+ return {
+ "iterations": 3,
+ "questions_per_iteration": 2,
+ "search_strategy": "standard",
+ }, 0.75
+
+ def optimize_for_quality(*args, **kwargs):
+ benchmark_weights = kwargs.get("benchmark_weights", {"simpleqa": 1.0})
+ print(
+ f"SIMULATION: optimize_for_quality called with benchmark_weights={benchmark_weights}"
+ )
+ return {
+ "iterations": 4,
+ "questions_per_iteration": 1,
+ "search_strategy": "iterdrag",
+ }, 0.85
+
+ def optimize_for_speed(*args, **kwargs):
+ benchmark_weights = kwargs.get("benchmark_weights", {"simpleqa": 1.0})
+ print(
+ f"SIMULATION: optimize_for_speed called with benchmark_weights={benchmark_weights}"
+ )
+ return {
+ "iterations": 2,
+ "questions_per_iteration": 2,
+ "search_strategy": "rapid",
+ }, 0.67
+
+
+# Set up logging
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)
+
+
+def print_optimization_results(params: Dict[str, Any], score: float):
+ """Print optimization results in a nicely formatted way."""
+ print("\n" + "=" * 50)
+ print(" OPTIMIZATION RESULTS ")
+ print("=" * 50)
+ print(f"SCORE: {score:.4f}")
+ print("\nBest Parameters:")
+ for param, value in params.items():
+ print(f" {param}: {value}")
+ print("=" * 50 + "\n")
+
+
+def main():
+ """Run the multi-benchmark optimization examples."""
+ # Create a timestamp-based directory for results
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ output_dir = f"optimization_demo_{timestamp}"
+ os.makedirs(output_dir, exist_ok=True)
+
+ # Research query for optimization examples
+ query = "Recent advancements in renewable energy"
+
+ # Example 1: SimpleQA only (default)
+ print("\n🔍 Running optimization with SimpleQA benchmark only...")
+ params1, score1 = optimize_parameters(
+ query=query,
+ n_trials=3, # Using a small number for quick demonstration
+ output_dir=os.path.join(output_dir, "simpleqa_only"),
+ )
+ print_optimization_results(params1, score1)
+
+ # Example 2: BrowseComp only
+ print("\n🔍 Running optimization with BrowseComp benchmark only...")
+ params2, score2 = optimize_parameters(
+ query=query,
+ n_trials=3, # Using a small number for quick demonstration
+ output_dir=os.path.join(output_dir, "browsecomp_only"),
+ benchmark_weights={"browsecomp": 1.0},
+ )
+ print_optimization_results(params2, score2)
+
+ # Example 3: 60/40 weighted combination (SimpleQA/BrowseComp)
+ print("\n🔍 Running optimization with 60% SimpleQA and 40% BrowseComp...")
+ params3, score3 = optimize_parameters(
+ query=query,
+ n_trials=5, # Using a small number for quick demonstration
+ output_dir=os.path.join(output_dir, "weighted_combination"),
+ benchmark_weights={
+ "simpleqa": 0.6, # 60% weight for SimpleQA
+ "browsecomp": 0.4, # 40% weight for BrowseComp
+ },
+ )
+ print_optimization_results(params3, score3)
+
+ # Example 4: Quality-focused with both benchmarks
+ print("\n🔍 Running quality-focused optimization with both benchmarks...")
+ params4, score4 = optimize_for_quality(
+ query=query,
+ n_trials=3,
+ output_dir=os.path.join(output_dir, "quality_focused"),
+ benchmark_weights={"simpleqa": 0.6, "browsecomp": 0.4},
+ )
+ print_optimization_results(params4, score4)
+
+ # Example 5: Speed-focused with both benchmarks
+ print("\n🔍 Running speed-focused optimization with both benchmarks...")
+ params5, score5 = optimize_for_speed(
+ query=query,
+ n_trials=3,
+ output_dir=os.path.join(output_dir, "speed_focused"),
+ benchmark_weights={"simpleqa": 0.5, "browsecomp": 0.5},
+ )
+ print_optimization_results(params5, score5)
+
+ print(f"\nAll optimization results saved to: {output_dir}")
+ print("View the results directory for detailed logs and visualizations.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/optimization/multi_benchmark_simulation.py b/examples/optimization/multi_benchmark_simulation.py
new file mode 100644
index 0000000000..5365de8e00
--- /dev/null
+++ b/examples/optimization/multi_benchmark_simulation.py
@@ -0,0 +1,408 @@
+"""
+Multi-benchmark optimization simulation.
+
+This script demonstrates how to use multi-benchmark optimization with weighted scores
+without actually running real benchmarks (just simulation).
+"""
+
+import json
+import logging
+import os
+import random
+import time
+from datetime import datetime
+from typing import Any, Dict, Optional, Tuple
+
+# Configure logging
+logging.basicConfig(
+ level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+)
+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):
+ """
+ Initialize benchmark simulator.
+
+ Args:
+ name: Name of the benchmark
+ quality_bias: Base quality score (will be adjusted by parameters)
+ speed_factor: How much iterations affect speed (higher = more sensitive)
+ """
+ self.name = name
+ self.quality_bias = quality_bias
+ self.speed_factor = speed_factor
+
+ def evaluate(self, params: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Simulate running a benchmark.
+
+ Args:
+ params: System parameters to evaluate
+
+ Returns:
+ Dictionary with simulated metrics
+ """
+ # Add some randomness to make it interesting
+ iterations = params.get("iterations", 2)
+ questions = params.get("questions_per_iteration", 2)
+ strategy = params.get("search_strategy", "standard")
+
+ # Simulate thinking for realism
+ time.sleep(0.5)
+
+ # Calculate quality score based on parameters
+ # Different benchmark types respond differently to parameters
+ if self.name == "simpleqa":
+ # SimpleQA likes more iterations
+ quality_score = (
+ 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)
+ else:
+ # BrowseComp likes more questions per iteration
+ quality_score = (
+ self.quality_bias + (questions * 0.05) - random.uniform(0, 0.2)
+ )
+ # BrowseComp is slower
+ speed_score = 1.0 - (iterations * questions * self.speed_factor)
+
+ # Strategy effects
+ if strategy == "rapid":
+ speed_score += 0.1
+ quality_score -= 0.05
+ elif strategy == "iterdrag":
+ quality_score += 0.1
+ speed_score -= 0.05
+
+ # Clamp values
+ quality_score = max(0.0, min(1.0, quality_score))
+ speed_score = max(0.0, min(1.0, speed_score))
+
+ return {
+ "benchmark_type": self.name,
+ "quality_score": quality_score,
+ "speed_score": speed_score,
+ "total_duration": iterations * questions * random.uniform(10, 20),
+ }
+
+
+class CompositeBenchmarkSimulator:
+ """Simulates running multiple benchmarks with weights."""
+
+ def __init__(self, benchmark_weights: Optional[Dict[str, float]] = None):
+ """
+ Initialize with benchmark weights.
+
+ Args:
+ benchmark_weights: Dictionary mapping benchmark names to weights
+ Default: {"simpleqa": 1.0}
+ """
+ self.benchmark_weights = benchmark_weights or {"simpleqa": 1.0}
+
+ # Create benchmark simulators
+ self.simulators = {
+ "simpleqa": BenchmarkSimulator(
+ "simpleqa", quality_bias=0.75, speed_factor=0.15
+ ),
+ "browsecomp": BenchmarkSimulator(
+ "browsecomp", quality_bias=0.7, speed_factor=0.25
+ ),
+ }
+
+ # Normalize weights
+ total_weight = sum(self.benchmark_weights.values())
+ self.normalized_weights = {
+ k: w / total_weight for k, w in self.benchmark_weights.items()
+ }
+
+ def evaluate(self, params: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Simulate running multiple benchmarks with weights.
+
+ Args:
+ params: System parameters to evaluate
+
+ Returns:
+ Dictionary with weighted results
+ """
+ all_results = {}
+ combined_quality_score = 0.0
+ combined_speed_score = 0.0
+ total_duration = 0.0
+
+ # Run each benchmark with weight > 0
+ for benchmark_name, weight in self.normalized_weights.items():
+ if weight > 0 and benchmark_name in self.simulators:
+ simulator = self.simulators[benchmark_name]
+
+ # Run benchmark simulation
+ result = simulator.evaluate(params)
+
+ # Store individual results
+ all_results[benchmark_name] = result
+
+ # Calculate weighted contribution
+ quality_score = result["quality_score"]
+ speed_score = result["speed_score"]
+
+ weighted_quality = quality_score * weight
+ weighted_speed = speed_score * weight
+
+ logger.info(
+ f"Benchmark {benchmark_name}: quality={quality_score:.4f}, "
+ f"speed={speed_score:.4f}, weight={weight:.2f}"
+ )
+
+ # Add to combined scores
+ combined_quality_score += weighted_quality
+ combined_speed_score += weighted_speed
+ total_duration += result["total_duration"]
+
+ # Return combined results
+ return {
+ "quality_score": combined_quality_score,
+ "speed_score": combined_speed_score,
+ "total_duration": total_duration,
+ "benchmark_results": all_results,
+ "benchmark_weights": self.normalized_weights,
+ }
+
+
+class OptunaOptimizerSimulator:
+ """Simulates Optuna optimizer for demonstration purposes."""
+
+ def __init__(
+ self,
+ benchmark_weights: Optional[Dict[str, float]] = None,
+ metric_weights: Optional[Dict[str, float]] = None,
+ ):
+ """
+ Initialize optimizer simulator.
+
+ Args:
+ benchmark_weights: Weights for different benchmarks
+ metric_weights: Weights for quality vs speed metrics
+ """
+ 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)
+
+ def optimize(
+ self, param_space: Dict[str, Any], n_trials: int = 10
+ ) -> Tuple[Dict[str, Any], float]:
+ """
+ Simulate optimization process.
+
+ Args:
+ param_space: Parameter space to explore
+ n_trials: Number of trials
+
+ Returns:
+ Tuple of best parameters and best score
+ """
+ logger.info(f"Starting optimization with {n_trials} trials")
+ logger.info(f"Parameter space: {param_space}")
+ logger.info(f"Benchmark weights: {self.benchmark_weights}")
+ logger.info(f"Metric weights: {self.metric_weights}")
+
+ best_score = 0.0
+ best_params = {}
+ all_trials = []
+
+ # Run simulated trials
+ for i in range(n_trials):
+ # Generate parameters for this trial
+ params = {}
+ for param_name, param_config in param_space.items():
+ param_type = param_config["type"]
+
+ if param_type == "int":
+ params[param_name] = random.randint(
+ param_config["low"], param_config["high"]
+ )
+ elif param_type == "categorical":
+ params[param_name] = random.choice(param_config["choices"])
+
+ logger.info(f"Trial {i + 1}/{n_trials}: Testing parameters: {params}")
+
+ # Simulate benchmark evaluation
+ result = self.benchmark_simulator.evaluate(params)
+
+ # Calculate combined score based on weights
+ quality_score = result["quality_score"]
+ speed_score = result["speed_score"]
+
+ combined_score = (
+ self.metric_weights.get("quality", 0.6) * quality_score
+ + self.metric_weights.get("speed", 0.4) * speed_score
+ )
+
+ logger.info(
+ f"Trial {i + 1}: Quality: {quality_score:.4f}, Speed: {speed_score:.4f}, "
+ f"Combined: {combined_score:.4f}"
+ )
+
+ # Save trial information
+ trial_info = {
+ "trial_number": i + 1,
+ "params": params,
+ "quality_score": quality_score,
+ "speed_score": speed_score,
+ "combined_score": combined_score,
+ "benchmark_results": result["benchmark_results"],
+ }
+ all_trials.append(trial_info)
+
+ # 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:.4f}"
+ )
+
+ # Return the best parameters
+ return best_params, best_score, all_trials
+
+
+def optimize_parameters(
+ param_space: Optional[Dict[str, Any]] = None,
+ n_trials: int = 10,
+ metric_weights: Optional[Dict[str, float]] = None,
+ benchmark_weights: Optional[Dict[str, float]] = None,
+) -> Tuple[Dict[str, Any], float]:
+ """
+ Simulate parameter optimization.
+
+ Args:
+ param_space: Parameter space to explore
+ n_trials: Number of trials to run
+ metric_weights: Weights for quality vs speed
+ benchmark_weights: Weights for different benchmarks
+
+ Returns:
+ Tuple of best parameters and best score
+ """
+ # Default parameter space
+ if param_space is None:
+ param_space = {
+ "iterations": {
+ "type": "int",
+ "low": 1,
+ "high": 5,
+ },
+ "questions_per_iteration": {
+ "type": "int",
+ "low": 1,
+ "high": 5,
+ },
+ "search_strategy": {
+ "type": "categorical",
+ "choices": ["iterdrag", "standard", "rapid", "parallel"],
+ },
+ }
+
+ # Create optimizer
+ optimizer = OptunaOptimizerSimulator(
+ benchmark_weights=benchmark_weights, metric_weights=metric_weights
+ )
+
+ # Run optimization
+ return optimizer.optimize(param_space, n_trials)
+
+
+def print_optimization_results(params: Dict[str, Any], score: float):
+ """Print optimization results in a nicely formatted way."""
+ print("\n" + "=" * 50)
+ print(" OPTIMIZATION RESULTS ")
+ print("=" * 50)
+ print(f"SCORE: {score:.4f}")
+ print("\nBest Parameters:")
+ for param, value in params.items():
+ print(f" {param}: {value}")
+ print("=" * 50 + "\n")
+
+
+def main():
+ """Run the multi-benchmark optimization simulation."""
+ # Create a timestamp-based directory for results
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ output_dir = "optimization_sim_" + timestamp
+ os.makedirs(output_dir, exist_ok=True)
+
+ print("\n🔬 Multi-Benchmark Optimization Simulation 🔬")
+ print(f"Results will be saved to: {output_dir}")
+
+ # Example 1: SimpleQA only (default)
+ print("\n🔍 Running optimization with SimpleQA benchmark only...")
+ params1, score1, trials1 = optimize_parameters(
+ n_trials=5, benchmark_weights={"simpleqa": 1.0}
+ )
+ print_optimization_results(params1, score1)
+
+ # Example 2: BrowseComp only
+ print("\n🔍 Running optimization with BrowseComp benchmark only...")
+ params2, score2, trials2 = optimize_parameters(
+ n_trials=5, benchmark_weights={"browsecomp": 1.0}
+ )
+ print_optimization_results(params2, score2)
+
+ # Example 3: 60/40 weighted combination (SimpleQA/BrowseComp)
+ print("\n🔍 Running optimization with 60% SimpleQA and 40% BrowseComp...")
+ params3, score3, trials3 = optimize_parameters(
+ n_trials=10,
+ benchmark_weights={
+ "simpleqa": 0.6, # 60% weight for SimpleQA
+ "browsecomp": 0.4, # 40% weight for BrowseComp
+ },
+ )
+ print_optimization_results(params3, score3)
+
+ # Save results
+ results = {
+ "timestamp": timestamp,
+ "simpleqa_only": {
+ "best_params": params1,
+ "best_score": score1,
+ "trials": trials1,
+ },
+ "browsecomp_only": {
+ "best_params": params2,
+ "best_score": score2,
+ "trials": trials2,
+ },
+ "weighted_combination": {
+ "best_params": params3,
+ "best_score": score3,
+ "trials": trials3,
+ "weights": {"simpleqa": 0.6, "browsecomp": 0.4},
+ },
+ }
+
+ results_file = os.path.join(output_dir, "multi_benchmark_results.json")
+ with open(results_file, "w") as f:
+ # Convert all values to serializable types
+ json.dump(
+ results,
+ f,
+ indent=2,
+ default=lambda o: float(o) if isinstance(o, (float, int)) else o,
+ )
+
+ print(f"\n✅ Simulation complete! Results saved to {results_file}")
+ print("\nComparison of best parameters:")
+ print(f"- SimpleQA only: {params1}")
+ print(f"- BrowseComp only: {params2}")
+ 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.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/optimization/run_multi_benchmark.py b/examples/optimization/run_multi_benchmark.py
new file mode 100755
index 0000000000..4ae3f64c22
--- /dev/null
+++ b/examples/optimization/run_multi_benchmark.py
@@ -0,0 +1,248 @@
+#!/usr/bin/env python
+"""
+Multi-benchmark optimization example for Local Deep Research.
+
+This script demonstrates how to run optimization with multiple benchmark types
+and custom weights between them.
+
+Usage:
+ # Run from project root with venv activated
+ cd /path/to/local-deep-research
+ source .venv/bin/activate
+ cd src
+ python ../examples/optimization/run_multi_benchmark.py
+"""
+
+import logging
+import os
+import sys
+from datetime import datetime
+from typing import Any, Dict
+
+# Add src directory to Python path
+src_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../src"))
+if src_dir not in sys.path:
+ sys.path.insert(0, src_dir)
+
+# Set the data directory with the database
+data_dir = os.path.join(src_dir, "data")
+if os.path.exists(os.path.join(data_dir, "ldr.db")):
+ print(f"Found database at {os.path.join(data_dir, 'ldr.db')}")
+ # Set environment variable to use this database
+ os.environ["LDR_DATA_DIR"] = data_dir
+else:
+ print(f"Warning: Database not found at {os.path.join(data_dir, 'ldr.db')}")
+
+# Import benchmark optimization functions
+try:
+ from local_deep_research.benchmarks.optimization.api import optimize_parameters
+
+ print("Successfully imported optimization API")
+except ImportError as e:
+ print(f"Error importing optimization API: {e}")
+ print("Current sys.path:", sys.path)
+ sys.exit(1)
+
+# Configure logging
+logging.basicConfig(
+ level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+)
+logger = logging.getLogger(__name__)
+
+
+def print_optimization_results(params: Dict[str, Any], score: float):
+ """Print optimization results in a nicely formatted way."""
+ print("\n" + "=" * 50)
+ print(" OPTIMIZATION RESULTS ")
+ print("=" * 50)
+ print(f"SCORE: {score:.4f}")
+ print("\nBest Parameters:")
+ for param, value in params.items():
+ print(f" {param}: {value}")
+ print("=" * 50 + "\n")
+
+
+def main():
+ """Run multi-benchmark optimization examples."""
+ # Create a timestamp-based directory for results
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+
+ # Put results in the data directory for easier access
+ if os.path.isdir(data_dir):
+ output_dir = os.path.join(
+ data_dir, "optimization_results", "multi_benchmark_" + timestamp
+ )
+ else:
+ output_dir = os.path.join(
+ "optimization_results", "multi_benchmark_" + timestamp
+ )
+
+ os.makedirs(output_dir, exist_ok=True)
+ print(f"Results will be saved to: {output_dir}")
+
+ print("\n🔬 Multi-Benchmark Optimization Example 🔬")
+ print("Results will be saved to: " + output_dir)
+
+ # Define a very small parameter space for testing
+ tiny_param_space = {
+ "iterations": {
+ "type": "int",
+ "low": 1,
+ "high": 3,
+ "step": 1,
+ },
+ "questions_per_iteration": {
+ "type": "int",
+ "low": 1,
+ "high": 3,
+ "step": 1,
+ },
+ "search_strategy": {
+ "type": "categorical",
+ "choices": ["iterdrag", "rapid", "parallel"],
+ },
+ }
+
+ # Example query for running optimization
+ query = "Recent developments in fusion energy research"
+
+ # Very small parameter space for quick testing
+ tiny_param_space = {
+ "iterations": {
+ "type": "int",
+ "low": 1,
+ "high": 2,
+ "step": 1,
+ },
+ "questions_per_iteration": {
+ "type": "int",
+ "low": 1,
+ "high": 2,
+ "step": 1,
+ },
+ "search_strategy": {
+ "type": "categorical",
+ "choices": ["rapid"],
+ },
+ }
+
+ # Run 1: SimpleQA benchmark only with minimal trials
+ print("\n🔍 Running SimpleQA-only optimization (minimal test)...")
+ try:
+ # Use very minimal settings for testing
+ mini_system_config = {
+ "iterations": 1,
+ "questions_per_iteration": 1,
+ "search_strategy": "rapid",
+ "max_results": 2, # Very few results
+ "search_tool": "wikipedia", # Fast search engine
+ }
+
+ # Import the evaluator directly for faster testing
+ from local_deep_research.benchmarks.evaluators import (
+ CompositeBenchmarkEvaluator,
+ )
+
+ print("Creating benchmark evaluator with SimpleQA only")
+ evaluator = CompositeBenchmarkEvaluator({"simpleqa": 1.0})
+
+ print("Running single benchmark evaluation (no optimization)...")
+ quality_results = evaluator.evaluate(
+ system_config=mini_system_config,
+ num_examples=2, # Use just 2 examples
+ output_dir=os.path.join(output_dir, "simpleqa_test"),
+ )
+
+ 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(
+ "Individual benchmark results:",
+ list(quality_results.get("benchmark_results", {}).keys()),
+ )
+
+ # Also run the Optuna optimizer with minimal settings
+ print("\nRunning minimal Optuna optimization...")
+ params1, score1 = optimize_parameters(
+ query=query,
+ param_space=tiny_param_space, # Use tiny param space
+ output_dir=os.path.join(output_dir, "simpleqa_only"),
+ n_trials=1, # Just one trial for testing
+ benchmark_weights={"simpleqa": 1.0}, # SimpleQA only
+ timeout=30, # Limit to 30 seconds
+ )
+ print_optimization_results(params1, score1)
+ except Exception as e:
+ logger.error(f"Error running SimpleQA optimization: {e}")
+ print(f"Error: {e}")
+
+ # Run 2: BrowseComp benchmark only (minimal test)
+ print("\n🔍 Running BrowseComp-only benchmark (minimal test)...")
+ try:
+ print("Creating benchmark evaluator with BrowseComp only")
+ browsecomp_evaluator = CompositeBenchmarkEvaluator({"browsecomp": 1.0})
+
+ print("Running single BrowseComp evaluation (no optimization)...")
+ bc_results = browsecomp_evaluator.evaluate(
+ system_config=mini_system_config,
+ num_examples=1, # Just 1 example for speed
+ output_dir=os.path.join(output_dir, "browsecomp_test"),
+ )
+
+ 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(
+ "Individual benchmark results:",
+ list(bc_results.get("benchmark_results", {}).keys()),
+ )
+
+ except Exception as e:
+ logger.error(f"Error running BrowseComp evaluation: {e}")
+ print(f"Error: {e}")
+
+ # Run 3: Combined benchmark with weights (minimal test)
+ print(
+ "\n🔍 Running combined benchmarks with weights (60% SimpleQA, 40% BrowseComp)..."
+ )
+ try:
+ print("Creating composite benchmark evaluator with weights")
+ composite_evaluator = CompositeBenchmarkEvaluator(
+ {"simpleqa": 0.6, "browsecomp": 0.4}
+ )
+
+ print("Running combined benchmark evaluation (no optimization)...")
+ combo_results = composite_evaluator.evaluate(
+ system_config=mini_system_config,
+ num_examples=1, # Just 1 example for speed
+ output_dir=os.path.join(output_dir, "combined_test"),
+ )
+
+ 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(
+ "Individual benchmark results:",
+ list(combo_results.get("benchmark_results", {}).keys()),
+ )
+
+ except Exception as e:
+ logger.error(f"Error running combined benchmark evaluation: {e}")
+ print(f"Error: {e}")
+
+ print("\nSkipping full optimization runs for time constraints.")
+ print("The system fully supports:")
+ print(
+ " 1. BrowseComp-only optimization with benchmark_weights={'browsecomp': 1.0}"
+ )
+ print(
+ " 2. Combined benchmarks with weights benchmark_weights={'simpleqa': 0.6, 'browsecomp': 0.4}"
+ )
+ print("\nThese would use the same API as demonstrated above.")
+
+ print(f"\nAll optimization runs completed. Results saved to {output_dir}")
+ print("Note: For serious optimization runs, increase n_trials to 20+")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/pyproject.toml b/pyproject.toml
index 3e81be2da6..0f2d589b91 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -24,7 +24,7 @@ dependencies = [
"langchain-core>=0.3.34",
"langchain-ollama>=0.2.3",
"langchain-openai>=0.3.5",
- "langchain_anthropic>=0.3.7",
+ "langchain-anthropic>=0.3.13",
"duckduckgo_search>=7.3.2",
"python-dateutil>=2.9.0",
"typing_extensions>=4.12.2",
diff --git a/src/local_deep_research/benchmarks/evaluators/__init__.py b/src/local_deep_research/benchmarks/evaluators/__init__.py
new file mode 100644
index 0000000000..cf5c5850e3
--- /dev/null
+++ b/src/local_deep_research/benchmarks/evaluators/__init__.py
@@ -0,0 +1,18 @@
+"""
+Benchmark evaluation package.
+
+This package provides evaluators for different benchmark types and
+a composite evaluator for weighted multi-benchmark evaluation.
+"""
+
+from .base import BaseBenchmarkEvaluator
+from .browsecomp import BrowseCompEvaluator
+from .composite import CompositeBenchmarkEvaluator
+from .simpleqa import SimpleQAEvaluator
+
+__all__ = [
+ "BaseBenchmarkEvaluator",
+ "SimpleQAEvaluator",
+ "BrowseCompEvaluator",
+ "CompositeBenchmarkEvaluator",
+]
diff --git a/src/local_deep_research/benchmarks/evaluators/base.py b/src/local_deep_research/benchmarks/evaluators/base.py
new file mode 100644
index 0000000000..4b51b7ec0f
--- /dev/null
+++ b/src/local_deep_research/benchmarks/evaluators/base.py
@@ -0,0 +1,74 @@
+"""
+Base class for benchmark evaluators.
+
+This module defines the abstract base class that all benchmark evaluators
+must implement, establishing a common interface for different benchmark types.
+"""
+
+import logging
+import os
+from abc import ABC, abstractmethod
+from typing import Any, Dict
+
+logger = logging.getLogger(__name__)
+
+
+class BaseBenchmarkEvaluator(ABC):
+ """
+ Abstract base class for benchmark evaluators.
+
+ All benchmark evaluator implementations must inherit from this class and
+ implement the evaluate method to run their specific benchmark type.
+ """
+
+ def __init__(self, name: str):
+ """
+ Initialize benchmark evaluator with a name.
+
+ Args:
+ name: Unique identifier for this benchmark type
+ """
+ self.name = name
+
+ def get_name(self) -> str:
+ """
+ Get the benchmark name.
+
+ Returns:
+ The benchmark identifier
+ """
+ return self.name
+
+ @abstractmethod
+ def evaluate(
+ self,
+ system_config: Dict[str, Any],
+ num_examples: int,
+ output_dir: str,
+ ) -> Dict[str, Any]:
+ """
+ Run benchmark evaluation with given system configuration.
+
+ Args:
+ system_config: Configuration parameters for the system under test
+ num_examples: Number of benchmark examples to evaluate
+ output_dir: Directory to save evaluation results
+
+ Returns:
+ Dictionary with evaluation metrics including quality_score (0-1)
+ """
+ pass
+
+ def _create_subdirectory(self, output_dir: str) -> str:
+ """
+ Create a benchmark-specific subdirectory for output.
+
+ Args:
+ output_dir: Parent directory for output
+
+ Returns:
+ Path to the benchmark-specific directory
+ """
+ benchmark_dir = os.path.join(output_dir, self.name)
+ os.makedirs(benchmark_dir, exist_ok=True)
+ return benchmark_dir
diff --git a/src/local_deep_research/benchmarks/evaluators/browsecomp.py b/src/local_deep_research/benchmarks/evaluators/browsecomp.py
new file mode 100644
index 0000000000..d10fbb030b
--- /dev/null
+++ b/src/local_deep_research/benchmarks/evaluators/browsecomp.py
@@ -0,0 +1,83 @@
+"""
+BrowseComp benchmark evaluator.
+
+This module provides a benchmark evaluator implementation for the BrowseComp
+benchmark, which tests browsing comprehension capabilities.
+"""
+
+import logging
+from typing import Any, Dict
+
+from ..runners import run_browsecomp_benchmark
+from .base import BaseBenchmarkEvaluator
+
+logger = logging.getLogger(__name__)
+
+
+class BrowseCompEvaluator(BaseBenchmarkEvaluator):
+ """
+ Evaluator for the BrowseComp benchmark.
+
+ This evaluator runs the BrowseComp benchmark, which tests a system's ability
+ to accurately comprehend and answer questions from web browsing.
+ """
+
+ def __init__(self):
+ """Initialize the BrowseComp evaluator."""
+ super().__init__("browsecomp")
+
+ def evaluate(
+ self,
+ system_config: Dict[str, Any],
+ num_examples: int,
+ output_dir: str,
+ ) -> Dict[str, Any]:
+ """
+ Run BrowseComp benchmark and return metrics.
+
+ Args:
+ system_config: Search and LLM configuration parameters
+ num_examples: Number of benchmark examples to run
+ output_dir: Directory to save evaluation results
+
+ Returns:
+ Dictionary with metrics including quality_score based on accuracy
+ """
+ # Create benchmark-specific directory
+ benchmark_dir = self._create_subdirectory(output_dir)
+
+ # Log benchmark execution
+ logger.info(f"Running BrowseComp benchmark with {num_examples} examples")
+
+ try:
+ # Run BrowseComp benchmark
+ results = run_browsecomp_benchmark(
+ num_examples=num_examples,
+ output_dir=benchmark_dir,
+ search_config=system_config,
+ run_evaluation=True,
+ )
+
+ # Extract metrics
+ metrics = results.get("metrics", {})
+ accuracy = metrics.get("accuracy", 0.0)
+
+ # Return evaluation results with quality score
+ return {
+ "benchmark_type": self.name,
+ "accuracy": accuracy,
+ "quality_score": accuracy, # Map accuracy directly to quality score
+ "raw_results": results,
+ "report_path": results.get("report_path"),
+ }
+
+ except Exception as e:
+ logger.error(f"Error in BrowseComp evaluation: {str(e)}")
+
+ # Return error information
+ return {
+ "benchmark_type": self.name,
+ "error": str(e),
+ "quality_score": 0.0,
+ "accuracy": 0.0,
+ }
diff --git a/src/local_deep_research/benchmarks/evaluators/composite.py b/src/local_deep_research/benchmarks/evaluators/composite.py
new file mode 100644
index 0000000000..aa8319a42f
--- /dev/null
+++ b/src/local_deep_research/benchmarks/evaluators/composite.py
@@ -0,0 +1,121 @@
+"""
+Composite benchmark evaluator.
+
+This module provides a composite evaluator that can run multiple benchmarks
+with weighted scores to provide a comprehensive evaluation.
+"""
+
+import logging
+from typing import Any, Dict, Optional
+
+# Import specific evaluator implementations
+from .browsecomp import BrowseCompEvaluator
+from .simpleqa import SimpleQAEvaluator
+
+logger = logging.getLogger(__name__)
+
+
+class CompositeBenchmarkEvaluator:
+ """
+ Evaluator that combines multiple benchmarks with weighted scores.
+
+ This evaluator runs multiple benchmark types and combines their scores
+ according to specified weights, enabling comprehensive evaluation across
+ different metrics and tasks.
+ """
+
+ def __init__(self, benchmark_weights: Optional[Dict[str, float]] = None):
+ """
+ Initialize with benchmark weights.
+
+ Args:
+ benchmark_weights: Dictionary mapping benchmark names to weights
+ Default: {"simpleqa": 1.0}
+ """
+ # Default to SimpleQA only if no weights provided
+ self.benchmark_weights = benchmark_weights or {"simpleqa": 1.0}
+
+ # Create evaluators for available benchmarks
+ self.evaluators = {
+ "simpleqa": SimpleQAEvaluator(),
+ "browsecomp": BrowseCompEvaluator(),
+ }
+
+ # Normalize weights to sum to 1.0
+ total_weight = sum(self.benchmark_weights.values())
+ if total_weight <= 0:
+ logger.warning(
+ "Total benchmark weight is zero or negative. Using default weights."
+ )
+ self.normalized_weights = {"simpleqa": 1.0}
+ else:
+ self.normalized_weights = {
+ k: w / total_weight for k, w in self.benchmark_weights.items()
+ }
+
+ # Log the weights being used
+ logger.info(f"Using normalized benchmark weights: {self.normalized_weights}")
+
+ def evaluate(
+ self,
+ system_config: Dict[str, Any],
+ num_examples: int,
+ output_dir: str,
+ ) -> Dict[str, Any]:
+ """
+ Run all requested benchmarks and compute weighted score.
+
+ Args:
+ system_config: Configuration parameters for the system under test
+ num_examples: Number of benchmark examples to evaluate
+ output_dir: Directory to save evaluation results
+
+ Returns:
+ Dictionary with combined metrics and individual benchmark results
+ """
+ all_results = {}
+ combined_score = 0.0
+
+ # Run each benchmark with weight > 0
+ for benchmark_name, weight in self.normalized_weights.items():
+ if weight > 0 and benchmark_name in self.evaluators:
+ evaluator = self.evaluators[benchmark_name]
+
+ try:
+ # Run benchmark evaluation
+ result = evaluator.evaluate(
+ system_config=system_config,
+ num_examples=num_examples,
+ output_dir=output_dir,
+ )
+
+ # Store individual results
+ all_results[benchmark_name] = result
+
+ # Calculate weighted contribution to combined score
+ quality_score = result.get("quality_score", 0.0)
+ weighted_contribution = quality_score * weight
+
+ logger.info(
+ f"Benchmark {benchmark_name}: score={quality_score:.4f}, "
+ f"weight={weight:.2f}, contribution={weighted_contribution:.4f}"
+ )
+
+ # Add to combined score
+ combined_score += weighted_contribution
+
+ except Exception as e:
+ logger.error(f"Error running {benchmark_name} benchmark: {str(e)}")
+ all_results[benchmark_name] = {
+ "benchmark_type": benchmark_name,
+ "error": str(e),
+ "quality_score": 0.0,
+ }
+
+ # Return combined results
+ return {
+ "quality_score": combined_score,
+ "benchmark_results": all_results,
+ "benchmark_weights": self.normalized_weights,
+ "combined_score": combined_score,
+ }
diff --git a/src/local_deep_research/benchmarks/evaluators/simpleqa.py b/src/local_deep_research/benchmarks/evaluators/simpleqa.py
new file mode 100644
index 0000000000..e55f468644
--- /dev/null
+++ b/src/local_deep_research/benchmarks/evaluators/simpleqa.py
@@ -0,0 +1,83 @@
+"""
+SimpleQA benchmark evaluator.
+
+This module provides a benchmark evaluator implementation for the SimpleQA
+benchmark, which tests simple question-answering capabilities.
+"""
+
+import logging
+from typing import Any, Dict
+
+from ..runners import run_simpleqa_benchmark
+from .base import BaseBenchmarkEvaluator
+
+logger = logging.getLogger(__name__)
+
+
+class SimpleQAEvaluator(BaseBenchmarkEvaluator):
+ """
+ Evaluator for the SimpleQA benchmark.
+
+ This evaluator runs the SimpleQA benchmark, which tests a system's ability
+ to accurately answer straightforward factual questions.
+ """
+
+ def __init__(self):
+ """Initialize the SimpleQA evaluator."""
+ super().__init__("simpleqa")
+
+ def evaluate(
+ self,
+ system_config: Dict[str, Any],
+ num_examples: int,
+ output_dir: str,
+ ) -> Dict[str, Any]:
+ """
+ Run SimpleQA benchmark and return metrics.
+
+ Args:
+ system_config: Search and LLM configuration parameters
+ num_examples: Number of benchmark examples to run
+ output_dir: Directory to save evaluation results
+
+ Returns:
+ Dictionary with metrics including quality_score based on accuracy
+ """
+ # Create benchmark-specific directory
+ benchmark_dir = self._create_subdirectory(output_dir)
+
+ # Log benchmark execution
+ logger.info(f"Running SimpleQA benchmark with {num_examples} examples")
+
+ try:
+ # Run SimpleQA benchmark
+ results = run_simpleqa_benchmark(
+ num_examples=num_examples,
+ output_dir=benchmark_dir,
+ search_config=system_config,
+ run_evaluation=True,
+ )
+
+ # Extract metrics
+ metrics = results.get("metrics", {})
+ accuracy = metrics.get("accuracy", 0.0)
+
+ # Return evaluation results with quality score
+ return {
+ "benchmark_type": self.name,
+ "accuracy": accuracy,
+ "quality_score": accuracy, # Map accuracy directly to quality score
+ "raw_results": results,
+ "report_path": results.get("report_path"),
+ }
+
+ except Exception as e:
+ logger.error(f"Error in SimpleQA evaluation: {str(e)}")
+
+ # Return error information
+ return {
+ "benchmark_type": self.name,
+ "error": str(e),
+ "quality_score": 0.0,
+ "accuracy": 0.0,
+ }
diff --git a/src/local_deep_research/benchmarks/optimization/api.py b/src/local_deep_research/benchmarks/optimization/api.py
index 49474c26af..5fcfdcee31 100644
--- a/src/local_deep_research/benchmarks/optimization/api.py
+++ b/src/local_deep_research/benchmarks/optimization/api.py
@@ -7,7 +7,7 @@ without having to directly work with the optimizer classes.
import logging
import os
-from typing import Any, Callable, Dict, List, Optional, Tuple, Union
+from typing import Any, Callable, Dict, List, Optional, Tuple
from local_deep_research.benchmarks.optimization.optuna_optimizer import OptunaOptimizer
@@ -29,7 +29,7 @@ def optimize_parameters(
optimization_metrics: Optional[List[str]] = None,
metric_weights: Optional[Dict[str, float]] = None,
progress_callback: Optional[Callable[[int, int, Dict], None]] = None,
- benchmark_type: str = "simpleqa",
+ benchmark_weights: Optional[Dict[str, float]] = None,
) -> Tuple[Dict[str, Any], float]:
"""
Optimize parameters for Local Deep Research.
@@ -49,7 +49,9 @@ def optimize_parameters(
optimization_metrics: List of metrics to optimize (default: ["quality", "speed"])
metric_weights: Dictionary of weights for each metric
progress_callback: Optional callback for progress updates
- benchmark_type: Type of benchmark to use ("simpleqa" or "browsecomp")
+ benchmark_weights: Dictionary mapping benchmark types to weights
+ (e.g., {"simpleqa": 0.6, "browsecomp": 0.4})
+ If None, only SimpleQA is used with weight 1.0
Returns:
Tuple of (best_parameters, best_score)
@@ -69,7 +71,7 @@ def optimize_parameters(
optimization_metrics=optimization_metrics,
metric_weights=metric_weights,
progress_callback=progress_callback,
- benchmark_type=benchmark_type,
+ benchmark_weights=benchmark_weights,
)
# Run optimization
@@ -84,7 +86,7 @@ def optimize_for_speed(
provider: Optional[str] = None,
search_tool: Optional[str] = None,
progress_callback: Optional[Callable[[int, int, Dict], None]] = None,
- benchmark_type: str = "simpleqa",
+ benchmark_weights: Optional[Dict[str, float]] = None,
) -> Tuple[Dict[str, Any], float]:
"""
Optimize parameters with a focus on speed performance.
@@ -97,7 +99,9 @@ def optimize_for_speed(
provider: LLM provider
search_tool: Search engine to use
progress_callback: Optional callback for progress updates
- benchmark_type: Type of benchmark to use ("simpleqa" or "browsecomp")
+ benchmark_weights: Dictionary mapping benchmark types to weights
+ (e.g., {"simpleqa": 0.6, "browsecomp": 0.4})
+ If None, only SimpleQA is used with weight 1.0
Returns:
Tuple of (best_parameters, best_score)
@@ -136,7 +140,7 @@ def optimize_for_speed(
metric_weights=metric_weights,
optimization_metrics=["speed", "quality"],
progress_callback=progress_callback,
- benchmark_type=benchmark_type,
+ benchmark_weights=benchmark_weights,
)
@@ -148,7 +152,7 @@ def optimize_for_quality(
provider: Optional[str] = None,
search_tool: Optional[str] = None,
progress_callback: Optional[Callable[[int, int, Dict], None]] = None,
- benchmark_type: str = "simpleqa",
+ benchmark_weights: Optional[Dict[str, float]] = None,
) -> Tuple[Dict[str, Any], float]:
"""
Optimize parameters with a focus on result quality.
@@ -161,7 +165,9 @@ def optimize_for_quality(
provider: LLM provider
search_tool: Search engine to use
progress_callback: Optional callback for progress updates
- benchmark_type: Type of benchmark to use ("simpleqa" or "browsecomp")
+ benchmark_weights: Dictionary mapping benchmark types to weights
+ (e.g., {"simpleqa": 0.6, "browsecomp": 0.4})
+ If None, only SimpleQA is used with weight 1.0
Returns:
Tuple of (best_parameters, best_score)
@@ -179,7 +185,7 @@ def optimize_for_quality(
metric_weights=metric_weights,
optimization_metrics=["quality", "speed"],
progress_callback=progress_callback,
- benchmark_type=benchmark_type,
+ benchmark_weights=benchmark_weights,
)
@@ -191,7 +197,7 @@ def optimize_for_efficiency(
provider: Optional[str] = None,
search_tool: Optional[str] = None,
progress_callback: Optional[Callable[[int, int, Dict], None]] = None,
- benchmark_type: str = "simpleqa",
+ benchmark_weights: Optional[Dict[str, float]] = None,
) -> Tuple[Dict[str, Any], float]:
"""
Optimize parameters with a focus on resource efficiency.
@@ -204,7 +210,9 @@ def optimize_for_efficiency(
provider: LLM provider
search_tool: Search engine to use
progress_callback: Optional callback for progress updates
- benchmark_type: Type of benchmark to use ("simpleqa" or "browsecomp")
+ benchmark_weights: Dictionary mapping benchmark types to weights
+ (e.g., {"simpleqa": 0.6, "browsecomp": 0.4})
+ If None, only SimpleQA is used with weight 1.0
Returns:
Tuple of (best_parameters, best_score)
@@ -222,7 +230,7 @@ def optimize_for_efficiency(
metric_weights=metric_weights,
optimization_metrics=["quality", "speed", "resource"],
progress_callback=progress_callback,
- benchmark_type=benchmark_type,
+ benchmark_weights=benchmark_weights,
)
diff --git a/src/local_deep_research/benchmarks/optimization/optuna_optimizer.py b/src/local_deep_research/benchmarks/optimization/optuna_optimizer.py
index 6623465a26..369aabc2a1 100644
--- a/src/local_deep_research/benchmarks/optimization/optuna_optimizer.py
+++ b/src/local_deep_research/benchmarks/optimization/optuna_optimizer.py
@@ -12,7 +12,7 @@ import os
import time
from datetime import datetime
from functools import partial
-from typing import Any, Callable, Dict, List, Optional, Tuple, Union
+from typing import Any, Callable, Dict, List, Optional, Tuple
import joblib
import numpy as np
@@ -24,13 +24,10 @@ from optuna.visualization import (
plot_slice,
)
-from local_deep_research.benchmarks import run_browsecomp_benchmark, run_simpleqa_benchmark
from local_deep_research.benchmarks.efficiency.speed_profiler import SpeedProfiler
+from local_deep_research.benchmarks.evaluators import CompositeBenchmarkEvaluator
-# Local Deep Research imports
-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 benchmark evaluator components
logger = logging.getLogger(__name__)
@@ -38,7 +35,8 @@ logger = logging.getLogger(__name__)
try:
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
- from matplotlib.patches import Circle, RegularPolygon
+
+ # We'll use matplotlib for plotting visualization results
PLOTTING_AVAILABLE = True
except ImportError:
@@ -46,92 +44,6 @@ except ImportError:
logger.warning("Matplotlib not available, visualization will be limited")
-def evaluate_benchmark_quality(
- system_config: Dict[str, Any],
- num_examples: int = 10,
- output_dir: Optional[str] = None,
- benchmark_type: str = "simpleqa",
-) -> Dict[str, float]:
- """
- Evaluate quality using a benchmark.
-
- Args:
- system_config: Configuration parameters to evaluate
- num_examples: Number of benchmark examples to use
- output_dir: Directory to save results (temporary if None)
- benchmark_type: Type of benchmark to use ("simpleqa" or "browsecomp")
-
- Returns:
- Dictionary with benchmark metrics
- """
- # Create temporary directory if not provided
- temp_dir = None
- if output_dir is None:
- import tempfile
-
- temp_dir = tempfile.mkdtemp(prefix="ldr_benchmark_")
- output_dir = temp_dir
-
- try:
- # Create search configuration from system config
- search_config = {
- "iterations": system_config.get("iterations", 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"),
- "provider": system_config.get("provider"),
- }
-
- # Run specified benchmark
- if benchmark_type.lower() == "browsecomp":
- logger.info(f"Running BrowseComp benchmark with {num_examples} examples")
- benchmark_results = run_browsecomp_benchmark(
- num_examples=num_examples,
- output_dir=output_dir,
- search_config=search_config,
- run_evaluation=True,
- )
- else: # Default to SimpleQA
- logger.info(f"Running SimpleQA benchmark with {num_examples} examples")
- benchmark_results = run_simpleqa_benchmark(
- num_examples=num_examples,
- output_dir=output_dir,
- search_config=search_config,
- run_evaluation=True,
- )
-
- # Extract key metrics
- metrics = benchmark_results.get("metrics", {})
- accuracy = metrics.get("accuracy", 0.0)
-
- # Return only the most relevant metrics
- return {
- "accuracy": accuracy,
- "quality_score": accuracy, # Map accuracy directly to quality score
- "benchmark_type": benchmark_type,
- }
-
- except Exception as e:
- logger.error(f"Error in benchmark evaluation: {str(e)}")
- return {
- "accuracy": 0.0,
- "quality_score": 0.0,
- "error": str(e),
- "benchmark_type": benchmark_type,
- }
-
- finally:
- # Clean up temporary directory if we created it
- if temp_dir and os.path.exists(temp_dir):
- import shutil
-
- try:
- shutil.rmtree(temp_dir)
- except Exception as e:
- logger.warning(f"Failed to clean up temporary directory: {str(e)}")
-
-
class OptunaOptimizer:
"""
Optimize parameters for Local Deep Research using Optuna.
@@ -158,7 +70,7 @@ class OptunaOptimizer:
optimization_metrics: Optional[List[str]] = None,
metric_weights: Optional[Dict[str, float]] = None,
progress_callback: Optional[Callable[[int, int, Dict], None]] = None,
- benchmark_type: str = "simpleqa",
+ benchmark_weights: Optional[Dict[str, float]] = None,
):
"""
Initialize the optimizer.
@@ -175,9 +87,11 @@ class OptunaOptimizer:
n_jobs: Number of parallel jobs for optimization
study_name: Name of the Optuna study
optimization_metrics: List of metrics to optimize (default: ["quality", "speed"])
- metric_weights: Dictionary of weights for each metric
+ metric_weights: Dictionary of weights for each metric (e.g., {"quality": 0.6, "speed": 0.4})
progress_callback: Optional callback for progress updates
- benchmark_type: Type of benchmark to use ("simpleqa" or "browsecomp")
+ benchmark_weights: Dictionary mapping benchmark types to weights
+ (e.g., {"simpleqa": 0.6, "browsecomp": 0.4})
+ If None, only SimpleQA is used with weight 1.0
"""
self.base_query = base_query
self.output_dir = output_dir
@@ -191,7 +105,10 @@ class OptunaOptimizer:
self.optimization_metrics = optimization_metrics or ["quality", "speed"]
self.metric_weights = metric_weights or {"quality": 0.6, "speed": 0.4}
self.progress_callback = progress_callback
- self.benchmark_type = benchmark_type
+
+ # Initialize benchmark evaluator with weights
+ self.benchmark_weights = benchmark_weights or {"simpleqa": 1.0}
+ self.benchmark_evaluator = CompositeBenchmarkEvaluator(self.benchmark_weights)
# Normalize weights to sum to 1.0
total_weight = sum(self.metric_weights.values())
@@ -248,6 +165,7 @@ class OptunaOptimizer:
)
logger.info(f"Parameter space: {param_space}")
logger.info(f"Metric weights: {self.metric_weights}")
+ logger.info(f"Benchmark weights: {self.benchmark_weights}")
# Initialize progress tracking
if self.progress_callback:
@@ -384,7 +302,7 @@ class OptunaOptimizer:
param_name,
param_config["low"],
param_config["high"],
- param_config.get("step", 1),
+ step=param_config.get("step", 1),
)
elif param_type == "float":
params[param_name] = trial.suggest_float(
@@ -510,13 +428,13 @@ class OptunaOptimizer:
"provider": self.provider,
}
- # Evaluate quality using specified benchmark type
+ # Evaluate quality using composite benchmark evaluator
# Use a small number of examples for efficiency
- quality_results = evaluate_benchmark_quality(
+ benchmark_dir = os.path.join(self.output_dir, "benchmark_temp")
+ quality_results = self.benchmark_evaluator.evaluate(
system_config=system_config,
num_examples=5, # Small number for optimization efficiency
- output_dir=os.path.join(self.output_dir, "benchmark_temp"),
- benchmark_type=self.benchmark_type,
+ output_dir=benchmark_dir,
)
# Stop timing
@@ -525,6 +443,7 @@ class OptunaOptimizer:
# Extract key metrics
quality_score = quality_results.get("quality_score", 0.0)
+ benchmark_results = quality_results.get("benchmark_results", {})
# Speed score: convert duration to a 0-1 score where faster is better
# Using a reasonable threshold (e.g., 180 seconds for 5 examples)
@@ -541,6 +460,7 @@ class OptunaOptimizer:
# Return streamlined results
return {
"quality_score": quality_score,
+ "benchmark_results": benchmark_results,
"speed_score": speed_score,
"total_duration": total_duration,
"score": combined_score,
@@ -613,7 +533,7 @@ class OptunaOptimizer:
"provider": self.provider,
"search_tool": self.search_tool,
"metric_weights": self.metric_weights,
- "benchmark_type": self.benchmark_type,
+ "benchmark_weights": self.benchmark_weights,
},
f,
indent=2,
@@ -838,7 +758,11 @@ class OptunaOptimizer:
cbar = plt.colorbar(scatter)
cbar.set_label("Trial Progression")
- plt.title("Quality vs. Speed Trade-off")
+ # Add benchmark weight information
+ 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.xlabel("Quality Score (Benchmark Accuracy)")
plt.ylabel("Speed Score")
plt.grid(True, linestyle="--", alpha=0.7)
@@ -1022,7 +946,7 @@ class OptunaOptimizer:
def optimize_parameters(
query: str,
param_space: Optional[Dict[str, Any]] = None,
- output_dir: str = "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,
@@ -1034,7 +958,7 @@ def optimize_parameters(
optimization_metrics: Optional[List[str]] = None,
metric_weights: Optional[Dict[str, float]] = None,
progress_callback: Optional[Callable[[int, int, Dict], None]] = None,
- benchmark_type: str = "simpleqa",
+ benchmark_weights: Optional[Dict[str, float]] = None,
) -> Tuple[Dict[str, Any], float]:
"""
Optimize parameters for Local Deep Research.
@@ -1052,9 +976,11 @@ def optimize_parameters(
n_jobs: Number of parallel jobs for optimization
study_name: Name of the Optuna study
optimization_metrics: List of metrics to optimize (default: ["quality", "speed"])
- metric_weights: Dictionary of weights for each metric
+ metric_weights: Dictionary of weights for each metric (e.g., {"quality": 0.6, "speed": 0.4})
progress_callback: Optional callback for progress updates
- benchmark_type: Type of benchmark to use ("simpleqa" or "browsecomp")
+ benchmark_weights: Dictionary mapping benchmark types to weights
+ (e.g., {"simpleqa": 0.6, "browsecomp": 0.4})
+ If None, only SimpleQA is used with weight 1.0
Returns:
Tuple of (best_parameters, best_score)
@@ -1074,7 +1000,7 @@ def optimize_parameters(
optimization_metrics=optimization_metrics,
metric_weights=metric_weights,
progress_callback=progress_callback,
- benchmark_type=benchmark_type,
+ benchmark_weights=benchmark_weights,
)
# Run optimization
@@ -1084,12 +1010,12 @@ def optimize_parameters(
def optimize_for_speed(
query: str,
n_trials: int = 20,
- output_dir: str = "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,
progress_callback: Optional[Callable[[int, int, Dict], None]] = None,
- benchmark_type: str = "simpleqa",
+ benchmark_weights: Optional[Dict[str, float]] = None,
) -> Tuple[Dict[str, Any], float]:
"""
Optimize parameters with a focus on speed performance.
@@ -1102,7 +1028,9 @@ def optimize_for_speed(
provider: LLM provider
search_tool: Search engine to use
progress_callback: Optional callback for progress updates
- benchmark_type: Type of benchmark to use ("simpleqa" or "browsecomp")
+ benchmark_weights: Dictionary mapping benchmark types to weights
+ (e.g., {"simpleqa": 0.6, "browsecomp": 0.4})
+ If None, only SimpleQA is used with weight 1.0
Returns:
Tuple of (best_parameters, best_score)
@@ -1141,19 +1069,19 @@ def optimize_for_speed(
metric_weights=metric_weights,
optimization_metrics=["speed", "quality"],
progress_callback=progress_callback,
- benchmark_type=benchmark_type,
+ benchmark_weights=benchmark_weights,
)
def optimize_for_quality(
query: str,
n_trials: int = 30,
- output_dir: str = "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,
progress_callback: Optional[Callable[[int, int, Dict], None]] = None,
- benchmark_type: str = "simpleqa",
+ benchmark_weights: Optional[Dict[str, float]] = None,
) -> Tuple[Dict[str, Any], float]:
"""
Optimize parameters with a focus on result quality.
@@ -1166,7 +1094,9 @@ def optimize_for_quality(
provider: LLM provider
search_tool: Search engine to use
progress_callback: Optional callback for progress updates
- benchmark_type: Type of benchmark to use ("simpleqa" or "browsecomp")
+ benchmark_weights: Dictionary mapping benchmark types to weights
+ (e.g., {"simpleqa": 0.6, "browsecomp": 0.4})
+ If None, only SimpleQA is used with weight 1.0
Returns:
Tuple of (best_parameters, best_score)
@@ -1184,5 +1114,50 @@ def optimize_for_quality(
metric_weights=metric_weights,
optimization_metrics=["quality", "speed"],
progress_callback=progress_callback,
- benchmark_type=benchmark_type,
+ benchmark_weights=benchmark_weights,
+ )
+
+
+def optimize_for_efficiency(
+ query: str,
+ n_trials: int = 25,
+ output_dir: str = os.path.join("data", "optimization_results"),
+ model_name: Optional[str] = None,
+ provider: Optional[str] = None,
+ search_tool: Optional[str] = None,
+ progress_callback: Optional[Callable[[int, int, Dict], None]] = None,
+ benchmark_weights: Optional[Dict[str, float]] = None,
+) -> Tuple[Dict[str, Any], float]:
+ """
+ Optimize parameters with a focus on resource efficiency.
+
+ Args:
+ query: The research query to use for all experiments
+ n_trials: Number of parameter combinations to try
+ output_dir: Directory to save optimization results
+ model_name: Name of the LLM model to use
+ provider: LLM provider
+ search_tool: Search engine to use
+ progress_callback: Optional callback for progress updates
+ benchmark_weights: Dictionary mapping benchmark types to weights
+ (e.g., {"simpleqa": 0.6, "browsecomp": 0.4})
+ If None, only SimpleQA is used with weight 1.0
+
+ Returns:
+ Tuple of (best_parameters, best_score)
+ """
+ # Balance of quality, speed and resource usage
+ metric_weights = {"quality": 0.4, "speed": 0.3, "resource": 0.3}
+
+ return optimize_parameters(
+ query=query,
+ output_dir=output_dir,
+ model_name=model_name,
+ provider=provider,
+ search_tool=search_tool,
+ n_trials=n_trials,
+ metric_weights=metric_weights,
+ optimization_metrics=["quality", "speed", "resource"],
+ progress_callback=progress_callback,
+ benchmark_weights=benchmark_weights,
)