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 benchmarking framework and update .gitignore

LearningCircuite3425ba1a5fe
diff --git a/.gitignore b/.gitignore
index 98c6c63a8e..e55c449f64 100644
--- a/.gitignore
+++ b/.gitignore
@@ -64,3 +64,9 @@ js-db/
*.sarif
codeql_analysis_results.txt
.coverage
+
+# benchmark results for examples
+examples/benchmark_results/
+
+# benchmark results for src
+src/benchmark_results/
diff --git a/src/benchmark-simple-qa.py b/src/benchmark-simple-qa.py
index e695895584..60b98945bf 100644
--- a/src/benchmark-simple-qa.py
+++ b/src/benchmark-simple-qa.py
@@ -121,7 +121,7 @@ def summarize_results(results_file: str):
if __name__ == "__main__":
print("Starting SimpleQA benchmark...")
# Start with a small sample for testing
- run_simpleqa_evaluation(num_examples=500)
+ run_simpleqa_evaluation(num_examples=800)
# Summarize results
summarize_results("ldr_simpleqa_results.jsonl")
diff --git a/src/local_deep_research/api/benchmark_functions.py b/src/local_deep_research/api/benchmark_functions.py
new file mode 100644
index 0000000000..794d36fdd7
--- /dev/null
+++ b/src/local_deep_research/api/benchmark_functions.py
@@ -0,0 +1,288 @@
+"""
+API functions for benchmarking.
+
+This module provides functions for running benchmarks programmatically.
+"""
+
+import logging
+from typing import Any, Dict, List, Optional
+
+from ..benchmarks import (
+ calculate_metrics,
+ generate_report,
+ run_benchmark,
+ run_browsecomp_benchmark,
+ run_simpleqa_benchmark,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def evaluate_simpleqa(
+ num_examples: int = 100,
+ search_iterations: int = 3,
+ questions_per_iteration: int = 3,
+ search_tool: str = "searxng",
+ human_evaluation: bool = False,
+ evaluation_model: Optional[str] = None,
+ evaluation_provider: Optional[str] = None,
+ output_dir: str = "benchmark_results",
+) -> Dict[str, Any]:
+ """
+ Run SimpleQA benchmark evaluation.
+
+ 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 (e.g., 'searxng', 'wikipedia')
+ human_evaluation: Whether to use human evaluation
+ evaluation_model: Optional custom model for evaluation
+ evaluation_provider: Optional custom provider for evaluation
+ output_dir: Directory to save results
+
+ Returns:
+ Dictionary with benchmark results
+ """
+ logger.info(f"Starting SimpleQA benchmark with {num_examples} examples")
+
+ # Set up search configuration
+ search_config = {
+ "iterations": search_iterations,
+ "questions_per_iteration": questions_per_iteration,
+ "search_tool": search_tool,
+ }
+
+ # Set up evaluation configuration if needed
+ evaluation_config = None
+ if evaluation_model or evaluation_provider:
+ evaluation_config = {}
+ if evaluation_model:
+ evaluation_config["model_name"] = evaluation_model
+ if evaluation_provider:
+ evaluation_config["provider"] = evaluation_provider
+
+ # Run the benchmark
+ results = run_simpleqa_benchmark(
+ num_examples=num_examples,
+ output_dir=output_dir,
+ search_config=search_config,
+ evaluation_config=evaluation_config,
+ human_evaluation=human_evaluation,
+ )
+
+ return results
+
+
+def evaluate_browsecomp(
+ num_examples: int = 100,
+ search_iterations: int = 3,
+ questions_per_iteration: int = 3,
+ search_tool: str = "searxng",
+ human_evaluation: bool = False,
+ evaluation_model: Optional[str] = None,
+ evaluation_provider: Optional[str] = None,
+ output_dir: str = "benchmark_results",
+) -> Dict[str, Any]:
+ """
+ Run BrowseComp benchmark evaluation.
+
+ 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 (e.g., 'searxng', 'wikipedia')
+ human_evaluation: Whether to use human evaluation
+ evaluation_model: Optional custom model for evaluation
+ evaluation_provider: Optional custom provider for evaluation
+ output_dir: Directory to save results
+
+ Returns:
+ Dictionary with benchmark results
+ """
+ logger.info(f"Starting BrowseComp benchmark with {num_examples} examples")
+
+ # Set up search configuration
+ search_config = {
+ "iterations": search_iterations,
+ "questions_per_iteration": questions_per_iteration,
+ "search_tool": search_tool,
+ }
+
+ # Set up evaluation configuration if needed
+ evaluation_config = None
+ if evaluation_model or evaluation_provider:
+ evaluation_config = {}
+ if evaluation_model:
+ evaluation_config["model_name"] = evaluation_model
+ if evaluation_provider:
+ evaluation_config["provider"] = evaluation_provider
+
+ # Run the benchmark
+ results = run_browsecomp_benchmark(
+ num_examples=num_examples,
+ output_dir=output_dir,
+ search_config=search_config,
+ evaluation_config=evaluation_config,
+ human_evaluation=human_evaluation,
+ )
+
+ return results
+
+
+def get_available_benchmarks() -> List[Dict[str, str]]:
+ """
+ Get information about available benchmarks.
+
+ Returns:
+ List of dictionaries with benchmark information
+ """
+ return [
+ {
+ "id": "simpleqa",
+ "name": "SimpleQA",
+ "description": "Benchmark for factual question answering",
+ "recommended_examples": 100,
+ },
+ {
+ "id": "browsecomp",
+ "name": "BrowseComp",
+ "description": "Benchmark for web browsing comprehension",
+ "recommended_examples": 100,
+ },
+ ]
+
+
+def compare_configurations(
+ dataset_type: str = "simpleqa",
+ num_examples: int = 20,
+ configurations: List[Dict[str, Any]] = None,
+ output_dir: str = "benchmark_comparisons",
+) -> Dict[str, Any]:
+ """
+ Compare multiple search configurations on the same benchmark.
+
+ Args:
+ dataset_type: Type of dataset to use
+ num_examples: Number of examples to evaluate
+ configurations: List of search configurations to compare
+ output_dir: Directory to save results
+
+ Returns:
+ Dictionary with comparison results
+ """
+ if not configurations:
+ # Default configurations to compare
+ configurations = [
+ {
+ "name": "Base Config",
+ "search_tool": "searxng",
+ "iterations": 1,
+ "questions_per_iteration": 3,
+ },
+ {
+ "name": "More Iterations",
+ "search_tool": "searxng",
+ "iterations": 3,
+ "questions_per_iteration": 3,
+ },
+ {
+ "name": "More Questions",
+ "search_tool": "searxng",
+ "iterations": 1,
+ "questions_per_iteration": 5,
+ },
+ ]
+
+ # Create output directory
+ import os
+
+ os.makedirs(output_dir, exist_ok=True)
+
+ # Run benchmarks for each configuration
+ results = []
+ for config in configurations:
+ config_name = config.pop("name", f"Config-{len(results)}")
+
+ logger.info(f"Running benchmark with configuration: {config_name}")
+
+ search_config = {
+ "iterations": config.pop("iterations", 1),
+ "questions_per_iteration": config.pop("questions_per_iteration", 3),
+ "search_tool": config.pop("search_tool", "searxng"),
+ }
+
+ # Add any remaining config items
+ for key, value in config.items():
+ search_config[key] = value
+
+ # Run benchmark with this configuration
+ benchmark_result = run_benchmark(
+ dataset_type=dataset_type,
+ num_examples=num_examples,
+ output_dir=os.path.join(output_dir, config_name.replace(" ", "_")),
+ search_config=search_config,
+ run_evaluation=True,
+ )
+
+ # Add configuration name to results
+ benchmark_result["configuration_name"] = config_name
+ benchmark_result["search_config"] = search_config
+
+ results.append(benchmark_result)
+
+ # Generate comparison report
+ import time
+
+ timestamp = time.strftime("%Y%m%d_%H%M%S")
+ report_file = os.path.join(output_dir, f"comparison_{dataset_type}_{timestamp}.md")
+
+ with open(report_file, "w") as f:
+ f.write(f"# Configuration Comparison - {dataset_type.capitalize()}\n\n")
+
+ # Write summary table
+ f.write("## Summary\n\n")
+ f.write("| Configuration | Accuracy | Avg. Time | Examples |\n")
+ f.write("|---------------|----------|-----------|----------|\n")
+
+ for result in results:
+ accuracy = result.get("metrics", {}).get("accuracy", 0)
+ avg_time = result.get("metrics", {}).get("average_processing_time", 0)
+ examples = result.get("total_examples", 0)
+
+ f.write(
+ f"| {result['configuration_name']} | {accuracy:.3f} | {avg_time:.2f}s | {examples} |\n"
+ )
+
+ f.write("\n## Configuration Details\n\n")
+
+ for result in results:
+ f.write(f"### {result['configuration_name']}\n\n")
+
+ config = result.get("search_config", {})
+ f.write("```\n")
+ for key, value in config.items():
+ f.write(f"{key}: {value}\n")
+ f.write("```\n\n")
+
+ logger.info(f"Comparison report saved to {report_file}")
+
+ return {
+ "status": "complete",
+ "dataset_type": dataset_type,
+ "configurations_tested": len(configurations),
+ "report_path": report_file,
+ "results": results,
+ }
+
+
+# Export the API functions
+__all__ = [
+ "evaluate_simpleqa",
+ "evaluate_browsecomp",
+ "get_available_benchmarks",
+ "compare_configurations",
+ "run_benchmark", # For advanced users
+ "calculate_metrics",
+ "generate_report",
+]
diff --git a/src/local_deep_research/benchmarks/README.md b/src/local_deep_research/benchmarks/README.md
new file mode 100644
index 0000000000..deca3446a5
--- /dev/null
+++ b/src/local_deep_research/benchmarks/README.md
@@ -0,0 +1,162 @@
+# LDR Benchmarking Framework
+
+The Local Deep Research (LDR) Benchmarking Framework allows you to evaluate and compare LDR's performance on standardized benchmarks.
+
+## Features
+
+- Run benchmarks on SimpleQA and BrowseComp datasets
+- Configure search parameters (iterations, questions per iteration, search tool)
+- Use automated evaluation with Claude 3.7 Sonnet (default) or other models
+- Generate detailed reports with metrics and examples
+- Compare multiple configurations to find optimal settings
+- API, CLI, and web interface integration
+
+## Benchmark Datasets
+
+### SimpleQA
+
+A straightforward question-answering benchmark with factual questions. This benchmark tests LDR's ability to find and synthesize factual information.
+
+### BrowseComp
+
+A web browsing comprehension benchmark with more complex questions requiring synthesis across multiple sources. This benchmark tests LDR's ability to understand and navigate complex information needs.
+
+## Usage
+
+### Programmatic API
+
+```python
+from local_deep_research.api.benchmark_functions import evaluate_simpleqa
+
+# Run SimpleQA benchmark with 20 examples
+result = evaluate_simpleqa(
+ num_examples=20,
+ search_iterations=3,
+ questions_per_iteration=3,
+ search_tool="searxng"
+)
+
+# Print accuracy
+print(f"Accuracy: {result['metrics']['accuracy']:.3f}")
+```
+
+### Command Line Interface
+
+```bash
+# Run SimpleQA benchmark
+python -m local_deep_research.cli.benchmark_commands simpleqa --examples 20 --iterations 3
+
+# Run BrowseComp benchmark
+python -m local_deep_research.cli.benchmark_commands browsecomp --examples 10 --search-tool wikipedia
+
+# Compare configurations
+python -m local_deep_research.cli.benchmark_commands compare --dataset simpleqa --examples 5
+```
+
+### Web Interface
+
+The benchmark dashboard is available at `/benchmark` in the LDR web interface. You can:
+
+1. Select a benchmark to run
+2. Configure parameters
+3. Run the benchmark
+4. View results and reports
+
+## Evaluation
+
+By default, benchmarks are evaluated using Claude 3.7 Sonnet via OpenRouter. You can customize the evaluation model:
+
+```python
+# Use a different model for evaluation
+result = evaluate_simpleqa(
+ num_examples=10,
+ evaluation_model="gpt-4o",
+ evaluation_provider="openai"
+)
+```
+
+You can also use human evaluation:
+
+```python
+# Use human evaluation
+result = evaluate_simpleqa(
+ num_examples=5,
+ human_evaluation=True
+)
+```
+
+## Configuration Comparison
+
+Compare multiple configurations to find optimal settings:
+
+```python
+from local_deep_research.api.benchmark_functions import compare_configurations
+
+# Define configurations to compare
+configurations = [
+ {
+ "name": "Base Config",
+ "search_tool": "searxng",
+ "iterations": 1,
+ "questions_per_iteration": 3
+ },
+ {
+ "name": "More Iterations",
+ "search_tool": "searxng",
+ "iterations": 3,
+ "questions_per_iteration": 3
+ },
+ {
+ "name": "Different Search Engine",
+ "search_tool": "wikipedia",
+ "iterations": 1,
+ "questions_per_iteration": 3
+ }
+]
+
+# Run comparison
+result = compare_configurations(
+ dataset_type="simpleqa",
+ num_examples=10,
+ configurations=configurations
+)
+```
+
+## Output Format
+
+Benchmark results include:
+
+- **metrics**: Accuracy, processing time, confidence scores
+- **report_path**: Path to generated report
+- **results_path**: Path to raw results file
+- **total_examples**: Number of examples processed
+- **status**: Completion status
+
+## Example Reports
+
+Reports include:
+
+- Overall accuracy and metrics
+- Configuration details
+- Example correct and incorrect answers
+- Time and date information
+
+## Integration with LDR Web App
+
+The benchmarking framework is fully integrated with the LDR web interface. You can run benchmarks and view results directly in the web app.
+
+## Adding Custom Benchmarks
+
+To add a custom benchmark:
+
+1. Create a dataset loader in `datasets.py`
+2. Add evaluation templates in `templates.py`
+3. Create benchmark runners in `runners.py`
+4. Expose the benchmark through the API in `api/benchmark_functions.py`
+
+## Performance Considerations
+
+- Running benchmarks can be resource-intensive
+- Start with a small number of examples for testing
+- Full benchmarks with 100+ examples may take several hours to complete
+- Consider using a more powerful machine for large benchmarks
diff --git a/src/local_deep_research/benchmarks/__init__.py b/src/local_deep_research/benchmarks/__init__.py
new file mode 100644
index 0000000000..85cf2434ba
--- /dev/null
+++ b/src/local_deep_research/benchmarks/__init__.py
@@ -0,0 +1,23 @@
+"""
+Benchmarking module for Local Deep Research.
+
+This module provides tools for evaluating LDR's performance on standard benchmarks.
+"""
+
+__version__ = "0.1.0"
+
+from .datasets import get_available_datasets, load_dataset
+from .metrics import calculate_metrics, generate_report
+
+# Import public APIs for easy access
+from .runners import run_benchmark, run_browsecomp_benchmark, run_simpleqa_benchmark
+
+__all__ = [
+ "run_benchmark",
+ "run_simpleqa_benchmark",
+ "run_browsecomp_benchmark",
+ "load_dataset",
+ "get_available_datasets",
+ "calculate_metrics",
+ "generate_report",
+]
diff --git a/src/local_deep_research/benchmarks/benchmark_functions.py b/src/local_deep_research/benchmarks/benchmark_functions.py
new file mode 100644
index 0000000000..6a7ff7e863
--- /dev/null
+++ b/src/local_deep_research/benchmarks/benchmark_functions.py
@@ -0,0 +1,302 @@
+"""
+API functions for benchmarking.
+
+This module provides functions for running benchmarks programmatically.
+"""
+
+import logging
+from typing import Any, Dict, List, Optional
+
+from ..benchmarks import (
+ calculate_metrics,
+ generate_report,
+ run_benchmark,
+ run_browsecomp_benchmark,
+ run_simpleqa_benchmark,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def evaluate_simpleqa(
+ num_examples: int = 100,
+ search_iterations: int = 3,
+ questions_per_iteration: int = 3,
+ search_tool: str = "searxng",
+ human_evaluation: bool = False,
+ evaluation_model: Optional[str] = None,
+ evaluation_provider: Optional[str] = None,
+ output_dir: str = "benchmark_results",
+) -> Dict[str, Any]:
+ """
+ Run SimpleQA benchmark evaluation.
+
+ 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 (e.g., 'searxng', 'wikipedia')
+ human_evaluation: Whether to use human evaluation
+ evaluation_model: Optional custom model for evaluation
+ evaluation_provider: Optional custom provider for evaluation
+ output_dir: Directory to save results
+
+ Returns:
+ Dictionary with benchmark results
+ """
+ logger.info(f"Starting SimpleQA benchmark with {num_examples} examples")
+
+ # Set up search configuration
+ search_config = {
+ "iterations": search_iterations,
+ "questions_per_iteration": questions_per_iteration,
+ "search_tool": search_tool,
+ }
+
+ # Set up evaluation configuration if needed
+ evaluation_config = None
+ if evaluation_model or evaluation_provider:
+ evaluation_config = {
+ "temperature": 0 # Always use zero temperature for evaluation
+ }
+ if evaluation_model:
+ evaluation_config["model_name"] = evaluation_model
+ if evaluation_provider:
+ evaluation_config["provider"] = evaluation_provider
+ # Add OpenRouter URL if using openai_endpoint
+ if evaluation_provider == "openai_endpoint":
+ evaluation_config["openai_endpoint_url"] = (
+ "https://openrouter.ai/api/v1"
+ )
+
+ # Run the benchmark
+ results = run_simpleqa_benchmark(
+ num_examples=num_examples,
+ output_dir=output_dir,
+ search_config=search_config,
+ evaluation_config=evaluation_config,
+ human_evaluation=human_evaluation,
+ )
+
+ return results
+
+
+def evaluate_browsecomp(
+ num_examples: int = 100,
+ search_iterations: int = 3,
+ questions_per_iteration: int = 3,
+ search_tool: str = "searxng",
+ human_evaluation: bool = False,
+ evaluation_model: Optional[str] = None,
+ evaluation_provider: Optional[str] = None,
+ output_dir: str = "benchmark_results",
+) -> Dict[str, Any]:
+ """
+ Run BrowseComp benchmark evaluation.
+
+ 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 (e.g., 'searxng', 'wikipedia')
+ human_evaluation: Whether to use human evaluation
+ evaluation_model: Optional custom model for evaluation
+ evaluation_provider: Optional custom provider for evaluation
+ output_dir: Directory to save results
+
+ Returns:
+ Dictionary with benchmark results
+ """
+ logger.info(f"Starting BrowseComp benchmark with {num_examples} examples")
+
+ # Set up search configuration
+ search_config = {
+ "iterations": search_iterations,
+ "questions_per_iteration": questions_per_iteration,
+ "search_tool": search_tool,
+ }
+
+ # Set up evaluation configuration if needed
+ evaluation_config = None
+ if evaluation_model or evaluation_provider:
+ evaluation_config = {
+ "temperature": 0 # Always use zero temperature for evaluation
+ }
+ if evaluation_model:
+ evaluation_config["model_name"] = evaluation_model
+ if evaluation_provider:
+ evaluation_config["provider"] = evaluation_provider
+ # Add OpenRouter URL if using openai_endpoint
+ if evaluation_provider == "openai_endpoint":
+ evaluation_config["openai_endpoint_url"] = (
+ "https://openrouter.ai/api/v1"
+ )
+
+ # Run the benchmark
+ results = run_browsecomp_benchmark(
+ num_examples=num_examples,
+ output_dir=output_dir,
+ search_config=search_config,
+ evaluation_config=evaluation_config,
+ human_evaluation=human_evaluation,
+ )
+
+ return results
+
+
+def get_available_benchmarks() -> List[Dict[str, str]]:
+ """
+ Get information about available benchmarks.
+
+ Returns:
+ List of dictionaries with benchmark information
+ """
+ return [
+ {
+ "id": "simpleqa",
+ "name": "SimpleQA",
+ "description": "Benchmark for factual question answering",
+ "recommended_examples": 100,
+ },
+ {
+ "id": "browsecomp",
+ "name": "BrowseComp",
+ "description": "Benchmark for web browsing comprehension",
+ "recommended_examples": 100,
+ },
+ ]
+
+
+def compare_configurations(
+ dataset_type: str = "simpleqa",
+ num_examples: int = 20,
+ configurations: List[Dict[str, Any]] = None,
+ output_dir: str = "benchmark_comparisons",
+) -> Dict[str, Any]:
+ """
+ Compare multiple search configurations on the same benchmark.
+
+ Args:
+ dataset_type: Type of dataset to use
+ num_examples: Number of examples to evaluate
+ configurations: List of search configurations to compare
+ output_dir: Directory to save results
+
+ Returns:
+ Dictionary with comparison results
+ """
+ if not configurations:
+ # Default configurations to compare
+ configurations = [
+ {
+ "name": "Base Config",
+ "search_tool": "searxng",
+ "iterations": 1,
+ "questions_per_iteration": 3,
+ },
+ {
+ "name": "More Iterations",
+ "search_tool": "searxng",
+ "iterations": 3,
+ "questions_per_iteration": 3,
+ },
+ {
+ "name": "More Questions",
+ "search_tool": "searxng",
+ "iterations": 1,
+ "questions_per_iteration": 5,
+ },
+ ]
+
+ # Create output directory
+ import os
+
+ os.makedirs(output_dir, exist_ok=True)
+
+ # Run benchmarks for each configuration
+ results = []
+ for config in configurations:
+ config_name = config.pop("name", f"Config-{len(results)}")
+
+ logger.info(f"Running benchmark with configuration: {config_name}")
+
+ search_config = {
+ "iterations": config.pop("iterations", 1),
+ "questions_per_iteration": config.pop("questions_per_iteration", 3),
+ "search_tool": config.pop("search_tool", "searxng"),
+ }
+
+ # Add any remaining config items
+ for key, value in config.items():
+ search_config[key] = value
+
+ # Run benchmark with this configuration
+ benchmark_result = run_benchmark(
+ dataset_type=dataset_type,
+ num_examples=num_examples,
+ output_dir=os.path.join(output_dir, config_name.replace(" ", "_")),
+ search_config=search_config,
+ run_evaluation=True,
+ )
+
+ # Add configuration name to results
+ benchmark_result["configuration_name"] = config_name
+ benchmark_result["search_config"] = search_config
+
+ results.append(benchmark_result)
+
+ # Generate comparison report
+ import time
+
+ timestamp = time.strftime("%Y%m%d_%H%M%S")
+ report_file = os.path.join(output_dir, f"comparison_{dataset_type}_{timestamp}.md")
+
+ with open(report_file, "w") as f:
+ f.write(f"# Configuration Comparison - {dataset_type.capitalize()}\n\n")
+
+ # Write summary table
+ f.write("## Summary\n\n")
+ f.write("| Configuration | Accuracy | Avg. Time | Examples |\n")
+ f.write("|---------------|----------|-----------|----------|\n")
+
+ for result in results:
+ accuracy = result.get("metrics", {}).get("accuracy", 0)
+ avg_time = result.get("metrics", {}).get("average_processing_time", 0)
+ examples = result.get("total_examples", 0)
+
+ f.write(
+ f"| {result['configuration_name']} | {accuracy:.3f} | {avg_time:.2f}s | {examples} |\n"
+ )
+
+ f.write("\n## Configuration Details\n\n")
+
+ for result in results:
+ f.write(f"### {result['configuration_name']}\n\n")
+
+ config = result.get("search_config", {})
+ f.write("```\n")
+ for key, value in config.items():
+ f.write(f"{key}: {value}\n")
+ f.write("```\n\n")
+
+ logger.info(f"Comparison report saved to {report_file}")
+
+ return {
+ "status": "complete",
+ "dataset_type": dataset_type,
+ "configurations_tested": len(configurations),
+ "report_path": report_file,
+ "results": results,
+ }
+
+
+# Export the API functions
+__all__ = [
+ "evaluate_simpleqa",
+ "evaluate_browsecomp",
+ "get_available_benchmarks",
+ "compare_configurations",
+ "run_benchmark", # For advanced users
+ "calculate_metrics",
+ "generate_report",
+]
diff --git a/src/local_deep_research/benchmarks/datasets.py b/src/local_deep_research/benchmarks/datasets.py
new file mode 100644
index 0000000000..3cd5358001
--- /dev/null
+++ b/src/local_deep_research/benchmarks/datasets.py
@@ -0,0 +1,116 @@
+"""
+Dataset handling for benchmarks.
+
+This module provides functions for loading and processing benchmark datasets.
+"""
+
+import base64
+import hashlib
+import logging
+import random
+from typing import Any, Dict, List, Optional
+
+import pandas as pd
+
+logger = logging.getLogger(__name__)
+
+# Default dataset URLs
+DEFAULT_DATASET_URLS = {
+ "simpleqa": "https://openaipublic.blob.core.windows.net/simple-evals/simple_qa_test_set.csv",
+ "browsecomp": "https://openaipublic.blob.core.windows.net/simple-evals/browse_comp_test_set.csv",
+}
+
+
+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 "Error: Could not decrypt data"
+
+
+def get_available_datasets() -> List[Dict[str, str]]:
+ """
+ Get list of available benchmark datasets.
+
+ Returns:
+ List of dictionaries with dataset information
+ """
+ return [
+ {
+ "id": "simpleqa",
+ "name": "SimpleQA",
+ "description": "Simple question-answering evaluation dataset",
+ "url": DEFAULT_DATASET_URLS["simpleqa"],
+ },
+ {
+ "id": "browsecomp",
+ "name": "BrowseComp",
+ "description": "Web browsing comprehension evaluation dataset",
+ "url": DEFAULT_DATASET_URLS["browsecomp"],
+ },
+ ]
+
+
+def load_dataset(
+ dataset_type: str,
+ dataset_path: Optional[str] = None,
+ num_examples: Optional[int] = None,
+ seed: int = 42,
+) -> List[Dict[str, Any]]:
+ """
+ Load and preprocess a dataset.
+
+ Args:
+ dataset_type: Type of dataset ('simpleqa' or 'browsecomp')
+ dataset_path: Path or URL to dataset (if None, uses default URL)
+ num_examples: Optional number of examples to sample
+ seed: Random seed for sampling
+
+ Returns:
+ List of processed examples
+ """
+ # Use default URL if path not provided
+ if not dataset_path:
+ if dataset_type.lower() not in DEFAULT_DATASET_URLS:
+ raise ValueError(f"Unknown dataset type: {dataset_type}")
+ dataset_path = DEFAULT_DATASET_URLS[dataset_type.lower()]
+
+ logger.info(f"Loading {dataset_type} dataset from {dataset_path}")
+
+ try:
+ # Load dataset using pandas
+ df = pd.read_csv(dataset_path)
+ examples = [row.to_dict() for _, row in df.iterrows()]
+
+ # Process BrowseComp dataset if needed
+ if dataset_type.lower() == "browsecomp":
+ # Note: BrowseComp normally needs decryption, but we're assuming
+ # we have the decrypted version or that decryption is handled elsewhere
+ pass
+
+ # Sample examples if specified
+ if num_examples and num_examples < len(examples):
+ random.seed(seed)
+ sampled_examples = random.sample(examples, num_examples)
+ logger.info(f"Sampled {num_examples} examples out of {len(examples)}")
+ return sampled_examples
+
+ logger.info(f"Loaded {len(examples)} examples")
+ return examples
+
+ except Exception as e:
+ logger.error(f"Error loading dataset: {e}")
+ raise
diff --git a/src/local_deep_research/benchmarks/graders.py b/src/local_deep_research/benchmarks/graders.py
new file mode 100644
index 0000000000..0bb4d011a6
--- /dev/null
+++ b/src/local_deep_research/benchmarks/graders.py
@@ -0,0 +1,410 @@
+"""
+Evaluation and grading functionality.
+
+This module provides tools for evaluating model outputs against reference answers.
+"""
+
+import json
+import logging
+import os
+import re
+from typing import Any, Callable, Dict, List, Optional
+
+from langchain.schema import HumanMessage
+
+from ..config.llm_config import get_llm
+from .templates import BROWSECOMP_GRADER_TEMPLATE, SIMPLEQA_GRADER_TEMPLATE
+
+logger = logging.getLogger(__name__)
+
+# Default evaluation configuration using Claude 3.7 Sonnet via OpenRouter
+DEFAULT_EVALUATION_CONFIG = {
+ "model_name": "anthropic/claude-3.7-sonnet", # Correct model ID for OpenRouter
+ "provider": "openai_endpoint", # Use OpenRouter
+ "openai_endpoint_url": "https://openrouter.ai/api/v1", # OpenRouter URL
+ "temperature": 0, # Zero temp for consistent evaluation
+ # Note: max_tokens removed as it's not supported by LDR's get_llm()
+}
+
+
+def get_evaluation_llm(custom_config: Optional[Dict[str, Any]] = None):
+ """
+ Get an LLM for evaluation purposes using Claude 3.7 Sonnet via OpenRouter
+ by default, which can be overridden with custom settings.
+
+ Args:
+ custom_config: Optional custom configuration that overrides defaults
+
+ Returns:
+ An LLM instance for evaluation
+ """
+ # Start with default config (Claude 3.7 Sonnet via OpenRouter)
+ config = DEFAULT_EVALUATION_CONFIG.copy()
+
+ # Override with any custom settings
+ if custom_config:
+ config.update(custom_config)
+
+ logger.info(
+ f"Getting evaluation LLM with provider={config['provider']}, model={config['model_name']}"
+ )
+
+ # Remove any parameters that LDR's get_llm doesn't support
+ # This ensures compatibility with LDR's implementation
+ ldr_supported_params = {
+ "model_name",
+ "temperature",
+ "provider",
+ "openai_endpoint_url",
+ "api_key",
+ }
+
+ filtered_config = {k: v for k, v in config.items() if k in ldr_supported_params}
+
+ # Check if we're using openai_endpoint but don't have an API key configured
+ if filtered_config.get("provider") == "openai_endpoint":
+ # Try to get API key from environment or config
+ import os
+
+ api_key = os.getenv("OPENAI_ENDPOINT_API_KEY")
+ if not api_key:
+ logger.warning(
+ "Using openai_endpoint provider but no API key found. "
+ "Set the OPENAI_ENDPOINT_API_KEY environment variable or "
+ "specify api_key in the evaluation_config."
+ )
+ # Try to fall back to LDR's config if API key not explicitly provided
+ # The get_llm function will handle this case
+
+ # Get the LLM using LDR's existing function
+ return get_llm(**filtered_config)
+
+
+def extract_answer_from_response(
+ response: str, dataset_type: str = "simpleqa"
+) -> Dict[str, str]:
+ """
+ Extract structured information from LDR's response.
+
+ Args:
+ response: Response from LDR
+ dataset_type: Type of dataset
+
+ Returns:
+ Dictionary with extracted answer and confidence
+ """
+ # Clean up citations
+ response = re.sub(r"\[\d+\]", "", response)
+
+ # Extract differently based on dataset type
+ if dataset_type.lower() == "browsecomp":
+ # Extract the final answer from structured 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
+ confidence_match = re.search(r"Confidence:\s*(\d+)%", response)
+ confidence = confidence_match.group(1) if confidence_match else "100"
+
+ return {"extracted_answer": exact_answer, "confidence": confidence}
+
+ # For SimpleQA, return the whole response as the answer
+ return {
+ "extracted_answer": response,
+ "confidence": "100", # SimpleQA doesn't have confidence scores
+ }
+
+
+def grade_results(
+ results_file: str,
+ output_file: str,
+ dataset_type: str = "simpleqa",
+ evaluation_config: Optional[Dict[str, Any]] = None,
+ progress_callback: Optional[Callable[[int, int, Dict], None]] = None,
+) -> List[Dict[str, Any]]:
+ """
+ Grade benchmark results using LLM.
+
+ Args:
+ results_file: Path to results file
+ output_file: Path to save graded results
+ dataset_type: Type of dataset
+ evaluation_config: Optional custom config for evaluation LLM
+ progress_callback: Optional callback for progress updates
+
+ Returns:
+ List of graded results
+ """
+ # Get evaluation LLM
+ evaluation_llm = get_evaluation_llm(evaluation_config)
+
+ # Select appropriate template
+ template = (
+ BROWSECOMP_GRADER_TEMPLATE
+ if dataset_type.lower() == "browsecomp"
+ else SIMPLEQA_GRADER_TEMPLATE
+ )
+
+ # Load results
+ results = []
+ with open(results_file, "r") as f:
+ for line in f:
+ if line.strip():
+ results.append(json.loads(line))
+
+ # Remove output file if it exists
+ if os.path.exists(output_file):
+ os.remove(output_file)
+
+ graded_results = []
+ correct_count = 0
+
+ # Process each result
+ for idx, result in enumerate(results):
+ question = result.get("problem", "")
+ correct_answer = result.get("correct_answer", "")
+ response = result.get("response", "")
+
+ # Call progress callback if provided
+ if progress_callback:
+ progress_callback(
+ idx,
+ len(results),
+ {"status": "grading", "index": idx, "total": len(results)},
+ )
+
+ logger.info(f"Grading {idx + 1}/{len(results)}: {question[:50]}...")
+
+ # Format grading prompt
+ grading_prompt = template.format(
+ question=question, correct_answer=correct_answer, response=response
+ )
+
+ try:
+ # Grade using LLM
+ if hasattr(evaluation_llm, "invoke") and callable(evaluation_llm.invoke):
+ if hasattr(evaluation_llm, "chat_messages"):
+ # Handle ChatOpenAI and similar models that use messages
+ grading_response = evaluation_llm.invoke(
+ [HumanMessage(content=grading_prompt)]
+ ).content
+ else:
+ # Handle other LLM types
+ grading_response = evaluation_llm.invoke(grading_prompt)
+ if hasattr(grading_response, "content"):
+ grading_response = grading_response.content
+ else:
+ # Fallback for other LLM interfaces
+ grading_response = str(evaluation_llm(grading_prompt))
+
+ # Extract grading information using regex
+ if dataset_type.lower() == "browsecomp":
+ # BrowseComp-specific extraction
+ extracted_answer_match = re.search(
+ r"extracted_final_answer:\s*(.*?)(?:\n|$)", grading_response
+ )
+ extracted_answer = (
+ extracted_answer_match.group(1).strip()
+ if extracted_answer_match
+ else "None"
+ )
+
+ reasoning_match = re.search(
+ r"reasoning:\s*(.*?)(?:\n\n|\ncorrect:|\Z)",
+ grading_response,
+ re.DOTALL,
+ )
+ reasoning = reasoning_match.group(1).strip() if reasoning_match else ""
+
+ correct_match = re.search(
+ r"correct:\s*(yes|no)", grading_response, re.IGNORECASE
+ )
+ is_correct = (
+ (correct_match.group(1).lower() == "yes")
+ if correct_match
+ else False
+ )
+
+ confidence_match = re.search(r"confidence:\s*(\d+)", grading_response)
+ confidence = confidence_match.group(1) if confidence_match else "100"
+ else:
+ # SimpleQA extraction
+ extracted_answer_match = re.search(
+ r"Extracted Answer:\s*(.*?)(?:\n|$)", grading_response
+ )
+ extracted_answer = (
+ extracted_answer_match.group(1).strip()
+ if extracted_answer_match
+ else "None"
+ )
+
+ reasoning_match = re.search(
+ r"Reasoning:\s*(.*?)(?:\nCorrect:|\Z)", grading_response, re.DOTALL
+ )
+ reasoning = reasoning_match.group(1).strip() if reasoning_match else ""
+
+ correct_match = re.search(
+ r"Correct:\s*(yes|no)", grading_response, re.IGNORECASE
+ )
+ is_correct = (
+ (correct_match.group(1).lower() == "yes")
+ if correct_match
+ else False
+ )
+
+ confidence = "100" # SimpleQA doesn't have confidence
+
+ if is_correct:
+ correct_count += 1
+
+ # Format graded result
+ graded_result = result.copy()
+ graded_result.update(
+ {
+ "extracted_by_grader": extracted_answer,
+ "reasoning": reasoning,
+ "is_correct": is_correct,
+ "graded_confidence": confidence,
+ "grader_response": grading_response,
+ }
+ )
+
+ graded_results.append(graded_result)
+
+ # Write to output file
+ with open(output_file, "a") as f:
+ f.write(json.dumps(graded_result) + "\n")
+
+ # Call progress callback if provided
+ if progress_callback:
+ progress_callback(
+ idx,
+ len(results),
+ {
+ "status": "graded",
+ "is_correct": is_correct,
+ "result": graded_result,
+ },
+ )
+
+ except Exception as e:
+ logger.error(f"Error grading result {idx + 1}: {str(e)}")
+
+ # Handle error
+ error_result = result.copy()
+ error_result["grading_error"] = str(e)
+
+ with open(output_file, "a") as f:
+ f.write(json.dumps(error_result) + "\n")
+
+ graded_results.append(error_result)
+
+ # Call progress callback if provided
+ if progress_callback:
+ progress_callback(
+ idx,
+ len(results),
+ {"status": "error", "error": str(e), "result": error_result},
+ )
+
+ accuracy = correct_count / len(results) if results else 0
+ logger.info(f"Grading complete. Accuracy: {accuracy:.3f}")
+ logger.info(f"Correct: {correct_count}/{len(results)}")
+
+ return graded_results
+
+
+def human_evaluation(
+ results_file: str, output_file: str, interactive: bool = True
+) -> List[Dict[str, Any]]:
+ """
+ Allow for human evaluation of results.
+
+ Args:
+ results_file: Path to results file
+ output_file: Path to save human-graded results
+ interactive: Whether to run in interactive console mode
+
+ Returns:
+ List of human-graded results
+ """
+ # Load results
+ results = []
+ with open(results_file, "r") as f:
+ for line in f:
+ if line.strip():
+ results.append(json.loads(line))
+
+ # Remove output file if it exists
+ if os.path.exists(output_file):
+ os.remove(output_file)
+
+ human_graded_results = []
+ correct_count = 0
+
+ if interactive:
+ logger.info(f"Human evaluation: {len(results)} examples to grade")
+ print(f"Human evaluation: {len(results)} examples to grade")
+ print(
+ "For each example, you'll see the question, correct answer, and model's response."
+ )
+ print("You'll be asked to judge if the model's answer is correct.")
+
+ for idx, result in enumerate(results):
+ question = result.get("problem", "")
+ correct_answer = result.get("correct_answer", "")
+ response = result.get("response", "")
+ extracted_answer = result.get("extracted_answer", "")
+
+ if interactive:
+ print(f"\n\n===== Example {idx + 1}/{len(results)} =====")
+ print(f"Question: {question}")
+ print(f"\nCorrect Answer: {correct_answer}")
+ print(f"\nModel Response: {response}")
+ print(f"\nExtracted Answer: {extracted_answer}")
+
+ # Get human judgment
+ while True:
+ judgment = (
+ input("\nIs the model's answer correct? (y/n): ").strip().lower()
+ )
+ if judgment in ["y", "n"]:
+ break
+ print("Please enter 'y' or 'n'")
+
+ is_correct = judgment == "y"
+
+ # Get reasoning
+ reasoning = input("Please provide reasoning for your judgment: ").strip()
+ else:
+ # Non-interactive mode - placeholder for API/UI implementation
+ # In a real implementation, this would be filled by UI actions
+ is_correct = False
+ reasoning = "Non-interactive evaluation"
+
+ if is_correct:
+ correct_count += 1
+
+ # Update result with human judgment
+ human_result = result.copy()
+ human_result.update(
+ {
+ "is_correct": is_correct,
+ "reasoning": reasoning,
+ "human_evaluation": True,
+ }
+ )
+
+ human_graded_results.append(human_result)
+
+ # Write to output file
+ with open(output_file, "a") as f:
+ f.write(json.dumps(human_result) + "\n")
+
+ accuracy = correct_count / len(results) if results else 0
+ logger.info(f"Human evaluation complete. Accuracy: {accuracy:.3f}")
+ if interactive:
+ print(f"\nHuman evaluation complete. Accuracy: {accuracy:.3f}")
+ print(f"Correct: {correct_count}/{len(results)}")
+
+ return human_graded_results
diff --git a/src/local_deep_research/benchmarks/metrics.py b/src/local_deep_research/benchmarks/metrics.py
new file mode 100644
index 0000000000..e21016353f
--- /dev/null
+++ b/src/local_deep_research/benchmarks/metrics.py
@@ -0,0 +1,247 @@
+"""
+Metrics calculation and report generation.
+
+This module provides tools for evaluating benchmark results and generating reports.
+"""
+
+import json
+import logging
+from datetime import datetime
+from typing import Any, Dict, Optional
+
+logger = logging.getLogger(__name__)
+
+
+def calculate_metrics(results_file: str) -> Dict[str, Any]:
+ """
+ Calculate evaluation metrics from results.
+
+ Args:
+ results_file: Path to results file
+
+ Returns:
+ Dictionary of metrics
+ """
+ # Load results
+ results = []
+ try:
+ with open(results_file, "r") as f:
+ for line in f:
+ if line.strip():
+ results.append(json.loads(line))
+ except Exception as e:
+ logger.error(f"Error loading results file: {e}")
+ return {"error": str(e)}
+
+ if not results:
+ return {"error": "No results found"}
+
+ # Calculate accuracy
+ graded_results = [r for r in results if "is_correct" in r]
+ correct_count = sum(1 for r in graded_results if r.get("is_correct", False))
+ total_graded = len(graded_results)
+ accuracy = correct_count / total_graded if total_graded else 0
+
+ # Calculate average processing time if available
+ processing_times = [
+ r.get("processing_time", 0) for r in results if "processing_time" in r
+ ]
+ avg_time = sum(processing_times) / len(processing_times) if processing_times else 0
+
+ # Average confidence if available
+ confidence_values = []
+ for r in results:
+ if "confidence" in r and r["confidence"]:
+ try:
+ confidence_values.append(int(r["confidence"]))
+ except (ValueError, TypeError):
+ pass
+
+ avg_confidence = (
+ sum(confidence_values) / len(confidence_values) if confidence_values else 0
+ )
+
+ # Calculate error rate
+ error_count = sum(1 for r in results if "error" in r)
+ error_rate = error_count / len(results) if results else 0
+
+ # Basic metrics
+ metrics = {
+ "total_examples": len(results),
+ "graded_examples": total_graded,
+ "correct": correct_count,
+ "accuracy": accuracy,
+ "average_processing_time": avg_time,
+ "average_confidence": avg_confidence,
+ "error_count": error_count,
+ "error_rate": error_rate,
+ "timestamp": datetime.now().isoformat(),
+ }
+
+ # If we have category information, calculate per-category metrics
+ categories = {}
+ for r in graded_results:
+ if "category" in r:
+ category = r["category"]
+ if category not in categories:
+ categories[category] = {"total": 0, "correct": 0}
+ categories[category]["total"] += 1
+ if r.get("is_correct", False):
+ categories[category]["correct"] += 1
+
+ if categories:
+ category_metrics = {}
+ for category, counts in categories.items():
+ category_metrics[category] = {
+ "total": counts["total"],
+ "correct": counts["correct"],
+ "accuracy": (
+ counts["correct"] / counts["total"] if counts["total"] else 0
+ ),
+ }
+ metrics["categories"] = category_metrics
+
+ return metrics
+
+
+def generate_report(
+ metrics: Dict[str, Any],
+ results_file: str,
+ output_file: str = "evaluation_report.md",
+ dataset_name: str = "Unknown",
+ config_info: Optional[Dict[str, Any]] = None,
+) -> str:
+ """
+ Generate a detailed report from evaluation results.
+
+ Args:
+ metrics: Dictionary of evaluation metrics
+ results_file: Path to results file
+ output_file: Path to save report
+ dataset_name: Name of dataset
+ config_info: Optional configuration information
+
+ Returns:
+ Path to the generated report file
+ """
+ # Load a sample of results for examples
+ results = []
+ try:
+ with open(results_file, "r") as f:
+ for line in f:
+ if line.strip():
+ results.append(json.loads(line))
+ except Exception as e:
+ logger.error(f"Error loading results for report: {e}")
+ results = []
+
+ # Sample up to 5 correct and 5 incorrect examples
+ correct_examples = [r for r in results if r.get("is_correct", False)][:5]
+ incorrect_examples = [
+ r for r in results if "is_correct" in r and not r.get("is_correct", False)
+ ][:5]
+
+ # Create report
+ report = [
+ f"# Evaluation Report: {dataset_name}",
+ "",
+ "## Summary",
+ "",
+ f"- **Total Examples**: {metrics.get('total_examples', 0)}",
+ f"- **Graded Examples**: {metrics.get('graded_examples', 0)}",
+ f"- **Correct Answers**: {metrics.get('correct', 0)}",
+ f"- **Accuracy**: {metrics.get('accuracy', 0):.3f}",
+ ]
+
+ if "average_processing_time" in metrics:
+ report.append(
+ f"- **Average Processing Time**: {metrics['average_processing_time']:.2f} seconds"
+ )
+
+ if "average_confidence" in metrics:
+ report.append(f"- **Average Confidence**: {metrics['average_confidence']:.2f}%")
+
+ if "error_count" in metrics and metrics["error_count"] > 0:
+ report.append(f"- **Error Count**: {metrics['error_count']}")
+ report.append(f"- **Error Rate**: {metrics['error_rate']:.3f}")
+
+ report.append("")
+
+ # Add per-category metrics if available
+ if "categories" in metrics:
+ report.extend(["## Category Performance", ""])
+
+ for category, category_metrics in metrics["categories"].items():
+ report.append(f"### {category}")
+ report.append("")
+ report.append(f"- **Total**: {category_metrics['total']}")
+ report.append(f"- **Correct**: {category_metrics['correct']}")
+ report.append(f"- **Accuracy**: {category_metrics['accuracy']:.3f}")
+ report.append("")
+
+ # Add configuration info if provided
+ if config_info:
+ report.extend(["## Configuration", ""])
+
+ for key, value in config_info.items():
+ report.append(f"- **{key}**: {value}")
+
+ report.append("")
+
+ # Add example sections
+ if correct_examples:
+ report.extend(["## Example Correct Answers", ""])
+
+ for idx, example in enumerate(correct_examples):
+ report.extend(
+ [
+ f"### Example {idx + 1}",
+ "",
+ f"**Question**: {example.get('problem', '')}",
+ "",
+ f"**Correct Answer**: {example.get('correct_answer', '')}",
+ "",
+ f"**Model Answer**: {example.get('extracted_answer', '')}",
+ "",
+ f"**Reasoning**: {example.get('reasoning', '')}",
+ "",
+ ]
+ )
+
+ if incorrect_examples:
+ report.extend(["## Example Incorrect Answers", ""])
+
+ for idx, example in enumerate(incorrect_examples):
+ report.extend(
+ [
+ f"### Example {idx + 1}",
+ "",
+ f"**Question**: {example.get('problem', '')}",
+ "",
+ f"**Correct Answer**: {example.get('correct_answer', '')}",
+ "",
+ f"**Model Answer**: {example.get('extracted_answer', '')}",
+ "",
+ f"**Reasoning**: {example.get('reasoning', '')}",
+ "",
+ ]
+ )
+
+ # Add timestamp
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+ report.extend(
+ [
+ "## Metadata",
+ "",
+ f"- **Generated**: {timestamp}",
+ f"- **Dataset**: {dataset_name}",
+ "",
+ ]
+ )
+
+ # Write report to file
+ with open(output_file, "w") as f:
+ f.write("\n".join(report))
+
+ logger.info(f"Report saved to {output_file}")
+ return output_file
diff --git a/src/local_deep_research/benchmarks/optimization/__init__.py b/src/local_deep_research/benchmarks/optimization/__init__.py
new file mode 100644
index 0000000000..d60d2de762
--- /dev/null
+++ b/src/local_deep_research/benchmarks/optimization/__init__.py
@@ -0,0 +1,24 @@
+"""
+Optimization submodule for parameter tuning in Local Deep Research.
+
+This module provides tools for finding optimal parameter configurations
+for the research system using Optuna and other optimization methods.
+"""
+
+from local_deep_research.benchmarking.optimization.api import optimize_parameters
+from local_deep_research.benchmarking.optimization.metrics import (
+ calculate_combined_score,
+ calculate_quality_metrics,
+ calculate_speed_metrics,
+)
+from local_deep_research.benchmarking.optimization.optuna_optimizer import (
+ OptunaOptimizer,
+)
+
+__all__ = [
+ "OptunaOptimizer",
+ "optimize_parameters",
+ "calculate_quality_metrics",
+ "calculate_speed_metrics",
+ "calculate_combined_score",
+]
diff --git a/src/local_deep_research/benchmarks/optimization/optimization.py b/src/local_deep_research/benchmarks/optimization/optimization.py
new file mode 100644
index 0000000000..8e721797ee
--- /dev/null
+++ b/src/local_deep_research/benchmarks/optimization/optimization.py
@@ -0,0 +1,208 @@
+"""
+API functions for parameter optimization in Local Deep Research.
+
+This module provides simplified interfaces for running parameter
+optimization tasks without directly working with the optimizer classes.
+"""
+
+import logging
+from typing import Any, Dict, List, Optional, Tuple
+
+from local_deep_research.benchmarking.optimization.optuna_optimizer import (
+ OptunaOptimizer,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def optimize_parameters(
+ query: str,
+ param_space: Optional[Dict[str, Any]] = None,
+ output_dir: str = "optimization_results",
+ model_name: Optional[str] = None,
+ provider: Optional[str] = None,
+ search_tool: Optional[str] = None,
+ temperature: float = 0.7,
+ n_trials: int = 30,
+ timeout: Optional[int] = None,
+ n_jobs: int = 1,
+ study_name: Optional[str] = None,
+ optimization_metrics: Optional[List[str]] = None,
+ metric_weights: Optional[Dict[str, float]] = None,
+) -> Tuple[Dict[str, Any], float]:
+ """
+ Optimize parameters for Local Deep Research.
+
+ Args:
+ query: The research query to use for all experiments
+ param_space: Dictionary defining parameter search spaces (optional)
+ 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
+ temperature: LLM temperature
+ n_trials: Number of parameter combinations to try
+ timeout: Maximum seconds to run optimization (None for no limit)
+ 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 (default: {"quality": 0.6, "speed": 0.4})
+
+ Returns:
+ Tuple of (best_parameters, best_score)
+ """
+ # Default metrics and weights if not provided
+ if optimization_metrics is None:
+ optimization_metrics = ["quality", "speed"]
+
+ if metric_weights is None:
+ metric_weights = {"quality": 0.6, "speed": 0.4}
+
+ # Create optimizer
+ optimizer = OptunaOptimizer(
+ base_query=query,
+ output_dir=output_dir,
+ model_name=model_name,
+ provider=provider,
+ search_tool=search_tool,
+ temperature=temperature,
+ n_trials=n_trials,
+ timeout=timeout,
+ n_jobs=n_jobs,
+ study_name=study_name,
+ optimization_metrics=optimization_metrics,
+ metric_weights=metric_weights,
+ )
+
+ # Run optimization
+ return optimizer.optimize(param_space)
+
+
+def get_default_param_space() -> Dict[str, Any]:
+ """
+ Get the default parameter space for optimization.
+
+ Returns:
+ Dictionary defining the default parameter search spaces
+ """
+ return {
+ "iterations": {
+ "type": "int",
+ "low": 1,
+ "high": 5,
+ "step": 1,
+ },
+ "questions_per_iteration": {
+ "type": "int",
+ "low": 1,
+ "high": 5,
+ "step": 1,
+ },
+ "search_strategy": {
+ "type": "categorical",
+ "choices": ["iterdrag", "standard", "rapid", "parallel", "source_based"],
+ },
+ "max_results": {
+ "type": "int",
+ "low": 10,
+ "high": 100,
+ "step": 10,
+ },
+ "max_filtered_results": {
+ "type": "int",
+ "low": 5,
+ "high": 50,
+ "step": 5,
+ },
+ }
+
+
+def optimize_for_speed(
+ query: str,
+ output_dir: str = "optimization_results",
+ model_name: Optional[str] = None,
+ provider: Optional[str] = None,
+ search_tool: Optional[str] = None,
+ n_trials: int = 20,
+) -> Tuple[Dict[str, Any], float]:
+ """
+ Quick function to optimize primarily for speed.
+
+ Args:
+ query: The research query to use for all experiments
+ 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
+ n_trials: Number of parameter combinations to try
+
+ Returns:
+ Tuple of (best_parameters, best_score)
+ """
+ # Focus on speed with reduced search space
+ 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": ["rapid", "parallel", "source_based"],
+ },
+ }
+
+ # Use speed-focused metrics and weights
+ return optimize_parameters(
+ query=query,
+ param_space=param_space,
+ output_dir=output_dir,
+ model_name=model_name,
+ provider=provider,
+ search_tool=search_tool,
+ n_trials=n_trials,
+ optimization_metrics=["speed", "quality"],
+ metric_weights={"speed": 0.8, "quality": 0.2},
+ )
+
+
+def optimize_for_quality(
+ query: str,
+ output_dir: str = "optimization_results",
+ model_name: Optional[str] = None,
+ provider: Optional[str] = None,
+ search_tool: Optional[str] = None,
+ n_trials: int = 30,
+) -> Tuple[Dict[str, Any], float]:
+ """
+ Function to optimize primarily for result quality.
+
+ Args:
+ query: The research query to use for all experiments
+ 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
+ n_trials: Number of parameter combinations to try
+
+ Returns:
+ Tuple of (best_parameters, best_score)
+ """
+ # Use quality-focused metrics and weights
+ return optimize_parameters(
+ query=query,
+ output_dir=output_dir,
+ model_name=model_name,
+ provider=provider,
+ search_tool=search_tool,
+ n_trials=n_trials,
+ optimization_metrics=["quality", "speed"],
+ metric_weights={"quality": 0.9, "speed": 0.1},
+ )
diff --git a/src/local_deep_research/benchmarks/runners.py b/src/local_deep_research/benchmarks/runners.py
new file mode 100644
index 0000000000..4390b62278
--- /dev/null
+++ b/src/local_deep_research/benchmarks/runners.py
@@ -0,0 +1,411 @@
+"""
+Benchmark runners for Local Deep Research.
+
+This module provides the main functions for running benchmarks using LDR.
+"""
+
+import json
+import logging
+import os
+import time
+from typing import Any, Callable, Dict, Optional
+
+from ..api import quick_summary
+from .datasets import DEFAULT_DATASET_URLS, load_dataset
+from .graders import extract_answer_from_response, grade_results
+from .metrics import calculate_metrics, generate_report
+from .templates import BROWSECOMP_QUERY_TEMPLATE
+
+logger = logging.getLogger(__name__)
+
+
+def format_query(question: str, dataset_type: str = "simpleqa") -> str:
+ """
+ Format query based on dataset type.
+
+ Args:
+ question: Original question
+ dataset_type: Type of dataset
+
+ Returns:
+ Formatted query for LDR
+ """
+ if dataset_type.lower() == "browsecomp":
+ # BrowseComp requires specific formatting
+ return BROWSECOMP_QUERY_TEMPLATE.format(question=question)
+
+ # Simple format for SimpleQA
+ return question
+
+
+def run_benchmark(
+ dataset_type: str,
+ dataset_path: Optional[str] = None,
+ num_examples: Optional[int] = None,
+ output_dir: str = "benchmark_results",
+ run_evaluation: bool = True,
+ evaluation_config: Optional[Dict[str, Any]] = None,
+ search_config: Optional[Dict[str, Any]] = None,
+ human_evaluation: bool = False,
+ progress_callback: Optional[Callable[[str, int, Dict], None]] = None,
+ seed: int = 42,
+) -> Dict[str, Any]:
+ """
+ Run a benchmark on the specified dataset.
+
+ Args:
+ dataset_type: Type of dataset ("simpleqa" or "browsecomp")
+ dataset_path: Optional custom dataset path
+ num_examples: Number of examples to use
+ output_dir: Directory to save results
+ run_evaluation: Whether to evaluate results
+ evaluation_config: Custom LLM config for evaluation
+ search_config: Custom search parameters
+ human_evaluation: Whether to use human evaluation
+ progress_callback: Optional callback for progress updates
+ seed: Random seed for reproducibility
+
+ Returns:
+ Dictionary with benchmark results and metrics
+ """
+ # Ensure output directory exists
+ os.makedirs(output_dir, exist_ok=True)
+
+ # Default search configuration
+ if not search_config:
+ search_config = {
+ "iterations": 3,
+ "questions_per_iteration": 3,
+ "search_tool": "searxng",
+ }
+
+ # Load dataset
+ dataset = load_dataset(
+ dataset_type=dataset_type,
+ dataset_path=dataset_path,
+ num_examples=num_examples,
+ seed=seed,
+ )
+
+ # Set up output files
+ timestamp = time.strftime("%Y%m%d_%H%M%S")
+ results_file = os.path.join(output_dir, f"{dataset_type}_{timestamp}_results.jsonl")
+ evaluation_file = os.path.join(
+ output_dir, f"{dataset_type}_{timestamp}_evaluation.jsonl"
+ )
+ report_file = os.path.join(output_dir, f"{dataset_type}_{timestamp}_report.md")
+
+ # Make sure output files don't exist
+ for file in [results_file, evaluation_file, report_file]:
+ if os.path.exists(file):
+ os.remove(file)
+
+ # Progress tracking
+ total_examples = len(dataset)
+
+ if progress_callback:
+ progress_callback(
+ "Starting benchmark",
+ 0,
+ {
+ "status": "started",
+ "dataset_type": dataset_type,
+ "total_examples": total_examples,
+ },
+ )
+
+ # Process each example
+ results = []
+
+ for i, example in enumerate(dataset):
+ # Extract question and answer based on dataset type
+ if dataset_type.lower() == "simpleqa":
+ question = example.get("problem", "")
+ correct_answer = example.get("answer", "")
+ else: # browsecomp
+ question = example.get("problem", "")
+ # For BrowseComp, the answer should be in "correct_answer" after decryption
+ correct_answer = example.get("correct_answer", "")
+ if not correct_answer and "answer" in example:
+ # Fallback to "answer" field if "correct_answer" is not available
+ correct_answer = example.get("answer", "")
+
+ # Update progress
+ if progress_callback:
+ progress_callback(
+ f"Processing example {i + 1}/{total_examples}",
+ int(i / total_examples * 50),
+ {
+ "status": "processing",
+ "current": i + 1,
+ "total": total_examples,
+ "question": (
+ question[:50] + "..." if len(question) > 50 else question
+ ),
+ },
+ )
+
+ logger.info(f"Processing {i + 1}/{total_examples}: {question[:50]}...")
+
+ try:
+ # Format query based on dataset type
+ formatted_query = format_query(question, dataset_type)
+
+ # Time the search
+ start_time = time.time()
+
+ # Get response from LDR
+ search_result = quick_summary(
+ query=formatted_query,
+ iterations=search_config.get("iterations", 3),
+ questions_per_iteration=search_config.get("questions_per_iteration", 3),
+ search_tool=search_config.get("search_tool", "searxng"),
+ )
+
+ end_time = time.time()
+ processing_time = end_time - start_time
+
+ # Extract response and search info
+ response = search_result.get("summary", "")
+
+ # Extract structured information
+ extracted = extract_answer_from_response(response, dataset_type)
+
+ # Format result
+ result = {
+ "id": example.get("id", f"example_{i}"),
+ "problem": question,
+ "correct_answer": correct_answer,
+ "response": response,
+ "extracted_answer": extracted["extracted_answer"],
+ "confidence": extracted["confidence"],
+ "processing_time": processing_time,
+ "sources": search_result.get("sources", []),
+ "search_config": search_config,
+ }
+
+ # Add to results list
+ results.append(result)
+
+ # Write result to file
+ with open(results_file, "a") as f:
+ f.write(json.dumps(result) + "\n")
+
+ # Update progress
+ if progress_callback:
+ progress_callback(
+ f"Completed example {i + 1}/{total_examples}",
+ int((i + 0.5) / total_examples * 50),
+ {
+ "status": "completed_example",
+ "current": i + 1,
+ "total": total_examples,
+ "result": result,
+ },
+ )
+
+ 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": question,
+ "correct_answer": correct_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")
+
+ # Update progress
+ if progress_callback:
+ progress_callback(
+ f"Error processing example {i + 1}/{total_examples}",
+ int((i + 0.5) / total_examples * 50),
+ {
+ "status": "error",
+ "current": i + 1,
+ "total": total_examples,
+ "error": str(e),
+ "result": error_result,
+ },
+ )
+
+ logger.info(f"Completed processing {total_examples} examples")
+
+ # Run evaluation if requested
+ if run_evaluation:
+ if progress_callback:
+ progress_callback(
+ "Starting evaluation",
+ 50,
+ {"status": "evaluating", "results_file": results_file},
+ )
+
+ if human_evaluation:
+ from .graders import human_evaluation as evaluate
+
+ logger.info("Running human evaluation...")
+ evaluation_results = evaluate(
+ results_file=results_file, output_file=evaluation_file, interactive=True
+ )
+ else:
+ logger.info("Running automated evaluation...")
+ try:
+ evaluation_results = grade_results(
+ results_file=results_file,
+ output_file=evaluation_file,
+ dataset_type=dataset_type,
+ evaluation_config=evaluation_config,
+ progress_callback=lambda current, total, meta: (
+ progress_callback(
+ f"Evaluating {current + 1}/{total}",
+ 50 + int((current + 0.5) / total * 40),
+ {**meta, "status": "evaluating"},
+ )
+ if progress_callback
+ else None
+ ),
+ )
+ except Exception as e:
+ logger.error(f"Automated evaluation failed: {str(e)}")
+
+ if progress_callback:
+ progress_callback(
+ "Automated evaluation failed. Falling back to human evaluation.",
+ 60,
+ {"status": "evaluation_fallback", "error": str(e)},
+ )
+
+ # Ask if user wants to fall back to human evaluation
+ fallback_to_human = False
+ print("\nAutomated evaluation failed with error:", str(e))
+ response = input(
+ "Do you want to fall back to human evaluation? (y/n): "
+ )
+ fallback_to_human = response.strip().lower() == "y"
+
+ if fallback_to_human:
+ logger.info("Falling back to human evaluation...")
+ from .graders import human_evaluation as evaluate
+
+ evaluation_results = evaluate(
+ results_file=results_file,
+ output_file=evaluation_file,
+ interactive=True,
+ )
+ else:
+ logger.info("Skipping evaluation due to error.")
+ # Create an empty evaluation file to prevent issues
+ with open(evaluation_file, "w") as f:
+ f.write("")
+
+ return {
+ "status": "evaluation_error",
+ "dataset_type": dataset_type,
+ "results_path": results_file,
+ "evaluation_error": str(e),
+ "total_examples": total_examples,
+ }
+
+ # Calculate metrics
+ if progress_callback:
+ progress_callback(
+ "Calculating metrics", 90, {"status": "calculating_metrics"}
+ )
+
+ metrics = calculate_metrics(evaluation_file)
+
+ # Generate report
+ if progress_callback:
+ progress_callback("Generating report", 95, {"status": "generating_report"})
+
+ dataset_name = dataset_type.capitalize()
+ report_path = generate_report(
+ metrics=metrics,
+ results_file=evaluation_file,
+ output_file=report_file,
+ dataset_name=dataset_name,
+ config_info={
+ "Dataset": dataset_path
+ or DEFAULT_DATASET_URLS.get(dataset_type, "Unknown"),
+ "Examples": total_examples,
+ "Iterations": search_config.get("iterations", 3),
+ "Questions per iteration": search_config.get(
+ "questions_per_iteration", 3
+ ),
+ "Search tool": search_config.get("search_tool", "searxng"),
+ "Evaluation method": "Human" if human_evaluation else "Automated",
+ },
+ )
+
+ # Mark as complete
+ if progress_callback:
+ progress_callback(
+ "Benchmark complete",
+ 100,
+ {"status": "complete", "metrics": metrics, "report_path": report_path},
+ )
+
+ return {
+ "status": "complete",
+ "dataset_type": dataset_type,
+ "results_path": results_file,
+ "evaluation_path": evaluation_file,
+ "report_path": report_path,
+ "metrics": metrics,
+ "total_examples": total_examples,
+ "accuracy": metrics.get("accuracy", 0),
+ }
+
+ else:
+ # No evaluation, just return results
+ if progress_callback:
+ progress_callback(
+ "Benchmark complete (no evaluation)",
+ 100,
+ {"status": "complete_no_eval", "results_path": results_file},
+ )
+
+ return {
+ "status": "complete_no_eval",
+ "dataset_type": dataset_type,
+ "results_path": results_file,
+ "total_examples": total_examples,
+ }
+
+
+def run_simpleqa_benchmark(num_examples: int = 100, **kwargs) -> Dict[str, Any]:
+ """
+ Run SimpleQA benchmark with default settings.
+
+ Args:
+ num_examples: Number of examples to process
+ **kwargs: Additional arguments to pass to run_benchmark
+
+ Returns:
+ Dictionary with benchmark results
+ """
+ return run_benchmark(dataset_type="simpleqa", num_examples=num_examples, **kwargs)
+
+
+def run_browsecomp_benchmark(num_examples: int = 100, **kwargs) -> Dict[str, Any]:
+ """
+ Run BrowseComp benchmark with default settings.
+
+ Args:
+ num_examples: Number of examples to process
+ **kwargs: Additional arguments to pass to run_benchmark
+
+ Returns:
+ Dictionary with benchmark results
+ """
+ return run_benchmark(dataset_type="browsecomp", num_examples=num_examples, **kwargs)
diff --git a/src/local_deep_research/benchmarks/templates.py b/src/local_deep_research/benchmarks/templates.py
new file mode 100644
index 0000000000..b38edb3398
--- /dev/null
+++ b/src/local_deep_research/benchmarks/templates.py
@@ -0,0 +1,65 @@
+"""
+Templates for benchmark evaluation.
+
+This module contains prompt templates used for evaluating model outputs
+against reference answers.
+"""
+
+# Template for SimpleQA grading
+SIMPLEQA_GRADER_TEMPLATE = """
+You are evaluating a question-answering system. Given a question, the correct answer,
+and the model's response, determine if the model's answer is correct.
+
+Question: {question}
+
+Correct Answer: {correct_answer}
+
+Model Response: {response}
+
+First, extract the model's final answer, ignoring explanations or reasoning.
+Then determine if the model's answer is correct by comparing it to the correct answer.
+Allow for minor variations in wording but be strict about factual accuracy.
+
+Provide your evaluation in this format:
+Extracted Answer: [The model's final answer, extracted from the full response]
+Reasoning: [Your explanation for why the answer is correct or incorrect]
+Correct: [yes/no]
+"""
+
+# Template for BrowseComp grading
+BROWSECOMP_GRADER_TEMPLATE = """
+Judge whether the following [response] to [question] is correct or not based on
+the precise and unambiguous [correct_answer] below.
+
+[question]: {question}
+
+[response]: {response}
+
+Your judgement must be in the format and criteria specified below:
+
+extracted_final_answer: The final exact answer extracted from the [response].
+Put the extracted answer as 'None' if there is no exact, final answer to extract
+from the response.
+
+[correct_answer]: {correct_answer}
+
+reasoning: Explain why the extracted_final_answer is correct or incorrect based
+on [correct_answer], focusing only on if there are meaningful differences between
+[correct_answer] and the extracted_final_answer.
+
+correct: Answer 'yes' if extracted_final_answer matches the [correct_answer] given
+above, or is within a small margin of error for numerical problems. Answer 'no' otherwise.
+
+confidence: The extracted confidence score between 0% and 100% from [response].
+Put 100 if there is no confidence score available.
+"""
+
+# Template for formatted BrowseComp queries
+BROWSECOMP_QUERY_TEMPLATE = """
+{question}
+
+Your response should be in the following format:
+Explanation: {{your explanation for your final answer}}
+Exact Answer: {{your succinct, final answer}}
+Confidence: {{your confidence score between 0% and 100% for your answer}}
+"""
diff --git a/src/local_deep_research/cli/benchmark_commands.py b/src/local_deep_research/cli/benchmark_commands.py
new file mode 100644
index 0000000000..7a4ef5e778
--- /dev/null
+++ b/src/local_deep_research/cli/benchmark_commands.py
@@ -0,0 +1,302 @@
+"""
+Command-line interface for benchmarking.
+
+This module provides CLI commands for running benchmarks.
+"""
+
+import argparse
+import logging
+
+from ..benchmarks import (
+ get_available_datasets,
+ run_browsecomp_benchmark,
+ run_simpleqa_benchmark,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def setup_benchmark_parser(subparsers):
+ """
+ Set up the benchmark CLI commands.
+
+ Args:
+ subparsers: argparse subparsers object to add commands to
+ """
+ # Common benchmark arguments
+ benchmark_parent = argparse.ArgumentParser(add_help=False)
+ benchmark_parent.add_argument(
+ "--examples",
+ type=int,
+ default=100,
+ help="Number of examples to run (default: 100)",
+ )
+ benchmark_parent.add_argument(
+ "--iterations",
+ type=int,
+ default=3,
+ help="Number of search iterations (default: 3)",
+ )
+ benchmark_parent.add_argument(
+ "--questions", type=int, default=3, help="Questions per iteration (default: 3)"
+ )
+ benchmark_parent.add_argument(
+ "--search-tool",
+ type=str,
+ default="searxng",
+ help="Search tool to use (default: searxng)",
+ )
+ benchmark_parent.add_argument(
+ "--output-dir",
+ type=str,
+ default="benchmark_results",
+ help="Directory to save results (default: benchmark_results)",
+ )
+ benchmark_parent.add_argument(
+ "--human-eval",
+ action="store_true",
+ help="Use human evaluation instead of automated",
+ )
+ benchmark_parent.add_argument(
+ "--eval-model", type=str, help="Model to use for evaluation"
+ )
+ benchmark_parent.add_argument(
+ "--eval-provider", type=str, help="Provider to use for evaluation"
+ )
+ benchmark_parent.add_argument(
+ "--custom-dataset", type=str, help="Path to custom dataset"
+ )
+ benchmark_parent.add_argument(
+ "--no-eval", action="store_true", help="Skip evaluation phase"
+ )
+
+ # SimpleQA benchmark command
+ simpleqa_parser = subparsers.add_parser(
+ "simpleqa", parents=[benchmark_parent], help="Run SimpleQA benchmark"
+ )
+ simpleqa_parser.set_defaults(func=run_simpleqa_cli)
+
+ # BrowseComp benchmark command
+ browsecomp_parser = subparsers.add_parser(
+ "browsecomp", parents=[benchmark_parent], help="Run BrowseComp benchmark"
+ )
+ browsecomp_parser.set_defaults(func=run_browsecomp_cli)
+
+ # List available benchmarks command
+ list_parser = subparsers.add_parser("list", help="List available benchmarks")
+ list_parser.set_defaults(func=list_benchmarks_cli)
+
+ # Compare configurations command
+ compare_parser = subparsers.add_parser(
+ "compare", help="Compare multiple search configurations"
+ )
+ compare_parser.add_argument(
+ "--dataset",
+ type=str,
+ default="simpleqa",
+ choices=["simpleqa", "browsecomp"],
+ help="Dataset to use for comparison",
+ )
+ compare_parser.add_argument(
+ "--examples",
+ type=int,
+ default=20,
+ help="Number of examples for each configuration (default: 20)",
+ )
+ compare_parser.add_argument(
+ "--output-dir",
+ type=str,
+ default="benchmark_comparisons",
+ help="Directory to save comparison results",
+ )
+ compare_parser.set_defaults(func=compare_configs_cli)
+
+
+def run_simpleqa_cli(args):
+ """
+ CLI handler for SimpleQA benchmark.
+
+ Args:
+ args: Parsed command-line arguments
+ """
+ # Set up search configuration
+ search_config = {
+ "iterations": args.iterations,
+ "questions_per_iteration": args.questions,
+ "search_tool": args.search_tool,
+ }
+
+ # Set up evaluation configuration if needed
+ evaluation_config = None
+ if args.eval_model or args.eval_provider:
+ evaluation_config = {}
+ if args.eval_model:
+ evaluation_config["model_name"] = args.eval_model
+ if args.eval_provider:
+ evaluation_config["provider"] = args.eval_provider
+
+ # Run the benchmark
+ result = run_simpleqa_benchmark(
+ num_examples=args.examples,
+ dataset_path=args.custom_dataset,
+ output_dir=args.output_dir,
+ search_config=search_config,
+ evaluation_config=evaluation_config,
+ human_evaluation=args.human_eval,
+ run_evaluation=not args.no_eval,
+ )
+
+ # Print results summary
+ if "metrics" in result:
+ print("\nSimpleQA Benchmark Results:")
+ print(f" Accuracy: {result['metrics'].get('accuracy', 0):.3f}")
+ print(f" Total examples: {result['total_examples']}")
+ print(f" Correct answers: {result['metrics'].get('correct', 0)}")
+ print(
+ f" Average time: {result['metrics'].get('average_processing_time', 0):.2f}s"
+ )
+ print(f"\nReport saved to: {result.get('report_path', 'N/A')}")
+ else:
+ print("\nSimpleQA Benchmark Completed (no evaluation)")
+ print(" Total examples: {result['total_examples']}")
+ print(f" Results saved to: {result.get('results_path', 'N/A')}")
+
+
+def run_browsecomp_cli(args):
+ """
+ CLI handler for BrowseComp benchmark.
+
+ Args:
+ args: Parsed command-line arguments
+ """
+ # Set up search configuration
+ search_config = {
+ "iterations": args.iterations,
+ "questions_per_iteration": args.questions,
+ "search_tool": args.search_tool,
+ }
+
+ # Set up evaluation configuration if needed
+ evaluation_config = None
+ if args.eval_model or args.eval_provider:
+ evaluation_config = {}
+ if args.eval_model:
+ evaluation_config["model_name"] = args.eval_model
+ if args.eval_provider:
+ evaluation_config["provider"] = args.eval_provider
+
+ # Run the benchmark
+ result = run_browsecomp_benchmark(
+ num_examples=args.examples,
+ dataset_path=args.custom_dataset,
+ output_dir=args.output_dir,
+ search_config=search_config,
+ evaluation_config=evaluation_config,
+ human_evaluation=args.human_eval,
+ run_evaluation=not args.no_eval,
+ )
+
+ # Print results summary
+ if "metrics" in result:
+ print("\nBrowseComp Benchmark Results:")
+ print(f" Accuracy: {result['metrics'].get('accuracy', 0):.3f}")
+ print(f" Total examples: {result['total_examples']}")
+ print(f" Correct answers: {result['metrics'].get('correct', 0)}")
+ print(
+ f" Average time: {result['metrics'].get('average_processing_time', 0):.2f}s"
+ )
+ print(f"\nReport saved to: {result.get('report_path', 'N/A')}")
+ else:
+ print("\nBrowseComp Benchmark Completed (no evaluation)")
+ print(f" Total examples: {result['total_examples']}")
+ print(f" Results saved to: {result.get('results_path', 'N/A')}")
+
+
+def list_benchmarks_cli(args):
+ """
+ CLI handler for listing available benchmarks.
+
+ Args:
+ args: Parsed command-line arguments
+ """
+ datasets = get_available_datasets()
+
+ print("\nAvailable Benchmarks:")
+ for dataset in datasets:
+ print(f" {dataset['id']}: {dataset['name']}")
+ print(f" {dataset['description']}")
+ print(f" URL: {dataset['url']}")
+ print()
+
+
+def compare_configs_cli(args):
+ """
+ CLI handler for comparing multiple configurations.
+
+ Args:
+ args: Parsed command-line arguments
+ """
+ # Import the compare configurations function
+ from ..api.benchmark_functions import compare_configurations
+
+ # Run the comparison
+ result = compare_configurations(
+ dataset_type=args.dataset,
+ num_examples=args.examples,
+ output_dir=args.output_dir,
+ )
+
+ # Print results summary
+ print("\nConfiguration Comparison Results:")
+ print(f" Dataset: {args.dataset}")
+ print(f" Configurations tested: {result['configurations_tested']}")
+ print(f" Report saved to: {result['report_path']}")
+
+ # Print brief comparison table
+ print("\nResults Summary:")
+ print("Configuration | Accuracy | Avg. Time")
+ print("--------------- | -------- | ---------")
+ for res in result["results"]:
+ name = res["configuration_name"]
+ acc = res.get("metrics", {}).get("accuracy", 0)
+ time = res.get("metrics", {}).get("average_processing_time", 0)
+ print(f"{name:15} | {acc:.3f} | {time:.2f}s")
+
+
+def main():
+ """
+ Main entry point for benchmark CLI.
+ """
+ parser = argparse.ArgumentParser(
+ description="Local Deep Research Benchmarking Tool", prog="ldr-benchmark"
+ )
+
+ # Set up logging
+ parser.add_argument("--verbose", action="store_true", help="Enable verbose logging")
+
+ # Create subparsers
+ subparsers = parser.add_subparsers(
+ dest="command", help="Command to run", required=True
+ )
+
+ # Set up commands
+ setup_benchmark_parser(subparsers)
+
+ # Parse arguments
+ args = parser.parse_args()
+
+ # Set up logging
+ log_level = logging.DEBUG if args.verbose else logging.INFO
+ logging.basicConfig(
+ level=log_level, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+ )
+
+ # Run command
+ if hasattr(args, "func"):
+ args.func(args)
+ else:
+ parser.print_help()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/local_deep_research/web/routes/benchmark_routes.py b/src/local_deep_research/web/routes/benchmark_routes.py
new file mode 100644
index 0000000000..2934fc7537
--- /dev/null
+++ b/src/local_deep_research/web/routes/benchmark_routes.py
@@ -0,0 +1,427 @@
+"""
+Web routes for benchmarking.
+
+This module provides Flask routes for the benchmark web interface.
+"""
+
+import logging
+import os
+import threading
+
+from flask import Blueprint, jsonify, render_template, request
+
+from ...api.benchmark_functions import (
+ compare_configurations,
+ evaluate_browsecomp,
+ evaluate_simpleqa,
+ get_available_benchmarks,
+)
+
+logger = logging.getLogger(__name__)
+
+# Create blueprint
+benchmark_bp = Blueprint("benchmark", __name__, url_prefix="/benchmark")
+
+# Store running jobs
+running_jobs = {}
+
+
+def run_benchmark_task(job_id, benchmark_type, params, callback=None):
+ """
+ Run a benchmark task in a separate thread.
+
+ Args:
+ job_id: Unique job ID
+ benchmark_type: Type of benchmark to run
+ params: Parameters for the benchmark
+ callback: Optional callback to run when job completes
+ """
+ try:
+ # Update job status to running
+ running_jobs[job_id]["status"] = "running"
+
+ # Run the benchmark based on type
+ if benchmark_type == "simpleqa":
+ result = evaluate_simpleqa(**params)
+ elif benchmark_type == "browsecomp":
+ result = evaluate_browsecomp(**params)
+ elif benchmark_type == "compare":
+ result = compare_configurations(**params)
+ else:
+ result = {"error": f"Unknown benchmark type: {benchmark_type}"}
+
+ # Update job with result
+ running_jobs[job_id]["status"] = "completed"
+ running_jobs[job_id]["result"] = result
+
+ # Call callback if provided
+ if callback:
+ callback(job_id, result)
+
+ except Exception as e:
+ logger.error(f"Error running benchmark job {job_id}: {str(e)}")
+ running_jobs[job_id]["status"] = "error"
+ running_jobs[job_id]["error"] = str(e)
+
+
+@benchmark_bp.route("/", methods=["GET"])
+def benchmark_dashboard():
+ """Render benchmark dashboard."""
+ return render_template(
+ "benchmark/dashboard.html", benchmarks=get_available_benchmarks()
+ )
+
+
+@benchmark_bp.route("/run", methods=["POST"])
+def run_benchmark_endpoint():
+ """Run benchmark with specified parameters."""
+ data = request.json
+
+ # Extract benchmark type
+ benchmark_type = data.get("benchmark_type")
+ if not benchmark_type:
+ return jsonify({"error": "benchmark_type is required"}), 400
+
+ # Generate job ID
+ import uuid
+
+ job_id = str(uuid.uuid4())
+
+ # Extract parameters
+ params = {
+ "num_examples": data.get("num_examples", 100),
+ "search_iterations": data.get("search_iterations", 3),
+ "questions_per_iteration": data.get("questions_per_iteration", 3),
+ "search_tool": data.get("search_tool", "searxng"),
+ "human_evaluation": data.get("human_evaluation", False),
+ "output_dir": os.path.join("benchmark_results", job_id),
+ }
+
+ # Add optional parameters if present
+ if "evaluation_model" in data:
+ params["evaluation_model"] = data["evaluation_model"]
+ if "evaluation_provider" in data:
+ params["evaluation_provider"] = data["evaluation_provider"]
+
+ # Store job info
+ running_jobs[job_id] = {
+ "id": job_id,
+ "benchmark_type": benchmark_type,
+ "params": params,
+ "status": "pending",
+ "start_time": import_time().time(),
+ }
+
+ # Start job in background thread
+ thread = threading.Thread(
+ target=run_benchmark_task, args=(job_id, benchmark_type, params)
+ )
+ thread.daemon = True
+ thread.start()
+
+ return jsonify(
+ {
+ "status": "started",
+ "job_id": job_id,
+ "message": f"Benchmark job started: {benchmark_type}",
+ }
+ )
+
+
+@benchmark_bp.route("/status/<job_id>", methods=["GET"])
+def benchmark_status(job_id):
+ """Get status of a benchmark job."""
+ if job_id not in running_jobs:
+ return jsonify({"error": "Job not found"}), 404
+
+ job = running_jobs[job_id]
+
+ # Calculate runtime if job is running
+ if job["status"] == "running":
+ job["runtime"] = import_time().time() - job["start_time"]
+
+ return jsonify(job)
+
+
+@benchmark_bp.route("/results/<job_id>", methods=["GET"])
+def benchmark_results(job_id):
+ """Get results of a completed benchmark job."""
+ if job_id not in running_jobs:
+ return jsonify({"error": "Job not found"}), 404
+
+ job = running_jobs[job_id]
+
+ if job["status"] != "completed":
+ return jsonify({"error": f"Job is not completed: {job['status']}"}), 400
+
+ # Return job result
+ return jsonify(job["result"])
+
+
+@benchmark_bp.route("/list", methods=["GET"])
+def list_benchmarks():
+ """List available benchmarks."""
+ return jsonify(get_available_benchmarks())
+
+
+@benchmark_bp.route("/jobs", methods=["GET"])
+def list_jobs():
+ """List all benchmark jobs."""
+ return jsonify(running_jobs)
+
+
+@benchmark_bp.route("/config", methods=["GET"])
+def get_benchmark_config():
+ """Get benchmark configuration options."""
+ return jsonify(
+ {
+ "search_tools": [
+ {"id": "searxng", "name": "SearXNG"},
+ {"id": "wikipedia", "name": "Wikipedia"},
+ {"id": "arxiv", "name": "ArXiv"},
+ {"id": "pubmed", "name": "PubMed"},
+ {"id": "auto", "name": "Auto (Multiple Engines)"},
+ ],
+ "evaluation_providers": [
+ {"id": "openai_endpoint", "name": "Claude (via OpenRouter)"},
+ {"id": "openai", "name": "OpenAI"},
+ {"id": "anthropic", "name": "Anthropic"},
+ {"id": "ollama", "name": "Ollama (Local)"},
+ ],
+ "evaluation_models": {
+ "openai_endpoint": [
+ {"id": "anthropic/claude-3.7-sonnet", "name": "Claude 3.7 Sonnet"}
+ ],
+ "openai": [
+ {"id": "gpt-4o", "name": "GPT-4o"},
+ {"id": "gpt-4-turbo", "name": "GPT-4 Turbo"},
+ {"id": "gpt-3.5-turbo", "name": "GPT-3.5 Turbo"},
+ ],
+ "anthropic": [
+ {"id": "claude-3-opus", "name": "Claude 3 Opus"},
+ {"id": "claude-3-sonnet", "name": "Claude 3 Sonnet"},
+ {"id": "claude-3-haiku", "name": "Claude 3 Haiku"},
+ ],
+ "ollama": [
+ {"id": "llama3", "name": "Llama 3"},
+ {"id": "gemma:7b", "name": "Gemma 7B"},
+ {"id": "mistral", "name": "Mistral"},
+ ],
+ },
+ }
+ )
+
+
+# Utility function for importing time dynamically to avoid circular imports
+def import_time():
+ """Import time module dynamically."""
+ import time
+
+ return time
+
+
+# Function to register routes with the main app
+def register_blueprint(app):
+ """Register benchmark routes with the Flask app."""
+ app.register_blueprint(benchmark_bp)
+
+ # Create templates directory if it doesn't exist
+ template_dir = os.path.join(
+ os.path.dirname(app.root_path), "templates", "benchmark"
+ )
+ os.makedirs(template_dir, exist_ok=True)
+
+ # Create dashboard template if it doesn't exist
+ dashboard_template = os.path.join(template_dir, "dashboard.html")
+ if not os.path.exists(dashboard_template):
+ with open(dashboard_template, "w") as f:
+ f.write(
+ """
+{% extends "base.html" %}
+{% block title %}Benchmarks{% endblock %}
+{% block content %}
+<div class="container">
+ <h1>LDR Benchmarks</h1>
+
+ <div class="card mb-4">
+ <div class="card-header">
+ <h2>Run Benchmark</h2>
+ </div>
+ <div class="card-body">
+ <form id="benchmarkForm">
+ <div class="form-group">
+ <label for="benchmarkType">Benchmark</label>
+ <select class="form-control" id="benchmarkType" required>
+ {% for benchmark in benchmarks %}
+ <option value="{{ benchmark.id }}">{{ benchmark.name }} - {{ benchmark.description }}</option>
+ {% endfor %}
+ </select>
+ </div>
+
+ <div class="form-group">
+ <label for="numExamples">Number of Examples</label>
+ <input type="number" class="form-control" id="numExamples" value="10" min="1" max="1000">
+ <small class="form-text text-muted">Higher numbers give more accurate results but take longer</small>
+ </div>
+
+ <div class="form-group">
+ <label for="searchIterations">Search Iterations</label>
+ <input type="number" class="form-control" id="searchIterations" value="3" min="1" max="10">
+ </div>
+
+ <div class="form-group">
+ <label for="questionsPerIteration">Questions Per Iteration</label>
+ <input type="number" class="form-control" id="questionsPerIteration" value="3" min="1" max="10">
+ </div>
+
+ <div class="form-group">
+ <label for="searchTool">Search Tool</label>
+ <select class="form-control" id="searchTool">
+ <option value="searxng">SearXNG</option>
+ <option value="wikipedia">Wikipedia</option>
+ <option value="auto">Auto (Multiple Engines)</option>
+ </select>
+ </div>
+
+ <button type="submit" class="btn btn-primary">Start Benchmark</button>
+ </form>
+ </div>
+ </div>
+
+ <div class="card mb-4" id="benchmarkStatus" style="display: none;">
+ <div class="card-header">
+ <h2>Benchmark Status</h2>
+ </div>
+ <div class="card-body">
+ <div class="progress mb-3">
+ <div class="progress-bar" id="benchmarkProgress" role="progressbar" style="width: 0%"></div>
+ </div>
+ <p id="statusMessage">Initializing benchmark...</p>
+ <button class="btn btn-secondary" id="viewResults" style="display: none;">View Results</button>
+ </div>
+ </div>
+
+ <div class="card" id="benchmarkResults" style="display: none;">
+ <div class="card-header">
+ <h2>Benchmark Results</h2>
+ </div>
+ <div class="card-body" id="resultsContent">
+ </div>
+ </div>
+</div>
+
+<script>
+ let currentJobId = null;
+ let statusInterval = null;
+
+ document.getElementById('benchmarkForm').addEventListener('submit', function(e) {
+ e.preventDefault();
+
+ const benchmarkType = document.getElementById('benchmarkType').value;
+ const numExamples = document.getElementById('numExamples').value;
+ const searchIterations = document.getElementById('searchIterations').value;
+ const questionsPerIteration = document.getElementById('questionsPerIteration').value;
+ const searchTool = document.getElementById('searchTool').value;
+
+ // Show status card
+ document.getElementById('benchmarkStatus').style.display = 'block';
+ document.getElementById('benchmarkResults').style.display = 'none';
+ document.getElementById('viewResults').style.display = 'none';
+
+ // Start benchmark
+ fetch('/benchmark/run', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ benchmark_type: benchmarkType,
+ num_examples: parseInt(numExamples),
+ search_iterations: parseInt(searchIterations),
+ questions_per_iteration: parseInt(questionsPerIteration),
+ search_tool: searchTool
+ })
+ })
+ .then(response => response.json())
+ .then(data => {
+ if (data.job_id) {
+ currentJobId = data.job_id;
+ document.getElementById('statusMessage').textContent = data.message;
+
+ // Start polling for status updates
+ statusInterval = setInterval(checkStatus, 2000);
+ } else {
+ document.getElementById('statusMessage').textContent = 'Error: ' + data.error;
+ }
+ })
+ .catch(error => {
+ document.getElementById('statusMessage').textContent = 'Error: ' + error;
+ });
+ });
+
+ function checkStatus() {
+ if (!currentJobId) return;
+
+ fetch('/benchmark/status/' + currentJobId)
+ .then(response => response.json())
+ .then(data => {
+ if (data.status === 'running') {
+ const runtime = data.runtime || 0;
+ document.getElementById('statusMessage').textContent = `Running benchmark... (${Math.round(runtime)}s elapsed)`;
+ document.getElementById('benchmarkProgress').style.width = '50%';
+ } else if (data.status === 'completed') {
+ clearInterval(statusInterval);
+ document.getElementById('statusMessage').textContent = 'Benchmark completed successfully!';
+ document.getElementById('benchmarkProgress').style.width = '100%';
+ document.getElementById('viewResults').style.display = 'inline-block';
+ document.getElementById('viewResults').onclick = function() {
+ showResults(currentJobId);
+ };
+ } else if (data.status === 'error') {
+ clearInterval(statusInterval);
+ document.getElementById('statusMessage').textContent = 'Error: ' + data.error;
+ document.getElementById('benchmarkProgress').style.width = '100%';
+ document.getElementById('benchmarkProgress').classList.add('bg-danger');
+ }
+ })
+ .catch(error => {
+ document.getElementById('statusMessage').textContent = 'Error checking status: ' + error;
+ });
+ }
+
+ function showResults(jobId) {
+ fetch('/benchmark/results/' + jobId)
+ .then(response => response.json())
+ .then(data => {
+ document.getElementById('benchmarkResults').style.display = 'block';
+
+ let html = '';
+
+ if (data.metrics) {
+ html += `<h3>Summary</h3>`;
+ html += `<p><strong>Accuracy:</strong> ${(data.metrics.accuracy * 100).toFixed(1)}%</p>`;
+ html += `<p><strong>Examples:</strong> ${data.metrics.total_examples}</p>`;
+ html += `<p><strong>Correct:</strong> ${data.metrics.correct}</p>`;
+
+ if (data.metrics.average_processing_time) {
+ html += `<p><strong>Average Processing Time:</strong> ${data.metrics.average_processing_time.toFixed(2)}s</p>`;
+ }
+
+ html += `<p><a href="${data.report_path}" target="_blank" class="btn btn-info">View Full Report</a></p>`;
+ } else {
+ html += `<p>No metrics available. Check the results file for details.</p>`;
+ html += `<p><a href="${data.results_path}" target="_blank" class="btn btn-info">View Results File</a></p>`;
+ }
+
+ document.getElementById('resultsContent').innerHTML = html;
+ })
+ .catch(error => {
+ document.getElementById('resultsContent').innerHTML = `<p>Error loading results: ${error}</p>`;
+ });
+ }
+</script>
+{% endblock %}
+ """
+ )
+
+ logger.info("Benchmark routes registered")