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 database-based LLM configuration and parallel benchmarking tools

LearningCircuitafe4e96ffa19
diff --git a/examples/optimization/README.md b/examples/optimization/README.md
index 147fcde5c6..0aa3f2b2b7 100644
--- a/examples/optimization/README.md
+++ b/examples/optimization/README.md
@@ -24,8 +24,11 @@ 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
+- `--model`: Model name for the LLM (e.g., 'claude-3-sonnet-20240229')
+- `--provider`: Provider for the LLM (e.g., 'anthropic', 'openai', 'openai_endpoint')
+- `--endpoint-url`: Custom endpoint URL (e.g., 'https://openrouter.ai/api/v1' for OpenRouter)
+- `--api-key`: API key for the LLM provider
+- `--temperature`: Temperature for the LLM (default: 0.7)
- `--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}'
@@ -34,6 +37,22 @@ Options:
- `example_optimization.py`: Full example with all optimization modes
- `example_quick_optimization.py`: Simplified example for quick testing
+- `gemini_optimization.py`: Example using Gemini 2.0 Flash via OpenRouter
+- `llm_multi_benchmark.py`: Example with multi-benchmark optimization and custom LLM settings
+
+### Utility Scripts
+
+- `update_llm_config.py`: Update LLM configuration in the database
+ ```bash
+ python update_llm_config.py --model "google/gemini-2.0-flash" --provider "openai_endpoint" --endpoint "https://openrouter.ai/api/v1" --api-key "your-api-key"
+ ```
+
+- `run_gemini_benchmark.py`: Run benchmarks with Gemini 2.0 Flash via OpenRouter
+ ```bash
+ python run_gemini_benchmark.py --api-key "your-api-key" --examples 10
+ ```
+
+**Important**: Always update the LLM configuration in the database before running benchmarks or optimization to ensure consistent behavior. The utility scripts above help you do this.
## How Optimization Works
@@ -53,6 +72,38 @@ Optimization explores parameters such as:
- `max_results`: Maximum number of search results to consider
- Other system-specific parameters
+## Using Custom LLM Models
+
+The optimization tools support different LLM providers and models:
+
+### Via OpenRouter
+
+To use models like Gemini or other models via OpenRouter:
+
+```bash
+python run_optimization.py "Research query" --model "google/gemini-2.0-flash-001" --provider "openai_endpoint" --endpoint-url "https://openrouter.ai/api/v1" --api-key "your-openrouter-api-key"
+```
+
+Or use the dedicated example:
+
+```bash
+python gemini_optimization.py --api-key "your-openrouter-api-key"
+```
+
+### Direct Provider Access
+
+To use models directly from providers like Anthropic or OpenAI:
+
+```bash
+python run_optimization.py "Research query" --model "claude-3-sonnet-20240229" --provider "anthropic" --api-key "your-anthropic-api-key"
+```
+
+Or for OpenAI:
+
+```bash
+python run_optimization.py "Research query" --model "gpt-4-turbo" --provider "openai" --api-key "your-openai-api-key"
+```
+
## Using Optimization Results
After running optimization, you can use the resulting parameters by updating your configuration:
@@ -66,5 +117,8 @@ results = quick_summary(
questions_per_iteration=best_params["questions_per_iteration"],
search_strategy=best_params["search_strategy"],
# Other optimized parameters
+ # You can also use custom LLM configuration:
+ model_name="your-model",
+ provider="your-provider"
)
```
\ No newline at end of file
diff --git a/examples/optimization/run_gemini_benchmark.py b/examples/optimization/run_gemini_benchmark.py
new file mode 100755
index 0000000000..6fc4884fbc
--- /dev/null
+++ b/examples/optimization/run_gemini_benchmark.py
@@ -0,0 +1,271 @@
+#!/usr/bin/env python
+"""
+Run benchmarks with Gemini Flash via OpenRouter.
+
+This script updates the database LLM configuration and then runs benchmarks
+with Gemini Flash via OpenRouter.
+
+Usage:
+ # Install dependencies with PDM
+ cd /path/to/local-deep-research
+ pdm install
+
+ # Run the script with PDM
+ pdm run python examples/optimization/run_gemini_benchmark.py --api-key "your-openrouter-api-key" --examples 10
+"""
+
+import argparse
+import logging
+import os
+import sys
+import time
+from datetime import datetime
+from typing import Dict, Optional, Any, List
+
+# Add the src directory to the Python path
+project_root = os.path.abspath(
+ os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
+)
+sys.path.insert(0, os.path.join(project_root, "src"))
+
+# Configure logging
+logging.basicConfig(
+ level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+)
+logger = logging.getLogger(__name__)
+
+
+def setup_gemini_config(api_key: Optional[str] = None) -> Dict[str, Any]:
+ """
+ Create a configuration for using Gemini Flash via OpenRouter.
+
+ Args:
+ api_key: OpenRouter API key (optional, will try to get from database if not provided)
+
+ Returns:
+ Dictionary with Gemini configuration
+ """
+ # Import database utilities
+ from local_deep_research.utilities.db_utils import get_db_setting, update_db_setting
+
+ # Check if API key exists in database
+ if not api_key:
+ api_key = get_db_setting("llm.openai_endpoint.api_key")
+ if not api_key:
+ logger.error("No API key found in database and none provided")
+ return {}
+
+ # Create configuration
+ config = {
+ "model_name": "google/gemini-2.0-flash",
+ "provider": "openai_endpoint",
+ "endpoint_url": "https://openrouter.ai/api/v1",
+ "api_key": api_key,
+ }
+
+ # Update database with this configuration
+ update_db_setting("llm.model", config["model_name"])
+ update_db_setting("llm.provider", config["provider"])
+ update_db_setting("llm.openai_endpoint.url", config["endpoint_url"])
+ update_db_setting("llm.openai_endpoint.api_key", config["api_key"])
+
+ # Log configuration
+ logger.info(f"LLM configuration updated to use Gemini Flash via OpenRouter")
+ logger.info(f"Model: {config['model_name']}")
+ logger.info(f"Provider: {config['provider']}")
+
+ return config
+
+
+def run_benchmarks(
+ examples: int = 5,
+ benchmarks: List[str] = None,
+ api_key: Optional[str] = None,
+ output_dir: Optional[str] = None,
+ search_iterations: int = 2,
+ questions_per_iteration: int = 3,
+ search_tool: str = "searxng",
+) -> Dict[str, Any]:
+ """
+ Run benchmarks with Gemini Flash via OpenRouter.
+
+ Args:
+ examples: Number of examples to evaluate for each benchmark
+ benchmarks: List of benchmarks to run (defaults to ["simpleqa", "browsecomp"])
+ api_key: OpenRouter API key
+ output_dir: Directory to save results
+ search_iterations: Number of search iterations per query
+ questions_per_iteration: Number of questions per iteration
+ search_tool: Search engine to use
+
+ Returns:
+ Dictionary with benchmark results
+ """
+ # Import benchmark functions
+ from local_deep_research.benchmarks.benchmark_functions import (
+ evaluate_simpleqa,
+ evaluate_browsecomp,
+ )
+
+ # Set up Gemini configuration
+ gemini_config = setup_gemini_config(api_key)
+ if not gemini_config:
+ return {"error": "Failed to set up Gemini configuration"}
+
+ # Create timestamp for output
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ if not output_dir:
+ output_dir = os.path.join(project_root, "benchmark_results", f"gemini_eval_{timestamp}")
+
+ os.makedirs(output_dir, exist_ok=True)
+
+ # Set benchmark list
+ if not benchmarks:
+ benchmarks = ["simpleqa", "browsecomp"]
+
+ results = {}
+
+ # Run each benchmark
+ for benchmark in benchmarks:
+ start_time = time.time()
+
+ try:
+ if benchmark.lower() == "simpleqa":
+ logger.info(f"Running SimpleQA benchmark with {examples} examples")
+ benchmark_results = evaluate_simpleqa(
+ num_examples=examples,
+ search_iterations=search_iterations,
+ questions_per_iteration=questions_per_iteration,
+ search_tool=search_tool,
+ search_model=gemini_config["model_name"],
+ search_provider=gemini_config["provider"],
+ endpoint_url=gemini_config["endpoint_url"],
+ output_dir=os.path.join(output_dir, "simpleqa"),
+ )
+ elif benchmark.lower() == "browsecomp":
+ logger.info(f"Running BrowseComp benchmark with {examples} examples")
+ benchmark_results = evaluate_browsecomp(
+ num_examples=examples,
+ search_iterations=search_iterations,
+ questions_per_iteration=questions_per_iteration,
+ search_tool=search_tool,
+ search_model=gemini_config["model_name"],
+ search_provider=gemini_config["provider"],
+ endpoint_url=gemini_config["endpoint_url"],
+ output_dir=os.path.join(output_dir, "browsecomp"),
+ )
+ else:
+ logger.warning(f"Unknown benchmark: {benchmark}")
+ continue
+
+ duration = time.time() - start_time
+
+ # Log results
+ logger.info(f"{benchmark} benchmark completed in {duration:.1f} seconds")
+ if isinstance(benchmark_results, dict):
+ accuracy = benchmark_results.get("accuracy", "N/A")
+ logger.info(f"{benchmark} accuracy: {accuracy}")
+
+ # Add to results
+ results[benchmark] = {
+ "results": benchmark_results,
+ "duration": duration,
+ }
+
+ except Exception as e:
+ logger.error(f"Error running {benchmark} benchmark: {e}")
+ import traceback
+ traceback.print_exc()
+
+ results[benchmark] = {
+ "error": str(e),
+ }
+
+ # Generate summary
+ logger.info("=" * 50)
+ logger.info("BENCHMARK SUMMARY")
+ logger.info("=" * 50)
+ logger.info(f"Model: {gemini_config.get('model_name')}")
+ logger.info(f"Examples per benchmark: {examples}")
+
+ for benchmark, benchmark_results in results.items():
+ if "error" in benchmark_results:
+ logger.info(f"{benchmark}: ERROR - {benchmark_results['error']}")
+ else:
+ accuracy = benchmark_results.get("results", {}).get("accuracy", "N/A")
+ duration = benchmark_results.get("duration", 0)
+ logger.info(f"{benchmark}: Accuracy = {accuracy}, Duration = {duration:.1f}s")
+
+ logger.info(f"Results saved to: {output_dir}")
+ logger.info("=" * 50)
+
+ # Save summary to a file
+ summary_file = os.path.join(output_dir, "benchmark_summary.json")
+ try:
+ import json
+ with open(summary_file, "w") as f:
+ json.dump({
+ "timestamp": timestamp,
+ "model": gemini_config.get("model_name"),
+ "provider": gemini_config.get("provider"),
+ "examples": examples,
+ "benchmarks": [b for b in benchmarks],
+ "results": {
+ b: {
+ "accuracy": r.get("results", {}).get("accuracy", None)
+ if "error" not in r else None,
+ "duration": r.get("duration", 0) if "error" not in r else 0,
+ "error": r.get("error", None) if "error" in r else None,
+ }
+ for b, r in results.items()
+ },
+ }, f, indent=2)
+ logger.info(f"Summary saved to {summary_file}")
+ except Exception as e:
+ logger.error(f"Error saving summary: {e}")
+
+ return {
+ "status": "complete",
+ "results": results,
+ "output_dir": output_dir,
+ }
+
+
+def main():
+ """Main function to parse arguments and run benchmarks."""
+ parser = argparse.ArgumentParser(description="Run benchmarks with Gemini Flash via OpenRouter")
+
+ # Benchmark configuration
+ parser.add_argument("--examples", type=int, default=5, help="Number of examples for each benchmark")
+ parser.add_argument("--benchmarks", nargs="+", choices=["simpleqa", "browsecomp"],
+ help="Benchmarks to run (default: both)")
+ parser.add_argument("--search-iterations", type=int, default=2,
+ help="Number of search iterations")
+ parser.add_argument("--questions-per-iteration", type=int, default=3,
+ help="Questions per iteration")
+ parser.add_argument("--search-tool", default="searxng", help="Search tool to use")
+
+ # API key
+ parser.add_argument("--api-key", help="OpenRouter API key (optional if already in database)")
+
+ # Output directory
+ parser.add_argument("--output-dir", help="Directory to save results (optional)")
+
+ args = parser.parse_args()
+
+ # Run benchmarks
+ results = run_benchmarks(
+ examples=args.examples,
+ benchmarks=args.benchmarks,
+ api_key=args.api_key,
+ output_dir=args.output_dir,
+ search_iterations=args.search_iterations,
+ questions_per_iteration=args.questions_per_iteration,
+ search_tool=args.search_tool,
+ )
+
+ return 0 if results.get("status") == "complete" else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
\ No newline at end of file
diff --git a/examples/optimization/run_parallel_benchmark.py b/examples/optimization/run_parallel_benchmark.py
new file mode 100755
index 0000000000..f562e9bce3
--- /dev/null
+++ b/examples/optimization/run_parallel_benchmark.py
@@ -0,0 +1,248 @@
+#!/usr/bin/env python
+"""
+Run SimpleQA and BrowseComp benchmarks in parallel with 300 examples each.
+
+This script demonstrates running multiple benchmarks in parallel with a large number of examples.
+
+Usage:
+ # Install dependencies with PDM
+ cd /path/to/local-deep-research
+ pdm install
+
+ # Run the script with PDM
+ pdm run python examples/optimization/run_parallel_benchmark.py
+"""
+
+import argparse
+import concurrent.futures
+import logging
+import os
+import sys
+import time
+from datetime import datetime
+
+# Add the src directory to the Python path
+project_root = os.path.abspath(
+ os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
+)
+sys.path.insert(0, os.path.join(project_root, "src"))
+
+# Configure logging
+logging.basicConfig(
+ level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+)
+logger = logging.getLogger(__name__)
+
+
+def run_simpleqa_benchmark(num_examples, output_dir, model=None, provider=None, endpoint_url=None, api_key=None):
+ """Run SimpleQA benchmark with specified number of examples."""
+ from local_deep_research.benchmarks.benchmark_functions import evaluate_simpleqa
+
+ logger.info(f"Starting SimpleQA benchmark with {num_examples} examples")
+ start_time = time.time()
+
+ # Run the benchmark
+ results = evaluate_simpleqa(
+ num_examples=num_examples,
+ search_iterations=2,
+ questions_per_iteration=3,
+ search_strategy="source_based",
+ search_tool="searxng",
+ search_model=model,
+ search_provider=provider,
+ endpoint_url=endpoint_url,
+ output_dir=os.path.join(output_dir, "simpleqa")
+ )
+
+ duration = time.time() - start_time
+ logger.info(f"SimpleQA benchmark completed in {duration:.1f} seconds")
+
+ if results and isinstance(results, dict):
+ logger.info(f"SimpleQA accuracy: {results.get('accuracy', 'N/A')}")
+
+ return results
+
+
+def run_browsecomp_benchmark(num_examples, output_dir, model=None, provider=None, endpoint_url=None, api_key=None):
+ """Run BrowseComp benchmark with specified number of examples."""
+ from local_deep_research.benchmarks.benchmark_functions import evaluate_browsecomp
+
+ logger.info(f"Starting BrowseComp benchmark with {num_examples} examples")
+ start_time = time.time()
+
+ # Run the benchmark
+ results = evaluate_browsecomp(
+ num_examples=num_examples,
+ search_iterations=3,
+ questions_per_iteration=3,
+ search_strategy="source_based",
+ search_tool="searxng",
+ search_model=model,
+ search_provider=provider,
+ endpoint_url=endpoint_url,
+ output_dir=os.path.join(output_dir, "browsecomp")
+ )
+
+ duration = time.time() - start_time
+ logger.info(f"BrowseComp benchmark completed in {duration:.1f} seconds")
+
+ if results and isinstance(results, dict):
+ logger.info(f"BrowseComp accuracy: {results.get('accuracy', 'N/A')}")
+
+ return results
+
+
+def setup_llm_environment(model=None, provider=None, endpoint_url=None, api_key=None):
+ """Set up environment variables for LLM configuration."""
+ if model:
+ os.environ["LDR_LLM__MODEL"] = model
+ logger.info(f"Using LLM model: {model}")
+
+ if provider:
+ os.environ["LDR_LLM__PROVIDER"] = provider
+ logger.info(f"Using LLM provider: {provider}")
+
+ if endpoint_url:
+ os.environ["OPENAI_ENDPOINT_URL"] = endpoint_url
+ os.environ["LDR_LLM__OPENAI_ENDPOINT_URL"] = endpoint_url
+ logger.info(f"Using endpoint URL: {endpoint_url}")
+
+ if api_key:
+ # Set the appropriate environment variable based on provider
+ if provider == "openai":
+ os.environ["OPENAI_API_KEY"] = api_key
+ os.environ["LDR_LLM__OPENAI_API_KEY"] = api_key
+ elif provider == "openai_endpoint":
+ os.environ["OPENAI_ENDPOINT_API_KEY"] = api_key
+ os.environ["LDR_LLM__OPENAI_ENDPOINT_API_KEY"] = api_key
+ elif provider == "anthropic":
+ os.environ["ANTHROPIC_API_KEY"] = api_key
+ os.environ["LDR_LLM__ANTHROPIC_API_KEY"] = api_key
+
+ logger.info("API key configured")
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Run SimpleQA and BrowseComp benchmarks in parallel")
+ parser.add_argument("--examples", type=int, default=300, help="Number of examples for each benchmark (default: 300)")
+
+ # LLM configuration options
+ parser.add_argument("--model", help="Model name for the LLM (e.g., 'claude-3-sonnet-20240229')")
+ parser.add_argument("--provider", help="Provider for the LLM (e.g., 'anthropic', 'openai', 'openai_endpoint')")
+ parser.add_argument("--endpoint-url", help="Custom endpoint URL (e.g., 'https://openrouter.ai/api/v1')")
+ parser.add_argument("--api-key", help="API key for the LLM provider")
+
+ 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(project_root, "benchmark_results", f"parallel_benchmark_{timestamp}")
+ os.makedirs(output_dir, exist_ok=True)
+
+ # Display start information
+ print(f"Starting parallel benchmarks with {args.examples} examples each")
+ print(f"Results will be saved to: {output_dir}")
+
+ # Set up LLM environment if specified
+ setup_llm_environment(
+ model=args.model,
+ provider=args.provider,
+ endpoint_url=args.endpoint_url,
+ api_key=args.api_key
+ )
+
+ # Start time for total execution
+ total_start_time = time.time()
+
+ # Run benchmarks in parallel using ThreadPoolExecutor
+ with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
+ # Submit both benchmark jobs
+ simpleqa_future = executor.submit(
+ run_simpleqa_benchmark,
+ args.examples,
+ output_dir,
+ args.model,
+ args.provider,
+ args.endpoint_url,
+ args.api_key
+ )
+
+ browsecomp_future = executor.submit(
+ run_browsecomp_benchmark,
+ args.examples,
+ output_dir,
+ args.model,
+ args.provider,
+ args.endpoint_url,
+ args.api_key
+ )
+
+ # Get results from both futures
+ try:
+ simpleqa_results = simpleqa_future.result()
+ print(f"SimpleQA benchmark completed successfully")
+ except Exception as e:
+ logger.error(f"Error in SimpleQA benchmark: {e}")
+ simpleqa_results = None
+
+ try:
+ browsecomp_results = browsecomp_future.result()
+ print(f"BrowseComp benchmark completed successfully")
+ except Exception as e:
+ logger.error(f"Error in BrowseComp benchmark: {e}")
+ browsecomp_results = None
+
+ # Calculate total time
+ total_duration = time.time() - total_start_time
+
+ # Print summary
+ print("\n" + "=" * 50)
+ print(" PARALLEL BENCHMARK SUMMARY ")
+ print("=" * 50)
+ print(f"Total duration: {total_duration:.1f} seconds")
+ print(f"Examples per benchmark: {args.examples}")
+
+ if simpleqa_results and isinstance(simpleqa_results, dict):
+ print(f"SimpleQA accuracy: {simpleqa_results.get('accuracy', 'N/A')}")
+ else:
+ print("SimpleQA: Failed or no results")
+
+ if browsecomp_results and isinstance(browsecomp_results, dict):
+ print(f"BrowseComp accuracy: {browsecomp_results.get('accuracy', 'N/A')}")
+ else:
+ print("BrowseComp: Failed or no results")
+
+ print(f"Results saved to: {output_dir}")
+ print("=" * 50)
+
+ # Save summary to JSON file
+ try:
+ import json
+
+ summary = {
+ "timestamp": timestamp,
+ "examples_per_benchmark": args.examples,
+ "total_duration": total_duration,
+ "simpleqa": {
+ "accuracy": simpleqa_results.get("accuracy") if simpleqa_results else None,
+ "completed": simpleqa_results is not None
+ },
+ "browsecomp": {
+ "accuracy": browsecomp_results.get("accuracy") if browsecomp_results else None,
+ "completed": browsecomp_results is not None
+ },
+ "model": args.model,
+ "provider": args.provider
+ }
+
+ with open(os.path.join(output_dir, "parallel_benchmark_summary.json"), "w") as f:
+ json.dump(summary, f, indent=2)
+
+ except Exception as e:
+ logger.error(f"Error saving summary: {e}")
+
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
\ No newline at end of file
diff --git a/examples/optimization/update_llm_config.py b/examples/optimization/update_llm_config.py
new file mode 100755
index 0000000000..49c5490e35
--- /dev/null
+++ b/examples/optimization/update_llm_config.py
@@ -0,0 +1,178 @@
+#!/usr/bin/env python
+"""
+Update LLM configuration in the database for benchmarks.
+
+This script updates the LLM configuration in the database to ensure
+consistent behavior when running benchmarks with different LLM models.
+
+Usage:
+ # Install dependencies with PDM
+ cd /path/to/local-deep-research
+ pdm install
+
+ # Run the script with PDM
+ pdm run python examples/optimization/update_llm_config.py --model "google/gemini-2.0-flash" --provider "openai_endpoint" --endpoint "https://openrouter.ai/api/v1" --api-key "your-api-key"
+
+ # Or to reset to default configuration
+ pdm run python examples/optimization/update_llm_config.py --reset
+"""
+
+import argparse
+import logging
+import os
+import sys
+from typing import Optional
+
+# Add the src directory to the Python path
+project_root = os.path.abspath(
+ os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
+)
+sys.path.insert(0, os.path.join(project_root, "src"))
+
+# Configure logging
+logging.basicConfig(
+ level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+)
+logger = logging.getLogger(__name__)
+
+
+def update_llm_configuration(
+ model_name: Optional[str] = None,
+ provider: Optional[str] = None,
+ endpoint_url: Optional[str] = None,
+ api_key: Optional[str] = None,
+ temperature: Optional[float] = None,
+ reset: bool = False,
+) -> bool:
+ """
+ Update LLM configuration in the database.
+
+ Args:
+ model_name: LLM model name to set
+ provider: LLM provider to set
+ endpoint_url: Endpoint URL for OpenRouter or similar services
+ api_key: API key for the provider
+ temperature: Temperature setting for the LLM
+ reset: If True, reset to default configuration
+
+ Returns:
+ True if successful, False otherwise
+ """
+ # Import database utility functions
+ try:
+ from local_deep_research.utilities.db_utils import update_db_setting, get_db_setting
+ except ImportError:
+ logger.error("Could not import database utilities. Make sure you're in the correct directory.")
+ return False
+
+ # Default configuration
+ default_config = {
+ "llm.model": "gemma:latest",
+ "llm.provider": "ollama",
+ "llm.temperature": 0.7,
+ "llm.max_tokens": 30000,
+ }
+
+ try:
+ if reset:
+ # Reset to default configuration
+ logger.info("Resetting LLM configuration to defaults")
+
+ for key, value in default_config.items():
+ update_db_setting(key, value)
+ logger.info(f"Reset {key} to {value}")
+
+ # Clear API keys
+ update_db_setting("llm.openai_endpoint.api_key", "")
+ update_db_setting("llm.openai_endpoint.url", "")
+
+ logger.info("LLM configuration reset to defaults")
+ return True
+
+ # Update model and provider if provided
+ if model_name:
+ update_db_setting("llm.model", model_name)
+ logger.info(f"Updated llm.model to {model_name}")
+
+ if provider:
+ update_db_setting("llm.provider", provider)
+ logger.info(f"Updated llm.provider to {provider}")
+
+ if temperature is not None:
+ update_db_setting("llm.temperature", temperature)
+ logger.info(f"Updated llm.temperature to {temperature}")
+
+ # Handle provider-specific settings
+ if provider == "openai_endpoint":
+ if endpoint_url:
+ update_db_setting("llm.openai_endpoint.url", endpoint_url)
+ logger.info(f"Updated llm.openai_endpoint.url to {endpoint_url}")
+
+ if api_key:
+ update_db_setting("llm.openai_endpoint.api_key", api_key)
+ logger.info(f"Updated llm.openai_endpoint.api_key (value hidden)")
+
+ elif provider == "openai":
+ if api_key:
+ update_db_setting("llm.openai.api_key", api_key)
+ logger.info(f"Updated llm.openai.api_key (value hidden)")
+
+ elif provider == "anthropic":
+ if api_key:
+ update_db_setting("llm.anthropic.api_key", api_key)
+ logger.info(f"Updated llm.anthropic.api_key (value hidden)")
+
+ # Verify settings were updated
+ current_model = get_db_setting("llm.model")
+ current_provider = get_db_setting("llm.provider")
+
+ logger.info(f"Current LLM configuration: model={current_model}, provider={current_provider}")
+
+ if provider == "openai_endpoint":
+ endpoint = get_db_setting("llm.openai_endpoint.url")
+ has_key = bool(get_db_setting("llm.openai_endpoint.api_key"))
+ logger.info(f"OpenAI Endpoint URL: {endpoint}")
+ logger.info(f"Has API key: {has_key}")
+
+ return True
+
+ except Exception as e:
+ logger.error(f"Error updating LLM configuration: {str(e)}")
+ return False
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Update LLM configuration in the database")
+
+ # Configuration options
+ parser.add_argument("--model", help="LLM model name")
+ parser.add_argument("--provider", help="LLM provider (e.g., 'anthropic', 'openai', 'openai_endpoint')")
+ parser.add_argument("--endpoint", help="Endpoint URL for OpenRouter or similar services")
+ parser.add_argument("--api-key", help="API key for the provider")
+ parser.add_argument("--temperature", type=float, help="Temperature setting for the LLM")
+
+ # Reset option
+ parser.add_argument("--reset", action="store_true", help="Reset to default configuration")
+
+ args = parser.parse_args()
+
+ # Check if any argument is provided
+ if not any([args.model, args.provider, args.endpoint, args.api_key, args.temperature, args.reset]):
+ parser.print_help()
+ return 1
+
+ # Update LLM configuration
+ success = update_llm_configuration(
+ model_name=args.model,
+ provider=args.provider,
+ endpoint_url=args.endpoint,
+ api_key=args.api_key,
+ temperature=args.temperature,
+ reset=args.reset,
+ )
+
+ return 0 if success else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
\ No newline at end of file
diff --git a/src/local_deep_research/benchmarks/benchmark_functions.py b/src/local_deep_research/benchmarks/benchmark_functions.py
index 6a7ff7e863..ae85cb4520 100644
--- a/src/local_deep_research/benchmarks/benchmark_functions.py
+++ b/src/local_deep_research/benchmarks/benchmark_functions.py
@@ -5,6 +5,7 @@ This module provides functions for running benchmarks programmatically.
"""
import logging
+import os
from typing import Any, Dict, List, Optional
from ..benchmarks import (
@@ -27,6 +28,10 @@ def evaluate_simpleqa(
evaluation_model: Optional[str] = None,
evaluation_provider: Optional[str] = None,
output_dir: str = "benchmark_results",
+ search_model: Optional[str] = None,
+ search_provider: Optional[str] = None,
+ endpoint_url: Optional[str] = None,
+ search_strategy: str = "source_based",
) -> Dict[str, Any]:
"""
Run SimpleQA benchmark evaluation.
@@ -40,6 +45,10 @@ def evaluate_simpleqa(
evaluation_model: Optional custom model for evaluation
evaluation_provider: Optional custom provider for evaluation
output_dir: Directory to save results
+ search_model: Optional model to use for the search system
+ search_provider: Optional provider to use for the search system
+ endpoint_url: Optional endpoint URL for OpenRouter or other API services
+ search_strategy: Search strategy to use (default: 'source_based')
Returns:
Dictionary with benchmark results
@@ -51,8 +60,25 @@ def evaluate_simpleqa(
"iterations": search_iterations,
"questions_per_iteration": questions_per_iteration,
"search_tool": search_tool,
+ "search_strategy": search_strategy,
}
+ # Add model configurations if provided
+ if search_model:
+ search_config["model_name"] = search_model
+ if search_provider:
+ search_config["provider"] = search_provider
+ if endpoint_url:
+ search_config["openai_endpoint_url"] = endpoint_url
+
+ # Check environment variables for additional configuration
+ if env_model := os.environ.get("LDR_SEARCH_MODEL"):
+ search_config["model_name"] = env_model
+ if env_provider := os.environ.get("LDR_SEARCH_PROVIDER"):
+ search_config["provider"] = env_provider
+ if env_url := os.environ.get("LDR_ENDPOINT_URL"):
+ search_config["openai_endpoint_url"] = env_url
+
# Set up evaluation configuration if needed
evaluation_config = None
if evaluation_model or evaluation_provider:
@@ -90,6 +116,10 @@ def evaluate_browsecomp(
evaluation_model: Optional[str] = None,
evaluation_provider: Optional[str] = None,
output_dir: str = "benchmark_results",
+ search_model: Optional[str] = None,
+ search_provider: Optional[str] = None,
+ endpoint_url: Optional[str] = None,
+ search_strategy: str = "source_based",
) -> Dict[str, Any]:
"""
Run BrowseComp benchmark evaluation.
@@ -103,6 +133,10 @@ def evaluate_browsecomp(
evaluation_model: Optional custom model for evaluation
evaluation_provider: Optional custom provider for evaluation
output_dir: Directory to save results
+ search_model: Optional model to use for the search system
+ search_provider: Optional provider to use for the search system
+ endpoint_url: Optional endpoint URL for OpenRouter or other API services
+ search_strategy: Search strategy to use (default: 'source_based')
Returns:
Dictionary with benchmark results
@@ -114,8 +148,25 @@ def evaluate_browsecomp(
"iterations": search_iterations,
"questions_per_iteration": questions_per_iteration,
"search_tool": search_tool,
+ "search_strategy": search_strategy,
}
+ # Add model configurations if provided
+ if search_model:
+ search_config["model_name"] = search_model
+ if search_provider:
+ search_config["provider"] = search_provider
+ if endpoint_url:
+ search_config["openai_endpoint_url"] = endpoint_url
+
+ # Check environment variables for additional configuration
+ if env_model := os.environ.get("LDR_SEARCH_MODEL"):
+ search_config["model_name"] = env_model
+ if env_provider := os.environ.get("LDR_SEARCH_PROVIDER"):
+ search_config["provider"] = env_provider
+ if env_url := os.environ.get("LDR_ENDPOINT_URL"):
+ search_config["openai_endpoint_url"] = env_url
+
# Set up evaluation configuration if needed
evaluation_config = None
if evaluation_model or evaluation_provider:
diff --git a/src/local_deep_research/benchmarks/optimization/api.py b/src/local_deep_research/benchmarks/optimization/api.py
index 5fcfdcee31..531e6cedd5 100644
--- a/src/local_deep_research/benchmarks/optimization/api.py
+++ b/src/local_deep_research/benchmarks/optimization/api.py
@@ -9,7 +9,13 @@ import logging
import os
from typing import Any, Callable, Dict, List, Optional, Tuple
-from local_deep_research.benchmarks.optimization.optuna_optimizer import OptunaOptimizer
+from ..metrics import (
+ calculate_quality_metrics,
+ calculate_speed_metrics,
+ calculate_resource_metrics,
+ calculate_combined_score,
+)
+from .optuna_optimizer import OptunaOptimizer
logger = logging.getLogger(__name__)
diff --git a/src/local_deep_research/benchmarks/optimization/metrics.py b/src/local_deep_research/benchmarks/optimization/metrics.py
index 7b3cc08eb7..4a5281d279 100644
--- a/src/local_deep_research/benchmarks/optimization/metrics.py
+++ b/src/local_deep_research/benchmarks/optimization/metrics.py
@@ -1,292 +1,20 @@
"""
-Simplified benchmark quality metrics for Local Deep Research optimization.
+Optimization metrics calculation.
-Uses existing benchmark functionality to evaluate parameter configurations.
+This module is maintained for backward compatibility.
+New code should use the unified metrics module.
"""
-import logging
-import os
-import tempfile
-import time
-from typing import Any, Dict, List, Optional, Union
-
-from local_deep_research.benchmarks import run_simpleqa_benchmark
-
-logger = logging.getLogger(__name__)
-
-
-def evaluate_benchmark_quality(
- system_config: Dict[str, Any],
- num_examples: int = 10,
- output_dir: Optional[str] = None,
-) -> Dict[str, float]:
- """
- Evaluate quality using SimpleQA benchmark.
-
- Args:
- system_config: Configuration parameters to evaluate
- num_examples: Number of benchmark examples to use
- output_dir: Directory to save results (temporary if None)
-
- Returns:
- Dictionary with benchmark metrics
- """
- # Create temporary directory if not provided
- temp_dir = None
- if output_dir is None:
- temp_dir = tempfile.mkdtemp(prefix="ldr_benchmark_")
- output_dir = temp_dir
-
- try:
- # Create search configuration from system config
- search_config = {
- "iterations": system_config.get("iterations", 2),
- "questions_per_iteration": system_config.get("questions_per_iteration", 2),
- "search_strategy": system_config.get("search_strategy", "iterdrag"),
- "search_tool": system_config.get("search_tool", "searxng"),
- "model_name": system_config.get("model_name"),
- "provider": system_config.get("provider"),
- }
-
- # Run benchmark
- logger.info(f"Running SimpleQA benchmark with {num_examples} examples")
- benchmark_results = run_simpleqa_benchmark(
- num_examples=num_examples,
- output_dir=output_dir,
- search_config=search_config,
- run_evaluation=True,
- )
-
- # Extract key metrics
- metrics = benchmark_results.get("metrics", {})
- accuracy = metrics.get("accuracy", 0.0)
-
- # Return only the most relevant metrics
- return {
- "accuracy": accuracy,
- "quality_score": accuracy, # Map accuracy directly to quality score
- }
-
- except Exception as e:
- logger.error(f"Error in benchmark evaluation: {str(e)}")
- return {"accuracy": 0.0, "quality_score": 0.0, "error": str(e)}
-
- finally:
- # Clean up temporary directory if we created it
- if temp_dir and os.path.exists(temp_dir):
- import shutil
-
- try:
- shutil.rmtree(temp_dir)
- except Exception as e:
- logger.warning(f"Failed to clean up temporary directory: {str(e)}")
-
-
-def measure_execution_time(
- system_config: Dict[str, Any],
- query: str = "test query",
- search_tool: Optional[str] = None,
- num_runs: int = 1,
-) -> Dict[str, float]:
- """
- Measure execution time for a given configuration.
-
- Args:
- system_config: Configuration parameters to evaluate
- query: Query to use for timing tests
- search_tool: Override search tool
- num_runs: Number of runs to average time over
-
- Returns:
- Dictionary with speed metrics
- """
- from local_deep_research.search_system import SearchSystem
-
- if search_tool:
- system_config["search_tool"] = search_tool
-
- # Configure system
- system = SearchSystem(
- iterations=system_config.get("iterations", 2),
- questions_per_iteration=system_config.get("questions_per_iteration", 2),
- search_strategy=system_config.get("search_strategy", "iterdrag"),
- search_tool=system_config.get("search_tool", "searxng"),
- model_name=system_config.get("model_name"),
- provider=system_config.get("provider"),
- )
-
- # Run multiple times and calculate average
- total_time = 0
- times = []
-
- try:
- for i in range(num_runs):
- logger.info(f"Executing speed test run {i+1}/{num_runs}")
- start_time = time.time()
- system.search(query, full_response=False)
- end_time = time.time()
- run_time = end_time - start_time
- times.append(run_time)
- total_time += run_time
-
- # Calculate metrics
- average_time = total_time / num_runs
-
- # Calculate speed score (0-1 scale, lower times are better)
- # Using sigmoid-like normalization where:
- # - Times around 30s get ~0.5 score
- # - Times under 10s get >0.8 score
- # - Times over 2min get <0.2 score
-
- # Scale to 0-1 score (lower is better, so invert)
- speed_score = 1.0 / (1.0 + (average_time / 30.0))
-
- return {
- "average_time": average_time,
- "min_time": min(times),
- "max_time": max(times),
- "speed_score": speed_score,
- }
-
- except Exception as e:
- logger.error(f"Error in speed measurement: {str(e)}")
- return {"average_time": 0.0, "speed_score": 0.0, "error": str(e)}
-
-
-def calculate_quality_metrics(
- system_config: Dict[str, Any],
- num_examples: int = 2, # Reduced for quicker demo
- output_dir: Optional[str] = None,
-) -> Dict[str, float]:
- """
- Calculate quality-related metrics for a configuration.
-
- Args:
- system_config: Configuration parameters to evaluate
- num_examples: Number of benchmark examples to use
- output_dir: Directory to save results (temporary if None)
-
- Returns:
- Dictionary with quality metrics
- """
- # Run quality evaluation
- quality_results = evaluate_benchmark_quality(
- system_config=system_config, num_examples=num_examples, output_dir=output_dir
- )
-
- # Return normalized quality score
- return {
- "quality_score": quality_results.get("quality_score", 0.0),
- "accuracy": quality_results.get("accuracy", 0.0),
- }
-
-
-def calculate_speed_metrics(
- system_config: Dict[str, Any],
- query: str = "test query",
- search_tool: Optional[str] = None,
- num_runs: int = 1,
-) -> Dict[str, float]:
- """
- Calculate speed-related metrics for a configuration.
-
- Args:
- system_config: Configuration parameters to evaluate
- query: Query to use for timing tests
- search_tool: Override search tool
- num_runs: Number of runs to average time over
-
- Returns:
- Dictionary with speed metrics
- """
- # Run speed measurement
- speed_results = measure_execution_time(
- system_config=system_config,
- query=query,
- search_tool=search_tool,
- num_runs=num_runs,
- )
-
- # Return normalized speed score
- return {
- "speed_score": speed_results.get("speed_score", 0.0),
- "average_time": speed_results.get("average_time", 0.0),
- }
-
-
-def calculate_resource_metrics(
- system_config: Dict[str, Any],
- query: str = "test query",
- search_tool: Optional[str] = None,
-) -> Dict[str, float]:
- """
- Calculate resource usage metrics for a configuration.
-
- Args:
- system_config: Configuration parameters to evaluate
- query: Query to use for resource tests
- search_tool: Override search tool
-
- Returns:
- Dictionary with resource metrics
- """
- # This is a simplified version - in a real implementation,
- # you would measure memory usage, API call counts, etc.
-
- # For now, we'll use a heuristic based on configuration values
- iterations = system_config.get("iterations", 2)
- questions = system_config.get("questions_per_iteration", 2)
- max_results = system_config.get("max_results", 50)
-
- # Simple heuristic: more iterations, questions, and results = more resources
- complexity = iterations * questions * (max_results / 50)
-
- # Normalize to 0-1 scale (lower is better)
- resource_score = 1.0 / (1.0 + (complexity / 4.0))
-
- return {"resource_score": resource_score, "estimated_complexity": complexity}
-
-
-def calculate_combined_score(
- metrics: Dict[str, Dict[str, float]], weights: Dict[str, float] = None
-) -> float:
- """
- Calculate a combined optimization score from multiple metrics.
-
- Args:
- metrics: Dictionary of metric categories and their values
- weights: Dictionary of weights for each metric category
-
- Returns:
- Combined score between 0 and 1
- """
- # Default weights if not provided
- if weights is None:
- weights = {"quality": 0.6, "speed": 0.3, "resource": 0.1}
-
- # Normalize weights to sum to 1
- total_weight = sum(weights.values())
- if total_weight == 0:
- return 0.0
-
- norm_weights = {k: v / total_weight for k, v in weights.items()}
-
- # Calculate weighted score
- score = 0.0
-
- # Quality component
- if "quality" in metrics and "quality" in norm_weights:
- quality_score = metrics["quality"].get("quality_score", 0.0)
- score += quality_score * norm_weights["quality"]
-
- # Speed component
- if "speed" in metrics and "speed" in norm_weights:
- speed_score = metrics["speed"].get("speed_score", 0.0)
- score += speed_score * norm_weights["speed"]
-
- # Resource component
- if "resource" in metrics and "resource" in norm_weights:
- resource_score = metrics["resource"].get("resource_score", 0.0)
- score += resource_score * norm_weights["resource"]
-
- return score
+from ..metrics.calculation import (
+ calculate_quality_metrics,
+ calculate_speed_metrics,
+ calculate_resource_metrics,
+ calculate_combined_score,
+)
+
+__all__ = [
+ "calculate_quality_metrics",
+ "calculate_speed_metrics",
+ "calculate_resource_metrics",
+ "calculate_combined_score",
+]
\ No newline at end of file