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 benchmark module components and examples

LearningCircuitaa5531a29a8e
diff --git a/examples/benchmarks/README.md b/examples/benchmarks/README.md
new file mode 100644
index 0000000000..3e1f669e4d
--- /dev/null
+++ b/examples/benchmarks/README.md
@@ -0,0 +1,62 @@
+# Benchmarks for Local Deep Research
+
+This directory contains scripts for running benchmarks to evaluate Local Deep Research's performance.
+
+## Available Benchmarks
+
+### SimpleQA
+
+The SimpleQA benchmark evaluates factual question answering capabilities.
+
+```bash
+python run_simpleqa.py --examples 10 --iterations 3 --questions 3
+```
+
+Options:
+- `--examples`: Number of examples to run (default: 10)
+- `--iterations`: Number of search iterations (default: 3)
+- `--questions`: Questions per iteration (default: 3)
+- `--search-tool`: Search tool to use (default: "searxng")
+- `--output-dir`: Directory to save results (default: "benchmark_results")
+- `--no-eval`: Skip evaluation
+- `--human-eval`: Use human evaluation
+- `--eval-model`: Model to use for evaluation
+- `--eval-provider`: Provider to use for evaluation
+
+### BrowseComp
+
+The BrowseComp benchmark evaluates web browsing comprehension and complex question answering.
+
+```bash
+python run_browsecomp.py --examples 5 --iterations 3 --questions 3
+```
+
+Options:
+- `--examples`: Number of examples to run (default: 2)
+- `--iterations`: Number of search iterations (default: 1)
+- `--questions`: Questions per iteration (default: 1)
+- `--search-tool`: Search tool to use (default: "searxng")
+- `--output-dir`: Directory to save results (default: "browsecomp_results")
+
+See `browsecomp_benchmark_readme.md` for more information on how BrowseComp works.
+
+## Running All Benchmarks
+
+To run both benchmarks and compare results:
+
+```bash
+# Run SimpleQA with default settings
+python run_simpleqa.py
+
+# Run BrowseComp with increased iterations and questions
+python run_browsecomp.py --iterations 3 --questions 3
+```
+
+## Evaluating Results
+
+Results are saved in the specified output directories and include:
+- Raw results (JSONL format)
+- Evaluation results (JSONL format)
+- Summary reports (Markdown format)
+
+The scripts will also print a summary of the results to the console, including accuracy metrics.
\ No newline at end of file
diff --git a/examples/benchmarks/browsecomp_benchmark_readme.md b/examples/benchmarks/browsecomp_benchmark_readme.md
new file mode 100644
index 0000000000..4094f99bc7
--- /dev/null
+++ b/examples/benchmarks/browsecomp_benchmark_readme.md
@@ -0,0 +1,84 @@
+# BrowseComp Benchmark for Local Deep Research
+
+This document explains how to run the BrowseComp benchmark with Local Deep Research.
+
+## Overview
+
+BrowseComp is a benchmark created by OpenAI to evaluate models on their ability to understand complex questions that may require browsing the web for answers. The questions in BrowseComp often involve multiple criteria that must be satisfied by a single answer.
+
+The benchmark questions are initially provided in an encrypted format, which requires decryption using a "canary" field in the dataset.
+
+## Running the Benchmark
+
+We've created a script called `browsecomp_fixed.py` in the root directory that properly decrypts the BrowseComp questions and runs them through Local Deep Research.
+
+### Basic Usage
+
+```bash
+python /path/to/browsecomp_fixed.py --examples 5 --iterations 3 --questions 3
+```
+
+### Parameters
+
+- `--examples`: Number of examples to run (default: 5)
+- `--iterations`: Number of search iterations per query (default: 1)
+- `--questions`: Questions per iteration (default: 1)
+- `--search-tool`: Search tool to use (default: "searxng")
+- `--output-dir`: Directory to save results (default: "browsecomp_results")
+
+### Performance Tips
+
+BrowseComp questions are challenging and may require more thorough search strategies:
+
+1. **Use more iterations**: Increasing the number of iterations allows the system to refine its understanding of the question and explore different aspects.
+ ```bash
+ python browsecomp_fixed.py --iterations 5
+ ```
+
+2. **Increase questions per iteration**: More questions means more angles to explore.
+ ```bash
+ python browsecomp_fixed.py --questions 5
+ ```
+
+3. **Try different search engines**: Some search engines might perform better for certain types of questions.
+ ```bash
+ python browsecomp_fixed.py --search-tool wikipedia
+ ```
+
+4. **Combine parameters for best results**:
+ ```bash
+ python browsecomp_fixed.py --examples 10 --iterations 3 --questions 3 --search-tool searxng
+ ```
+
+## Understanding the Results
+
+The script saves results in the output directory with the following files:
+
+- `browsecomp_[timestamp]_results.jsonl`: Raw results from the benchmark
+- `browsecomp_[timestamp]_evaluation.jsonl`: Evaluation of the results by a grader model
+
+The script will also print a summary with:
+- Overall accuracy
+- Number of correct answers
+- Average processing time
+
+## How It Works
+
+1. The script loads the BrowseComp dataset
+2. For each example, it decrypts the problem and correct answer using the "canary" field
+3. It runs the decrypted question through LDR's search system
+4. It extracts the answer from LDR's response
+5. A grader evaluates whether the extracted answer matches the correct answer
+
+## Improving Benchmark Performance
+
+To improve performance on the BrowseComp benchmark:
+
+1. Optimize parameters for more thorough search (more iterations and questions)
+2. Use search engines that provide more relevant results for complex queries
+3. Consider pre-processing or reformulating the questions to better match search engine capabilities
+4. Experiment with different search strategies in LDR's configuration
+
+## Technical Details
+
+The decryption process uses a simple XOR cipher with a key derived from the canary value using SHA-256. This matches the approach used in the original BrowseComp evaluation script.
\ No newline at end of file
diff --git a/examples/benchmarks/run_browsecomp.py b/examples/benchmarks/run_browsecomp.py
new file mode 100644
index 0000000000..19842419e6
--- /dev/null
+++ b/examples/benchmarks/run_browsecomp.py
@@ -0,0 +1,245 @@
+#!/usr/bin/env python
+"""
+BrowseComp benchmark with proper decryption.
+
+This script runs the BrowseComp benchmark with proper decryption using the canary field.
+"""
+
+import base64
+import hashlib
+import json
+import logging
+import os
+import re
+import sys
+import time
+from typing import Dict, Any, List, Optional
+
+# Configure logging
+logging.basicConfig(
+ 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__)))))
+
+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.graders import grade_results
+
+
+def derive_key(password: str, length: int) -> bytes:
+ """Derive a fixed-length key from the password using SHA256."""
+ hasher = hashlib.sha256()
+ hasher.update(password.encode())
+ key = hasher.digest()
+ return key * (length // len(key)) + key[: length % len(key)]
+
+
+def decrypt(ciphertext_b64: str, password: str) -> str:
+ """Decrypt base64-encoded ciphertext with XOR."""
+ try:
+ encrypted = base64.b64decode(ciphertext_b64)
+ key = derive_key(password, len(encrypted))
+ decrypted = bytes(a ^ b for a, b in zip(encrypted, key))
+ return decrypted.decode()
+ except Exception as e:
+ logger.error(f"Error decrypting data: {str(e)}")
+ return f"Error: Could not decrypt data - {str(e)}"
+
+
+def run_browsecomp_with_canary(
+ num_examples: int = 5,
+ search_iterations: int = 1,
+ questions_per_iteration: int = 1,
+ search_tool: str = "searxng",
+ 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")
+
+ # 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]}...")
+
+ # Format query for BrowseComp
+ 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,
+ iterations=search_iterations,
+ 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}"),
+ "problem": decrypted_question, # Store decrypted question
+ "correct_answer": decrypted_answer, # Store decrypted answer
+ "response": response,
+ "extracted_answer": exact_answer,
+ "confidence": confidence,
+ "processing_time": processing_time,
+ "sources": search_result.get("sources", []),
+ "search_config": {
+ "iterations": search_iterations,
+ "questions_per_iteration": questions_per_iteration,
+ "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",
+ "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:
+ evaluation_results = grade_results(
+ results_file=results_file,
+ output_file=evaluation_file,
+ dataset_type="browsecomp",
+ )
+ 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))
+ 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
+
+ print("\nBrowseComp Benchmark Results:")
+ print(f" Accuracy: {accuracy:.3f}")
+ print(f" Total examples: {total_examples}")
+ print(f" Correct answers: {correct_count}")
+ print(f" Average time: {avg_time:.2f}s")
+ print()
+ print(f"Report saved to: {evaluation_file}")
+
+ return {
+ "status": "complete",
+ "dataset_type": "browsecomp",
+ "results_path": results_file,
+ "evaluation_path": evaluation_file,
+ "metrics": {"accuracy": accuracy, "average_processing_time": avg_time},
+ "total_examples": total_examples,
+ "accuracy": accuracy,
+ }
+
+
+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")
+
+ args = parser.parse_args()
+
+ run_browsecomp_with_canary(
+ num_examples=args.examples,
+ search_iterations=args.iterations,
+ questions_per_iteration=args.questions,
+ search_tool=args.search_tool,
+ output_dir=args.output_dir,
+ )
+
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
\ No newline at end of file
diff --git a/examples/benchmarks/run_simpleqa.py b/examples/benchmarks/run_simpleqa.py
new file mode 100644
index 0000000000..fab3216f85
--- /dev/null
+++ b/examples/benchmarks/run_simpleqa.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+"""
+SimpleQA Benchmark Runner for Local Deep Research.
+
+This script provides a convenient way to run the SimpleQA benchmark.
+"""
+
+import argparse
+import sys
+import os
+
+# Add the project root to the path
+sys.path.insert(0, os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))
+
+# Import the benchmark functionality
+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("--no-eval", action="store_true", help="Skip evaluation")
+
+ # Optional evaluation parameters
+ parser.add_argument("--human-eval", action="store_true", help="Use human evaluation")
+ parser.add_argument("--eval-model", type=str, help="Model to use for evaluation")
+ parser.add_argument("--eval-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,
+ search_iterations=args.iterations,
+ questions_per_iteration=args.questions,
+ search_tool=args.search_tool,
+ human_evaluation=args.human_eval,
+ evaluation_model=args.eval_model,
+ 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
diff --git a/examples/optimization/README.md b/examples/optimization/README.md
new file mode 100644
index 0000000000..147fcde5c6
--- /dev/null
+++ b/examples/optimization/README.md
@@ -0,0 +1,70 @@
+# Optimization Tools for Local Deep Research
+
+This directory contains scripts for optimizing Local Deep Research's parameters.
+
+## Parameter Optimization
+
+Optimization helps find the best settings for different use cases:
+- **Balanced**: Optimizes for a good balance of speed and quality
+- **Speed-focused**: Prioritizes faster responses
+- **Quality-focused**: Prioritizes more accurate, comprehensive answers
+- **Efficiency**: Balances quality, speed, and resource usage
+
+## Available Scripts
+
+### Main Optimization Runner
+
+`run_optimization.py` provides a command-line interface for running different types of optimization:
+
+```bash
+python run_optimization.py "What are the latest developments in fusion energy?" --mode quality --trials 20
+```
+
+Options:
+- `query`: The research query to use for optimization
+- `--output-dir`: Directory to save results (default: "optimization_results")
+- `--search-tool`: Search tool to use (default: "searxng")
+- `--model`: Model name for the LLM
+- `--provider`: Provider for the LLM
+- `--trials`: Number of parameter combinations to try (default: 30)
+- `--mode`: Optimization mode ("balanced", "speed", "quality", "efficiency")
+- `--weights`: Custom weights as JSON string, e.g., '{"quality": 0.7, "speed": 0.3}'
+
+### Example Scripts
+
+- `example_optimization.py`: Full example with all optimization modes
+- `example_quick_optimization.py`: Simplified example for quick testing
+
+## How Optimization Works
+
+The optimization process:
+1. Defines a parameter space to explore (iterations, questions per iteration, search strategy, etc.)
+2. Runs multiple trials with different parameter combinations
+3. Evaluates each combination using benchmarks
+4. Uses Optuna to efficiently search for the best parameters
+5. Returns the optimal parameters and stores detailed results
+
+## Example Parameter Space
+
+Optimization explores parameters such as:
+- `iterations`: Number of search iterations
+- `questions_per_iteration`: Number of questions to generate per iteration
+- `search_strategy`: Search strategy to use ("standard", "rapid", "iterdrag", etc.)
+- `max_results`: Maximum number of search results to consider
+- Other system-specific parameters
+
+## Using Optimization Results
+
+After running optimization, you can use the resulting parameters by updating your configuration:
+
+```python
+from local_deep_research.api import quick_summary
+
+results = quick_summary(
+ query="What are the latest developments in fusion energy?",
+ iterations=best_params["iterations"],
+ questions_per_iteration=best_params["questions_per_iteration"],
+ search_strategy=best_params["search_strategy"],
+ # Other optimized parameters
+)
+```
\ No newline at end of file
diff --git a/examples/optimization/example_optimization.py b/examples/optimization/example_optimization.py
new file mode 100644
index 0000000000..8abba4535e
--- /dev/null
+++ b/examples/optimization/example_optimization.py
@@ -0,0 +1,81 @@
+# example_optimization.py - Quick Demo Version
+
+import os
+import logging
+import json
+from datetime import datetime
+
+# Import the optimization functionality
+from local_deep_research.benchmarks.optimization import (
+ optimize_parameters,
+ optimize_for_speed,
+ optimize_for_quality
+)
+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'
+)
+
+def main():
+ # Create timestamp for unique output directory
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ output_dir = f"optimization_results_{timestamp}"
+ os.makedirs(output_dir, exist_ok=True)
+
+ print(f"Starting quick optimization demo - results will be saved to {output_dir}")
+
+ # Demo with just a single simple optimization
+ print("\n=== Running quick demo optimization ===")
+
+ # Create a very simple parameter set to test
+ 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"], # Just use the fastest strategy
+ },
+ }
+
+ 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
+ output_dir=os.path.join(output_dir, "demo"),
+ param_space=param_space, # Limited parameter space
+ metric_weights={"quality": 0.5, "speed": 0.5}
+ )
+
+ print(f"Best parameters: {balanced_params}")
+ print(f"Best score: {balanced_score:.4f}")
+
+ # Save demo results to a summary file
+ summary = {
+ "timestamp": timestamp,
+ "demo": {
+ "parameters": balanced_params,
+ "score": balanced_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}")
+ 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
new file mode 100644
index 0000000000..7319d3e985
--- /dev/null
+++ b/examples/optimization/example_quick_optimization.py
@@ -0,0 +1,257 @@
+# example_quick_optimization.py - Simplified Demo
+
+import os
+import logging
+import json
+import time
+import random
+from datetime import datetime
+from typing import Dict, Any, Tuple
+
+# Configure logging
+logging.basicConfig(
+ 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
+) -> 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)
+ )
+ elif param_config.get("type") == "categorical":
+ 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
+
+ # Calculate weighted score
+ 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}")
+
+ # 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}")
+
+ return best_params, best_score
+
+
+def optimize_for_speed(
+ 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)
+ """
+ if param_space is None:
+ param_space = {
+ "iterations": {
+ "type": "int",
+ "low": 1,
+ "high": 3,
+ },
+ "questions_per_iteration": {
+ "type": "int",
+ "low": 1,
+ "high": 3,
+ },
+ "search_strategy": {
+ "type": "categorical",
+ "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
+ )
+
+
+def optimize_for_quality(
+ 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)
+ """
+ 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": ["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
+ )
+
+
+def main():
+ # Create timestamp for unique output directory
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ output_dir = 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": {
+ "type": "int",
+ "low": 1,
+ "high": 3,
+ },
+ "questions_per_iteration": {
+ "type": "int",
+ "low": 1,
+ "high": 3,
+ },
+ "search_strategy": {
+ "type": "categorical",
+ "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}
+ )
+
+ 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)
+ }
+ }
+
+ 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("would run actual benchmarks with these parameters to evaluate performance.")
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/examples/optimization/run_optimization.py b/examples/optimization/run_optimization.py
new file mode 100644
index 0000000000..4e0c9f1f2b
--- /dev/null
+++ b/examples/optimization/run_optimization.py
@@ -0,0 +1,118 @@
+#!/usr/bin/env python
+"""
+Parameter Optimization Runner for Local Deep Research.
+
+This script provides a convenient way to run hyperparameter optimization.
+"""
+
+import argparse
+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__)))))
+
+# Import the optimization functionality
+from local_deep_research.benchmarks.optimization import (
+ optimize_parameters,
+ optimize_for_speed,
+ optimize_for_quality,
+ optimize_for_efficiency
+)
+
+
+def main():
+ """Run parameter optimization with command-line arguments."""
+ 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("--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}'")
+
+ 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}")
+
+ # Parse custom weights if provided
+ custom_weights = None
+ if args.weights:
+ try:
+ 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(
+ query=args.query,
+ search_tool=args.search_tool,
+ n_trials=args.trials,
+ model_name=args.model,
+ provider=args.provider,
+ output_dir=output_dir
+ )
+ elif args.mode == "quality":
+ best_params, best_score = optimize_for_quality(
+ query=args.query,
+ search_tool=args.search_tool,
+ n_trials=args.trials,
+ model_name=args.model,
+ provider=args.provider,
+ output_dir=output_dir
+ )
+ elif args.mode == "efficiency":
+ best_params, best_score = optimize_for_efficiency(
+ query=args.query,
+ search_tool=args.search_tool,
+ n_trials=args.trials,
+ model_name=args.model,
+ provider=args.provider,
+ output_dir=output_dir
+ )
+ else: # balanced
+ best_params, best_score = optimize_parameters(
+ query=args.query,
+ search_tool=args.search_tool,
+ n_trials=args.trials,
+ model_name=args.model,
+ provider=args.provider,
+ output_dir=output_dir,
+ 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,
+ "query": args.query,
+ "mode": args.mode,
+ "trials": args.trials,
+ "search_tool": args.search_tool,
+ "best_parameters": best_params,
+ "best_score": best_score,
+ "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
diff --git a/src/local_deep_research/benchmarks/cli.py b/src/local_deep_research/benchmarks/cli.py
new file mode 100644
index 0000000000..8d91e0a451
--- /dev/null
+++ b/src/local_deep_research/benchmarks/cli.py
@@ -0,0 +1,314 @@
+"""
+Command-line interface for benchmarking functionality.
+
+This module provides a command-line interface for running parameter
+optimization, comparison, and benchmarking tasks.
+"""
+
+import argparse
+import logging
+import os
+import sys
+from datetime import datetime
+from typing import List, Dict, Any, 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
+
+# Configure logging
+logging.basicConfig(
+ level=logging.INFO,
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
+)
+logger = logging.getLogger(__name__)
+
+
+def parse_args():
+ """Parse command line arguments."""
+ parser = argparse.ArgumentParser(
+ description='Local Deep Research Benchmarking Tools',
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ epilog="""
+Examples:
+ # Run parameter optimization
+ python -m local_deep_research.benchmarks.cli optimize "What are the latest advancements in quantum computing?"
+
+ # Compare different configurations
+ python -m local_deep_research.benchmarks.cli compare "What are the effects of climate change?" --configs configs.json
+
+ # 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')
+
+ # 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')
+
+ # 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')
+
+ # 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')
+
+ 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,
+ output_dir=args.output_dir,
+ model_name=args.model,
+ provider=args.provider,
+ search_tool=args.search_tool,
+ temperature=args.temperature,
+ n_trials=args.n_trials,
+ timeout=args.timeout,
+ n_jobs=args.n_jobs,
+ study_name=args.study_name,
+ 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:
+ 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,
+ configurations=configurations,
+ output_dir=args.output_dir,
+ model_name=args.model,
+ provider=args.provider,
+ search_tool=args.search_tool,
+ 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)]):
+ 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."""
+ 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
+ )
+
+ # 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():
+ if name != "total_duration" and name.endswith("_duration"):
+ component = name.replace("_duration", "")
+ duration = value
+ percent = (duration / total_duration * 100) if total_duration > 0 else 0
+ 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"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
+ },
+ "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)
+
+ 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
+
+
+def main():
+ """Main entry point for the CLI."""
+ args = parse_args()
+
+ if args.command == 'optimize':
+ return run_optimization(args)
+ elif args.command == 'compare':
+ return run_comparison(args)
+ elif args.command == 'profile':
+ return run_profiling(args)
+ else:
+ print("Please specify a command. Use --help for more information.")
+ return 1
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/src/local_deep_research/benchmarks/comparison/__init__.py b/src/local_deep_research/benchmarks/comparison/__init__.py
new file mode 100644
index 0000000000..9a6e94a77a
--- /dev/null
+++ b/src/local_deep_research/benchmarks/comparison/__init__.py
@@ -0,0 +1,12 @@
+"""
+Comparison submodule for evaluating different configurations of Local Deep Research.
+
+This module provides tools for comparing the performance of different
+parameters, models, and search engines.
+"""
+
+from local_deep_research.benchmarks.comparison.evaluator import compare_configurations
+
+__all__ = [
+ 'compare_configurations',
+]
diff --git a/src/local_deep_research/benchmarks/comparison/evaluator.py b/src/local_deep_research/benchmarks/comparison/evaluator.py
new file mode 100644
index 0000000000..813c5b24fe
--- /dev/null
+++ b/src/local_deep_research/benchmarks/comparison/evaluator.py
@@ -0,0 +1,768 @@
+"""
+Configuration comparison for Local Deep Research.
+
+This module provides functions for comparing different parameter configurations
+and evaluating their performance across various metrics.
+"""
+
+import json
+import logging
+import os
+import time
+from datetime import datetime
+from typing import Dict, List, Optional, Any, Tuple
+
+import numpy as np
+import matplotlib.pyplot as plt
+
+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
+from local_deep_research.benchmarks.efficiency.speed_profiler import SpeedProfiler
+from local_deep_research.benchmarks.efficiency.resource_monitor import ResourceMonitor
+from local_deep_research.benchmarks.optimization.metrics import (
+ calculate_quality_metrics,
+ calculate_speed_metrics,
+ calculate_resource_metrics,
+ calculate_combined_score
+)
+
+logger = logging.getLogger(__name__)
+
+
+def compare_configurations(
+ query: str,
+ configurations: List[Dict[str, Any]],
+ output_dir: str = "comparison_results",
+ model_name: Optional[str] = None,
+ provider: Optional[str] = None,
+ search_tool: Optional[str] = None,
+ repetitions: int = 1,
+ metric_weights: Optional[Dict[str, float]] = None,
+) -> Dict[str, Any]:
+ """
+ Compare multiple parameter configurations.
+
+ Args:
+ query: Research query to use for evaluation
+ configurations: List of parameter configurations to compare
+ output_dir: Directory to save comparison results
+ model_name: Name of the LLM model to use
+ provider: LLM provider
+ search_tool: Search engine to use
+ repetitions: Number of repetitions for each configuration
+ metric_weights: Dictionary of weights for each metric type
+
+ Returns:
+ Dictionary with comparison results
+ """
+ os.makedirs(output_dir, exist_ok=True)
+
+ # Default metric weights if not provided
+ if metric_weights is None:
+ metric_weights = {
+ "quality": 0.6,
+ "speed": 0.4,
+ "resource": 0.0 # Disabled by default
+ }
+
+ # Verify valid configurations
+ if not configurations:
+ logger.error("No configurations provided for comparison")
+ return {"error": "No configurations provided"}
+
+ # Results storage
+ results = []
+
+ # Process each configuration
+ for i, config in enumerate(configurations):
+ logger.info(f"Evaluating configuration {i+1}/{len(configurations)}: {config}")
+
+ # Name for this configuration
+ config_name = config.get("name", f"Configuration {i+1}")
+
+ # Results for all repetitions of this configuration
+ config_results = []
+
+ # Run multiple repetitions
+ for rep in range(repetitions):
+ logger.info(f"Starting repetition {rep+1}/{repetitions} for {config_name}")
+
+ try:
+ # Run the configuration
+ result = _evaluate_single_configuration(
+ query=query,
+ config=config,
+ model_name=model_name,
+ provider=provider,
+ search_tool=search_tool
+ )
+
+ config_results.append(result)
+ logger.info(f"Completed repetition {rep+1} for {config_name}")
+
+ except Exception as e:
+ logger.error(f"Error in {config_name}, repetition {rep+1}: {str(e)}")
+ # Add error info but continue with other configurations
+ config_results.append({
+ "error": str(e),
+ "success": False
+ })
+
+ # Calculate aggregate metrics across repetitions
+ if config_results:
+ # Filter out failed runs
+ successful_runs = [r for r in config_results if r.get("success", False)]
+
+ if successful_runs:
+ # Calculate average metrics
+ avg_metrics = _calculate_average_metrics(successful_runs)
+
+ # Calculate overall score
+ overall_score = calculate_combined_score(
+ quality_metrics=avg_metrics.get("quality_metrics", {}),
+ speed_metrics=avg_metrics.get("speed_metrics", {}),
+ resource_metrics=avg_metrics.get("resource_metrics", {}),
+ weights=metric_weights
+ )
+
+ result_summary = {
+ "name": config_name,
+ "configuration": config,
+ "success": True,
+ "runs_completed": len(successful_runs),
+ "runs_failed": len(config_results) - len(successful_runs),
+ "avg_metrics": avg_metrics,
+ "overall_score": overall_score,
+ "individual_results": config_results
+ }
+ else:
+ # All runs failed
+ result_summary = {
+ "name": config_name,
+ "configuration": config,
+ "success": False,
+ "runs_completed": 0,
+ "runs_failed": len(config_results),
+ "error": "All runs failed",
+ "individual_results": config_results
+ }
+
+ results.append(result_summary)
+
+ # Sort results by overall score (if available)
+ sorted_results = sorted(
+ [r for r in results if r.get("success", False)],
+ key=lambda x: x.get("overall_score", 0),
+ reverse=True
+ )
+
+ # Add failed configurations at the end
+ sorted_results.extend([r for r in results if not r.get("success", False)])
+
+ # Create comparison report
+ comparison_report = {
+ "query": query,
+ "configurations_tested": len(configurations),
+ "successful_configurations": len([r for r in results if r.get("success", False)]),
+ "failed_configurations": len([r for r in results if not r.get("success", False)]),
+ "repetitions": repetitions,
+ "metric_weights": metric_weights,
+ "timestamp": datetime.now().isoformat(),
+ "results": sorted_results
+ }
+
+ # Save results to file
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ result_file = os.path.join(output_dir, f"comparison_results_{timestamp}.json")
+
+ with open(result_file, "w") as f:
+ json.dump(comparison_report, f, indent=2)
+
+ # Generate visualizations
+ visualizations_dir = os.path.join(output_dir, "visualizations")
+ os.makedirs(visualizations_dir, exist_ok=True)
+
+ _create_comparison_visualizations(
+ comparison_report,
+ output_dir=visualizations_dir,
+ timestamp=timestamp
+ )
+
+ logger.info(f"Comparison completed. Results saved to {result_file}")
+
+ # Add report path to the result
+ comparison_report["report_path"] = result_file
+
+ return comparison_report
+
+
+def _evaluate_single_configuration(
+ query: str,
+ config: Dict[str, Any],
+ model_name: Optional[str] = None,
+ provider: Optional[str] = None,
+ search_tool: Optional[str] = None,
+) -> Dict[str, Any]:
+ """
+ Evaluate a single configuration.
+
+ Args:
+ query: Research query to evaluate
+ config: Configuration parameters
+ model_name: Name of the LLM model to use
+ provider: LLM provider
+ search_tool: Search engine to use
+
+ Returns:
+ Dictionary with evaluation results
+ """
+ # Extract configuration parameters
+ config_model_name = config.get("model_name", model_name)
+ config_provider = config.get("provider", provider)
+ config_search_tool = config.get("search_tool", search_tool)
+ config_iterations = config.get("iterations", 2)
+ config_questions_per_iteration = config.get("questions_per_iteration", 2)
+ config_search_strategy = config.get("search_strategy", "iterdrag")
+ config_max_results = config.get("max_results", 50)
+ config_max_filtered_results = config.get("max_filtered_results", 20)
+
+ # Initialize profiling tools
+ speed_profiler = SpeedProfiler()
+ resource_monitor = ResourceMonitor(sampling_interval=0.5)
+
+ # Start profiling
+ speed_profiler.start()
+ resource_monitor.start()
+
+ try:
+ # Get LLM
+ with speed_profiler.timer("llm_initialization"):
+ llm = get_llm(
+ temperature=config.get("temperature", 0.7),
+ model_name=config_model_name,
+ provider=config_provider
+ )
+
+ # Set up search engine if specified
+ with speed_profiler.timer("search_initialization"):
+ search = None
+ if config_search_tool:
+ search = get_search(
+ config_search_tool,
+ llm_instance=llm,
+ max_results=config_max_results,
+ max_filtered_results=config_max_filtered_results
+ )
+
+ # Create search system
+ system = AdvancedSearchSystem(llm=llm, search=search)
+ system.max_iterations = config_iterations
+ system.questions_per_iteration = config_questions_per_iteration
+ system.strategy_name = config_search_strategy
+
+ # Run the analysis
+ with speed_profiler.timer("analysis"):
+ results = system.analyze_topic(query)
+
+ # Stop profiling
+ speed_profiler.stop()
+ resource_monitor.stop()
+
+ # Calculate metrics
+ quality_metrics = calculate_quality_metrics(
+ results=results,
+ system_info={"all_links_of_system": getattr(system, "all_links_of_system", [])}
+ )
+
+ speed_metrics = calculate_speed_metrics(
+ timing_info=speed_profiler.get_summary(),
+ system_info={
+ "iterations": config_iterations,
+ "questions_per_iteration": config_questions_per_iteration,
+ "results": results
+ }
+ )
+
+ resource_metrics = calculate_resource_metrics(
+ resource_info=resource_monitor.get_combined_stats(),
+ system_info={
+ "iterations": config_iterations,
+ "questions_per_iteration": config_questions_per_iteration,
+ "results": results
+ }
+ )
+
+ # Return comprehensive results
+ return {
+ "query": query,
+ "config": config,
+ "success": True,
+ "findings_count": len(results.get("findings", [])),
+ "knowledge_length": len(results.get("current_knowledge", "")),
+ "quality_metrics": quality_metrics,
+ "speed_metrics": speed_metrics,
+ "resource_metrics": resource_metrics,
+ "timing_details": speed_profiler.get_timings(),
+ "resource_details": resource_monitor.get_combined_stats()
+ }
+
+ except Exception as e:
+ # Stop profiling on error
+ speed_profiler.stop()
+ resource_monitor.stop()
+
+ # Log the error
+ logger.error(f"Error evaluating configuration: {str(e)}")
+
+ # Return error information
+ return {
+ "query": query,
+ "config": config,
+ "success": False,
+ "error": str(e),
+ "timing_details": speed_profiler.get_timings(),
+ "resource_details": resource_monitor.get_combined_stats()
+ }
+
+
+def _calculate_average_metrics(results: List[Dict[str, Any]]) -> Dict[str, Any]:
+ """
+ Calculate average metrics across multiple runs.
+
+ Args:
+ results: List of individual run results
+
+ Returns:
+ Dictionary with averaged metrics
+ """
+ # Check if there are any successful results
+ if not results:
+ return {}
+
+ # Initialize average metrics
+ avg_metrics = {
+ "quality_metrics": {},
+ "speed_metrics": {},
+ "resource_metrics": {}
+ }
+
+ # Quality metrics
+ quality_keys = set()
+ for result in results:
+ quality_metrics = result.get("quality_metrics", {})
+ quality_keys.update(quality_metrics.keys())
+
+ for key in quality_keys:
+ values = [r.get("quality_metrics", {}).get(key) for r in results]
+ values = [v for v in values if v is not None]
+ if values:
+ avg_metrics["quality_metrics"][key] = sum(values) / len(values)
+
+ # Speed metrics
+ speed_keys = set()
+ for result in results:
+ speed_metrics = result.get("speed_metrics", {})
+ speed_keys.update(speed_metrics.keys())
+
+ for key in speed_keys:
+ values = [r.get("speed_metrics", {}).get(key) for r in results]
+ values = [v for v in values if v is not None]
+ if values:
+ avg_metrics["speed_metrics"][key] = sum(values) / len(values)
+
+ # Resource metrics
+ resource_keys = set()
+ for result in results:
+ resource_metrics = result.get("resource_metrics", {})
+ resource_keys.update(resource_metrics.keys())
+
+ for key in resource_keys:
+ values = [r.get("resource_metrics", {}).get(key) for r in results]
+ values = [v for v in values if v is not None]
+ if values:
+ avg_metrics["resource_metrics"][key] = sum(values) / len(values)
+
+ return avg_metrics
+
+
+def _create_comparison_visualizations(
+ comparison_report: Dict[str, Any],
+ output_dir: str,
+ timestamp: str
+):
+ """
+ Create visualizations for the comparison results.
+
+ Args:
+ comparison_report: Comparison report dictionary
+ output_dir: Directory to save visualizations
+ timestamp: Timestamp string for filenames
+ """
+ # Check if there are successful results
+ successful_results = [
+ r for r in comparison_report.get("results", [])
+ if r.get("success", False)
+ ]
+
+ if not successful_results:
+ logger.warning("No successful configurations to visualize")
+ return
+
+ # Extract configuration names
+ config_names = [r.get("name", f"Config {i+1}") for i, r in enumerate(successful_results)]
+
+ # 1. Overall score comparison
+ plt.figure(figsize=(12, 6))
+ scores = [r.get("overall_score", 0) for r in successful_results]
+
+ # Create horizontal bar chart
+ plt.barh(config_names, scores, color='skyblue')
+ plt.xlabel('Overall Score')
+ plt.ylabel('Configuration')
+ plt.title('Configuration Performance Comparison')
+ plt.grid(axis='x', linestyle='--', alpha=0.7)
+ plt.tight_layout()
+ plt.savefig(os.path.join(output_dir, f"overall_score_comparison_{timestamp}.png"))
+ plt.close()
+
+ # 2. Quality metrics comparison
+ quality_metrics = ["overall_quality", "source_count", "lexical_diversity"]
+ _create_metric_comparison_chart(
+ successful_results,
+ config_names,
+ quality_metrics,
+ "quality_metrics",
+ "Quality Metrics Comparison",
+ os.path.join(output_dir, f"quality_metrics_comparison_{timestamp}.png")
+ )
+
+ # 3. Speed metrics comparison
+ speed_metrics = ["overall_speed", "total_duration", "duration_per_question"]
+ _create_metric_comparison_chart(
+ successful_results,
+ config_names,
+ speed_metrics,
+ "speed_metrics",
+ "Speed Metrics Comparison",
+ os.path.join(output_dir, f"speed_metrics_comparison_{timestamp}.png")
+ )
+
+ # 4. Resource metrics comparison
+ resource_metrics = ["overall_resource", "process_memory_max_mb", "system_cpu_avg"]
+ _create_metric_comparison_chart(
+ successful_results,
+ config_names,
+ resource_metrics,
+ "resource_metrics",
+ "Resource Usage Comparison",
+ os.path.join(output_dir, f"resource_metrics_comparison_{timestamp}.png")
+ )
+
+ # 5. Spider chart for multi-dimensional comparison
+ _create_spider_chart(
+ successful_results,
+ config_names,
+ os.path.join(output_dir, f"spider_chart_comparison_{timestamp}.png")
+ )
+
+ # 6. Pareto frontier chart for quality vs. speed
+ _create_pareto_chart(
+ successful_results,
+ os.path.join(output_dir, f"pareto_chart_comparison_{timestamp}.png")
+ )
+
+
+def _create_metric_comparison_chart(
+ results: List[Dict[str, Any]],
+ config_names: List[str],
+ metric_keys: List[str],
+ metric_category: str,
+ title: str,
+ output_path: str
+):
+ """
+ Create a chart comparing specific metrics across configurations.
+
+ Args:
+ results: List of configuration results
+ config_names: Names of configurations
+ metric_keys: Keys of metrics to compare
+ metric_category: Category of metrics (quality_metrics, speed_metrics, etc.)
+ title: Chart title
+ output_path: Path to save the chart
+ """
+ # Create figure with multiple subplots (one per metric)
+ fig, axes = plt.subplots(len(metric_keys), 1, figsize=(12, 5 * len(metric_keys)))
+
+ # Handle case with only one metric
+ if len(metric_keys) == 1:
+ axes = [axes]
+
+ for i, metric_key in enumerate(metric_keys):
+ ax = axes[i]
+
+ # Get metric values
+ metric_values = []
+ for result in results:
+ metrics = result.get("avg_metrics", {}).get(metric_category, {})
+ value = metrics.get(metric_key)
+
+ # Handle time values for better visualization
+ if "duration" in metric_key and value is not None:
+ # Convert to seconds if > 60 seconds, minutes if > 60 minutes
+ if value > 3600:
+ value = value / 3600 # Convert to hours
+ metric_key += " (hours)"
+ elif value > 60:
+ value = value / 60 # Convert to minutes
+ metric_key += " (minutes)"
+ else:
+ metric_key += " (seconds)"
+
+ metric_values.append(value if value is not None else 0)
+
+ # Create horizontal bar chart
+ bars = ax.barh(config_names, metric_values, color='lightblue')
+ ax.set_xlabel(metric_key.replace('_', ' ').title())
+ ax.set_title(f"{metric_key.replace('_', ' ').title()}")
+ ax.grid(axis='x', linestyle='--', alpha=0.7)
+
+ # Add value labels to bars
+ for bar in bars:
+ width = bar.get_width()
+ label_x_pos = width * 1.01
+ ax.text(label_x_pos, bar.get_y() + bar.get_height()/2, f'{width:.2f}',
+ va='center')
+
+ plt.suptitle(title, fontsize=16)
+ plt.tight_layout()
+ plt.savefig(output_path)
+ plt.close()
+
+
+def _create_spider_chart(
+ results: List[Dict[str, Any]],
+ config_names: List[str],
+ output_path: str
+):
+ """
+ Create a spider chart comparing metrics across configurations.
+
+ Args:
+ results: List of configuration results
+ config_names: Names of configurations
+ output_path: Path to save the chart
+ """
+ # Try to import the radar chart module
+ try:
+ from matplotlib.path import Path
+ from matplotlib.projections import register_projection
+ from matplotlib.projections.polar import PolarAxes
+ from matplotlib.spines import Spine
+
+ def radar_factory(num_vars, frame='circle'):
+ """Create a radar chart with `num_vars` axes."""
+ # Calculate evenly-spaced axis angles
+ theta = np.linspace(0, 2*np.pi, num_vars, endpoint=False)
+
+ class RadarAxes(PolarAxes):
+ name = 'radar'
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.set_theta_zero_location('N')
+
+ def fill(self, *args, closed=True, **kwargs):
+ return super().fill(closed=closed, *args, **kwargs)
+
+ def plot(self, *args, **kwargs):
+ return super().plot(*args, **kwargs)
+
+ def set_varlabels(self, labels):
+ self.set_thetagrids(np.degrees(theta), labels)
+
+ def _gen_axes_patch(self):
+ if frame == 'circle':
+ return Circle((0.5, 0.5), 0.5)
+ elif frame == 'polygon':
+ return RegularPolygon((0.5, 0.5), num_vars, radius=0.5, edgecolor="k")
+ else:
+ raise ValueError("Unknown value for 'frame': %s" % frame)
+
+ def _gen_axes_spines(self):
+ if frame == 'circle':
+ return super()._gen_axes_spines()
+ elif frame == 'polygon':
+ spine_type = Spine.circular_spine
+ verts = unit_poly_verts(num_vars)
+ vertices = [(0.5, 0.5)] + verts
+ codes = [Path.MOVETO] + [Path.LINETO] * num_vars + [Path.CLOSEPOLY]
+ path = Path(vertices, codes)
+ spine = Spine(self, spine_type, path)
+ spine.set_transform(self.transAxes)
+ return {'polar': spine}
+ else:
+ raise ValueError("Unknown value for 'frame': %s" % frame)
+
+ def unit_poly_verts(num_vars):
+ """Return vertices of polygon for radar chart."""
+ verts = []
+ for i in range(num_vars):
+ angle = theta[i]
+ verts.append((0.5 * (1 + np.cos(angle)), 0.5 * (1 + np.sin(angle))))
+ return verts
+
+ register_projection(RadarAxes)
+ return theta
+
+ # Select metrics for the spider chart
+ metrics = [
+ {"name": "Quality", "key": "quality_metrics.overall_quality"},
+ {"name": "Speed", "key": "speed_metrics.overall_speed"},
+ {"name": "Sources", "key": "quality_metrics.normalized_source_count"},
+ {"name": "Content", "key": "quality_metrics.normalized_knowledge_length"},
+ {"name": "Memory", "key": "resource_metrics.normalized_memory_usage", "invert": True},
+ ]
+
+ # Extract metric values
+ spoke_labels = [m["name"] for m in metrics]
+ num_vars = len(spoke_labels)
+ theta = radar_factory(num_vars)
+
+ fig, ax = plt.subplots(figsize=(10, 10), subplot_kw=dict(projection='radar'))
+
+ # Color map for different configurations
+ colors = plt.cm.viridis(np.linspace(0, 1, len(results)))
+
+ for i, result in enumerate(results):
+ values = []
+ for metric in metrics:
+ # Extract metric value using the key path (e.g., "quality_metrics.overall_quality")
+ key_parts = metric["key"].split(".")
+ value = result.get("avg_metrics", {})
+ for part in key_parts:
+ value = value.get(part, 0) if isinstance(value, dict) else 0
+
+ # Invert if needed (for metrics where lower is better)
+ if metric.get("invert", False):
+ value = 1.0 - value
+
+ values.append(value)
+
+ # Plot this configuration
+ ax.plot(theta, values, color=colors[i], linewidth=2, label=config_names[i])
+ ax.fill(theta, values, color=colors[i], alpha=0.25)
+
+ # Set chart properties
+ ax.set_varlabels(spoke_labels)
+ plt.legend(loc='best', bbox_to_anchor=(0.5, 0.1))
+ plt.title('Multi-Dimensional Configuration Comparison', size=16, y=1.05)
+ plt.tight_layout()
+
+ # Save chart
+ plt.savefig(output_path)
+ plt.close()
+
+ except Exception as e:
+ logger.error(f"Error creating spider chart: {str(e)}")
+ # Create a text-based chart as fallback
+ plt.figure(figsize=(10, 6))
+ plt.text(0.5, 0.5, f"Spider chart could not be created: {str(e)}",
+ horizontalalignment='center', verticalalignment='center')
+ plt.axis('off')
+ plt.savefig(output_path)
+ plt.close()
+
+
+def _create_pareto_chart(
+ results: List[Dict[str, Any]],
+ output_path: str
+):
+ """
+ Create a Pareto frontier chart showing quality vs. speed tradeoff.
+
+ Args:
+ results: List of configuration results
+ output_path: Path to save the chart
+ """
+ # Extract quality and speed metrics
+ quality_scores = []
+ speed_scores = []
+ names = []
+
+ for result in results:
+ metrics = result.get("avg_metrics", {})
+ quality = metrics.get("quality_metrics", {}).get("overall_quality", 0)
+
+ # For speed, we use inverse of duration (so higher is better)
+ duration = metrics.get("speed_metrics", {}).get("total_duration", 1)
+ speed = 1.0 / max(duration, 0.001) # Avoid division by zero
+
+ quality_scores.append(quality)
+ speed_scores.append(speed)
+ names.append(result.get("name", "Configuration"))
+
+ # Create scatter plot
+ plt.figure(figsize=(10, 8))
+ plt.scatter(quality_scores, speed_scores, s=100, alpha=0.7)
+
+ # Add labels for each point
+ for i, name in enumerate(names):
+ plt.annotate(name,
+ (quality_scores[i], speed_scores[i]),
+ xytext=(5, 5),
+ textcoords='offset points')
+
+ # Identify Pareto frontier
+ pareto_points = []
+ for i, (q, s) in enumerate(zip(quality_scores, speed_scores)):
+ is_pareto = True
+ for q2, s2 in zip(quality_scores, speed_scores):
+ if q2 > q and s2 > s: # Dominated
+ is_pareto = False
+ break
+ if is_pareto:
+ pareto_points.append(i)
+
+ # Highlight Pareto frontier
+ pareto_quality = [quality_scores[i] for i in pareto_points]
+ pareto_speed = [speed_scores[i] for i in pareto_points]
+
+ # Sort pareto points for line drawing
+ pareto_sorted = sorted(zip(pareto_quality, pareto_speed, pareto_points))
+ pareto_quality = [p[0] for p in pareto_sorted]
+ pareto_speed = [p[1] for p in pareto_sorted]
+ pareto_indices = [p[2] for p in pareto_sorted]
+
+ # Draw Pareto frontier line
+ plt.plot(pareto_quality, pareto_speed, 'r--', linewidth=2)
+
+ # Highlight Pareto optimal points
+ plt.scatter([quality_scores[i] for i in pareto_indices],
+ [speed_scores[i] for i in pareto_indices],
+ s=150, facecolors='none', edgecolors='r', linewidth=2)
+
+ # Add labels for Pareto optimal configurations
+ for i in pareto_indices:
+ plt.annotate(names[i],
+ (quality_scores[i], speed_scores[i]),
+ xytext=(8, 8),
+ textcoords='offset points',
+ bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.7))
+
+ # Set chart properties
+ plt.xlabel('Quality Score (higher is better)')
+ plt.ylabel('Speed Score (higher is better)')
+ plt.title('Quality vs. Speed Tradeoff (Pareto Frontier)', size=14)
+ plt.grid(True, linestyle='--', alpha=0.7)
+
+ # Add explanation
+ plt.figtext(0.5, 0.01,
+ "Points on the red line are Pareto optimal configurations\n"
+ "(no other configuration is better in both quality and speed)",
+ ha='center', fontsize=10, bbox=dict(boxstyle='round', fc='white', alpha=0.7))
+
+ plt.tight_layout()
+ plt.savefig(output_path)
+ plt.close()
\ No newline at end of file
diff --git a/src/local_deep_research/benchmarks/efficiency/__init__.py b/src/local_deep_research/benchmarks/efficiency/__init__.py
new file mode 100644
index 0000000000..f2f088b60f
--- /dev/null
+++ b/src/local_deep_research/benchmarks/efficiency/__init__.py
@@ -0,0 +1,14 @@
+"""
+Efficiency submodule for speed and resource monitoring in Local Deep Research.
+
+This module provides tools for measuring and optimizing execution speed
+and resource usage of the research system.
+"""
+
+from local_deep_research.benchmarks.efficiency.speed_profiler import SpeedProfiler
+from local_deep_research.benchmarks.efficiency.resource_monitor import ResourceMonitor
+
+__all__ = [
+ 'SpeedProfiler',
+ 'ResourceMonitor',
+]
diff --git a/src/local_deep_research/benchmarks/efficiency/resource_monitor.py b/src/local_deep_research/benchmarks/efficiency/resource_monitor.py
new file mode 100644
index 0000000000..21271f1b8b
--- /dev/null
+++ b/src/local_deep_research/benchmarks/efficiency/resource_monitor.py
@@ -0,0 +1,367 @@
+"""
+Resource monitoring tools for Local Deep Research.
+
+This module provides functionality for tracking CPU, memory and other
+system resource usage during the research process.
+"""
+
+import logging
+import threading
+import time
+from contextlib import contextmanager
+from typing import Dict, List, Optional, Any, Callable, Tuple
+
+logger = logging.getLogger(__name__)
+
+# Try to import psutil, but don't fail if not available
+try:
+ import psutil
+ PSUTIL_AVAILABLE = True
+except ImportError:
+ PSUTIL_AVAILABLE = False
+ logger.warning("psutil not available, resource monitoring will be limited")
+
+
+class ResourceMonitor:
+ """
+ Monitor system resource usage during research.
+
+ This class provides methods for tracking CPU, memory, and disk usage
+ during system execution. It can be used to identify resource bottlenecks
+ and optimize configurations for different hardware environments.
+ """
+
+ def __init__(self,
+ sampling_interval: float = 1.0,
+ track_process: bool = True,
+ track_system: bool = True):
+ """
+ Initialize the resource monitor.
+
+ Args:
+ sampling_interval: Seconds between resource usage measurements
+ track_process: Whether to track this process's resource usage
+ track_system: Whether to track overall system resource usage
+ """
+ self.sampling_interval = sampling_interval
+ self.track_process = track_process
+ self.track_system = track_system
+
+ self.monitoring = False
+ self.monitor_thread = None
+
+ # Resource usage data
+ self.process_data = []
+ self.system_data = []
+ self.start_time = None
+ self.end_time = None
+
+ # Check if we can monitor resources
+ self.can_monitor = PSUTIL_AVAILABLE
+ if not self.can_monitor:
+ logger.warning("Resource monitoring requires psutil. Install with: pip install psutil")
+
+ def start(self):
+ """Start monitoring resource usage."""
+ if not self.can_monitor:
+ logger.warning("Resource monitoring not available (psutil not installed)")
+ return
+
+ if self.monitoring:
+ logger.warning("Resource monitoring already started")
+ return
+
+ self.process_data = []
+ self.system_data = []
+ self.start_time = time.time()
+ self.monitoring = True
+
+ # Start monitoring in a background thread
+ self.monitor_thread = threading.Thread(
+ target=self._monitor_resources,
+ daemon=True
+ )
+ self.monitor_thread.start()
+
+ logger.info(f"Resource monitoring started with {self.sampling_interval}s interval")
+
+ def stop(self):
+ """Stop monitoring resource usage."""
+ if not self.monitoring:
+ return
+
+ self.monitoring = False
+ self.end_time = time.time()
+
+ # Wait for the monitoring thread to finish
+ if self.monitor_thread:
+ self.monitor_thread.join(timeout=2.0)
+ self.monitor_thread = None
+
+ logger.info("Resource monitoring stopped")
+
+ def _monitor_resources(self):
+ """Background thread that collects resource usage data."""
+ if not PSUTIL_AVAILABLE:
+ return
+
+ # Get this process
+ current_process = psutil.Process()
+
+ while self.monitoring:
+ timestamp = time.time()
+
+ try:
+ # Monitor this process
+ if self.track_process:
+ process_cpu = current_process.cpu_percent(interval=None)
+ process_memory = current_process.memory_info()
+
+ self.process_data.append({
+ 'timestamp': timestamp,
+ 'cpu_percent': process_cpu,
+ 'memory_rss': process_memory.rss, # Resident Set Size in bytes
+ 'memory_vms': process_memory.vms, # Virtual Memory Size in bytes
+ 'memory_shared': getattr(process_memory, 'shared', 0),
+ 'num_threads': current_process.num_threads(),
+ 'open_files': len(current_process.open_files()),
+ 'status': current_process.status()
+ })
+
+ # Monitor overall system
+ if self.track_system:
+ system_cpu = psutil.cpu_percent(interval=None)
+ system_memory = psutil.virtual_memory()
+ system_disk = psutil.disk_usage('/')
+
+ self.system_data.append({
+ 'timestamp': timestamp,
+ 'cpu_percent': system_cpu,
+ 'memory_total': system_memory.total,
+ 'memory_available': system_memory.available,
+ 'memory_used': system_memory.used,
+ 'memory_percent': system_memory.percent,
+ 'disk_total': system_disk.total,
+ 'disk_used': system_disk.used,
+ 'disk_percent': system_disk.percent
+ })
+
+ except Exception as e:
+ logger.error(f"Error monitoring resources: {str(e)}")
+
+ # Sleep until next sampling interval
+ time.sleep(self.sampling_interval)
+
+ @contextmanager
+ def monitor(self):
+ """
+ Context manager for monitoring resources during a block of code.
+
+ Example:
+ with resource_monitor.monitor():
+ # Code to monitor
+ do_something_resource_intensive()
+ """
+ self.start()
+ try:
+ yield
+ finally:
+ self.stop()
+
+ def get_process_stats(self) -> Dict[str, Any]:
+ """
+ Get statistics about this process's resource usage.
+
+ Returns:
+ Dictionary with process resource usage statistics
+ """
+ if not self.process_data:
+ return {}
+
+ # Extract data series
+ timestamps = [d['timestamp'] for d in self.process_data]
+ cpu_values = [d['cpu_percent'] for d in self.process_data]
+ memory_values = [d['memory_rss'] / (1024 * 1024) for d in self.process_data] # Convert to MB
+
+ # Calculate statistics
+ stats = {
+ 'start_time': self.start_time,
+ 'end_time': self.end_time,
+ 'duration': self.end_time - self.start_time if self.end_time else None,
+ 'sample_count': len(self.process_data),
+ 'cpu_min': min(cpu_values) if cpu_values else None,
+ 'cpu_max': max(cpu_values) if cpu_values else None,
+ 'cpu_avg': sum(cpu_values) / len(cpu_values) if cpu_values else None,
+ 'memory_min_mb': min(memory_values) if memory_values else None,
+ 'memory_max_mb': max(memory_values) if memory_values else None,
+ 'memory_avg_mb': sum(memory_values) / len(memory_values) if memory_values else None,
+ 'thread_max': max(d['num_threads'] for d in self.process_data) if self.process_data else None,
+ }
+
+ return stats
+
+ def get_system_stats(self) -> Dict[str, Any]:
+ """
+ Get statistics about overall system resource usage.
+
+ Returns:
+ Dictionary with system resource usage statistics
+ """
+ if not self.system_data:
+ return {}
+
+ # Extract data series
+ timestamps = [d['timestamp'] for d in self.system_data]
+ cpu_values = [d['cpu_percent'] for d in self.system_data]
+ memory_values = [d['memory_percent'] for d in self.system_data]
+ disk_values = [d['disk_percent'] for d in self.system_data]
+
+ # Calculate statistics
+ stats = {
+ 'start_time': self.start_time,
+ 'end_time': self.end_time,
+ 'duration': self.end_time - self.start_time if self.end_time else None,
+ 'sample_count': len(self.system_data),
+ 'cpu_min': min(cpu_values) if cpu_values else None,
+ 'cpu_max': max(cpu_values) if cpu_values else None,
+ 'cpu_avg': sum(cpu_values) / len(cpu_values) if cpu_values else None,
+ 'memory_min_percent': min(memory_values) if memory_values else None,
+ 'memory_max_percent': max(memory_values) if memory_values else None,
+ 'memory_avg_percent': sum(memory_values) / len(memory_values) if memory_values else None,
+ 'disk_min_percent': min(disk_values) if disk_values else None,
+ 'disk_max_percent': max(disk_values) if disk_values else None,
+ 'disk_avg_percent': sum(disk_values) / len(disk_values) if disk_values else None,
+ 'memory_total_gb': self.system_data[0]['memory_total'] / (1024**3) if self.system_data else None,
+ 'disk_total_gb': self.system_data[0]['disk_total'] / (1024**3) if self.system_data else None,
+ }
+
+ return stats
+
+ def get_combined_stats(self) -> Dict[str, Any]:
+ """
+ Get combined resource usage statistics.
+
+ Returns:
+ Dictionary with both process and system statistics
+ """
+ process_stats = self.get_process_stats()
+ system_stats = self.get_system_stats()
+
+ # Combine stats
+ stats = {
+ 'start_time': self.start_time,
+ 'end_time': self.end_time,
+ 'duration': self.end_time - self.start_time if self.end_time else None,
+ }
+
+ # Add process stats with 'process_' prefix
+ for key, value in process_stats.items():
+ if key not in ['start_time', 'end_time', 'duration']:
+ stats[f'process_{key}'] = value
+
+ # Add system stats with 'system_' prefix
+ for key, value in system_stats.items():
+ if key not in ['start_time', 'end_time', 'duration']:
+ stats[f'system_{key}'] = value
+
+ # Calculate derived metrics
+ if (process_stats.get('memory_max_mb') is not None and
+ system_stats.get('memory_total_gb') is not None):
+
+ # Process memory as percentage of total system memory
+ system_memory_mb = system_stats['memory_total_gb'] * 1024
+ stats['process_memory_percent'] = (
+ (process_stats['memory_max_mb'] / system_memory_mb) * 100
+ if system_memory_mb > 0 else 0
+ )
+
+ return stats
+
+ def print_summary(self):
+ """Print a formatted summary of resource usage."""
+ process_stats = self.get_process_stats()
+ system_stats = self.get_system_stats()
+
+ print("\n===== RESOURCE USAGE SUMMARY =====")
+
+ if process_stats:
+ print("\n--- Process Resources ---")
+ print(f"CPU usage: {process_stats.get('cpu_avg', 0):.1f}% avg, "
+ f"{process_stats.get('cpu_max', 0):.1f}% peak")
+ print(f"Memory usage: {process_stats.get('memory_avg_mb', 0):.1f} MB avg, "
+ f"{process_stats.get('memory_max_mb', 0):.1f} MB peak")
+ print(f"Threads: {process_stats.get('thread_max', 0)} max")
+
+ if system_stats:
+ print("\n--- System Resources ---")
+ print(f"CPU usage: {system_stats.get('cpu_avg', 0):.1f}% avg, "
+ f"{system_stats.get('cpu_max', 0):.1f}% peak")
+ print(f"Memory usage: {system_stats.get('memory_avg_percent', 0):.1f}% avg, "
+ f"{system_stats.get('memory_max_percent', 0):.1f}% peak "
+ f"(Total: {system_stats.get('memory_total_gb', 0):.1f} GB)")
+ print(f"Disk usage: {system_stats.get('disk_avg_percent', 0):.1f}% avg "
+ f"(Total: {system_stats.get('disk_total_gb', 0):.1f} GB)")
+
+ print("\n===================================")
+
+ def export_data(self) -> Dict[str, Any]:
+ """
+ Export all collected data.
+
+ Returns:
+ Dictionary with all collected resource usage data
+ """
+ return {
+ 'start_time': self.start_time,
+ 'end_time': self.end_time,
+ 'sampling_interval': self.sampling_interval,
+ 'process_data': self.process_data,
+ 'system_data': self.system_data
+ }
+
+
+def check_system_resources() -> Dict[str, Any]:
+ """
+ Check current system resources.
+
+ Returns:
+ Dictionary with current resource usage information
+ """
+ if not PSUTIL_AVAILABLE:
+ return {
+ 'error': 'psutil not available',
+ 'available': False
+ }
+
+ try:
+ # Get basic system information
+ cpu_count = psutil.cpu_count(logical=True)
+ cpu_physical = psutil.cpu_count(logical=False)
+ cpu_percent = psutil.cpu_percent(interval=0.1)
+
+ memory = psutil.virtual_memory()
+ disk = psutil.disk_usage('/')
+
+ # Format results
+ result = {
+ 'available': True,
+ 'cpu_count': cpu_count,
+ 'cpu_physical': cpu_physical,
+ 'cpu_percent': cpu_percent,
+ 'memory_total_gb': memory.total / (1024**3),
+ 'memory_available_gb': memory.available / (1024**3),
+ 'memory_used_gb': memory.used / (1024**3),
+ 'memory_percent': memory.percent,
+ 'disk_total_gb': disk.total / (1024**3),
+ 'disk_free_gb': disk.free / (1024**3),
+ 'disk_percent': disk.percent
+ }
+
+ return result
+
+ except Exception as e:
+ logger.error(f"Error checking system resources: {str(e)}")
+ return {
+ 'error': str(e),
+ 'available': False
+ }
diff --git a/src/local_deep_research/benchmarks/efficiency/speed_profiler.py b/src/local_deep_research/benchmarks/efficiency/speed_profiler.py
new file mode 100644
index 0000000000..b5fdfbfe37
--- /dev/null
+++ b/src/local_deep_research/benchmarks/efficiency/speed_profiler.py
@@ -0,0 +1,214 @@
+"""
+Speed profiling tools for Local Deep Research.
+
+This module provides functionality for measuring execution time
+of different components and processes in the research system.
+"""
+
+import logging
+import time
+from contextlib import contextmanager
+from typing import Dict, List, Optional, Any, Callable
+
+logger = logging.getLogger(__name__)
+
+
+class SpeedProfiler:
+ """
+ Profiler for tracking execution speed of components.
+
+ This class provides methods for timing operations and
+ collecting performance statistics for later analysis.
+ """
+
+ def __init__(self):
+ """Initialize the profiler with empty timing data."""
+ self.timings = {}
+ self.current_timers = {}
+ self.total_start_time = None
+ self.total_end_time = None
+
+ def start(self):
+ """Start the global profiling session."""
+ self.timings = {}
+ self.current_timers = {}
+ self.total_start_time = time.time()
+
+ def stop(self):
+ """Stop the global profiling session."""
+ self.total_end_time = time.time()
+
+ # Stop any timers that are still running
+ for name in list(self.current_timers.keys()):
+ self.stop_timer(name)
+
+ def start_timer(self, name: str):
+ """
+ Start a named timer.
+
+ Args:
+ name: Name of the timer to start
+ """
+ if name in self.current_timers:
+ logger.warning(f"Timer '{name}' is already running. Restarting.")
+
+ self.current_timers[name] = time.time()
+
+ def stop_timer(self, name: str):
+ """
+ Stop a named timer and record the elapsed time.
+
+ Args:
+ name: Name of the timer to stop
+ """
+ if name not in self.current_timers:
+ logger.warning(f"Timer '{name}' was not started.")
+ return
+
+ elapsed = time.time() - self.current_timers[name]
+
+ if name not in self.timings:
+ self.timings[name] = {
+ "total": elapsed,
+ "count": 1,
+ "min": elapsed,
+ "max": elapsed,
+ "starts": [self.current_timers[name]],
+ "durations": [elapsed]
+ }
+ else:
+ self.timings[name]["total"] += elapsed
+ self.timings[name]["count"] += 1
+ self.timings[name]["min"] = min(self.timings[name]["min"], elapsed)
+ self.timings[name]["max"] = max(self.timings[name]["max"], elapsed)
+ self.timings[name]["starts"].append(self.current_timers[name])
+ self.timings[name]["durations"].append(elapsed)
+
+ del self.current_timers[name]
+
+ @contextmanager
+ def timer(self, name: str):
+ """
+ Context manager for timing a block of code.
+
+ Args:
+ name: Name of the timer
+
+ Example:
+ with profiler.timer("my_operation"):
+ # Code to time
+ do_something()
+ """
+ self.start_timer(name)
+ try:
+ yield
+ finally:
+ self.stop_timer(name)
+
+ def get_timings(self) -> Dict[str, Any]:
+ """
+ Get all recorded timings.
+
+ Returns:
+ Dictionary of timing data for all measured operations
+ """
+ result = self.timings.copy()
+
+ # Add averages
+ for name, data in result.items():
+ if data["count"] > 0:
+ data["avg"] = data["total"] / data["count"]
+
+ # Add total duration
+ if self.total_start_time is not None and self.total_end_time is not None:
+ result["total"] = {
+ "total": self.total_end_time - self.total_start_time,
+ "count": 1,
+ "min": self.total_end_time - self.total_start_time,
+ "max": self.total_end_time - self.total_start_time,
+ "avg": self.total_end_time - self.total_start_time,
+ "starts": [self.total_start_time],
+ "durations": [self.total_end_time - self.total_start_time]
+ }
+
+ return result
+
+ def get_summary(self) -> Dict[str, float]:
+ """
+ Get a summary of timing information.
+
+ Returns:
+ Dictionary with summary statistics
+ """
+ timings = self.get_timings()
+ summary = {}
+
+ # Total duration
+ if "total" in timings:
+ summary["total_duration"] = timings["total"]["total"]
+ elif self.total_start_time is not None and self.total_end_time is not None:
+ summary["total_duration"] = self.total_end_time - self.total_start_time
+ else:
+ summary["total_duration"] = sum(t["total"] for t in timings.values())
+
+ # Component durations
+ for name, data in timings.items():
+ if name != "total":
+ summary[f"{name}_duration"] = data["total"]
+ summary[f"{name}_percent"] = (
+ data["total"] / summary["total_duration"] * 100
+ if summary["total_duration"] > 0 else 0
+ )
+
+ # Per-operation breakdowns
+ for name, data in timings.items():
+ if data["count"] > 0:
+ summary[f"{name}_per_operation"] = data["total"] / data["count"]
+
+ return summary
+
+ def print_summary(self):
+ """Print a formatted summary of timing information."""
+ summary = self.get_summary()
+ total = summary.get("total_duration", 0)
+
+ print("\n===== SPEED PROFILE SUMMARY =====")
+ print(f"Total execution time: {total:.2f} seconds")
+ print("\n--- Component Breakdown ---")
+
+ # Print each component's timing
+ for name, data in self.timings.items():
+ if name != "total":
+ percent = data["total"] / total * 100 if total > 0 else 0
+ print(f"{name}: {data['total']:.2f}s ({percent:.1f}%) - "
+ f"{data['count']} calls, avg {data['total'] / data['count']:.3f}s per call")
+
+ print("\n==============================")
+
+
+def time_function(func: Callable) -> Callable:
+ """
+ Decorator to time a function's execution.
+
+ Args:
+ func: Function to time
+
+ Returns:
+ Wrapped function that logs its execution time
+
+ Example:
+ @time_function
+ def my_slow_function():
+ # Some slow code
+ pass
+ """
+ def wrapper(*args, **kwargs):
+ start_time = time.time()
+ result = func(*args, **kwargs)
+ elapsed = time.time() - start_time
+
+ logger.info(f"{func.__name__} took {elapsed:.3f} seconds")
+
+ return result
+
+ return wrapper