~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
Small fixes for eval script
Daniel Petti32885dbd5aac
diff --git a/examples/benchmarks/run_resumable_parallel_benchmark.py b/examples/benchmarks/run_resumable_parallel_benchmark.pyindex d178b0e2ef..e7113d3832 100644--- a/examples/benchmarks/run_resumable_parallel_benchmark.py+++ b/examples/benchmarks/run_resumable_parallel_benchmark.py@@ -8,8 +8,8 @@ and continuing from where it left off.Usage:# Start new benchmarkpdm run python examples/benchmarks/run_resumable_parallel_benchmark.py-- # Resume interrupted benchmark++ # Resume interrupted benchmarkpdm run python examples/benchmarks/run_resumable_parallel_benchmark.py \--resume-from benchmark_results/parallel_benchmark_20250513_235221"""@@ -17,32 +17,27 @@ Usage:import argparseimport concurrent.futuresimport json-import loggingimport osimport sysimport timefrom datetime import datetimefrom pathlib import Path-from typing import Any, Dict, List, Optional, Set, Tuple+from typing import Any, Dict, Optional, Tuple-# Add the src directory to the Python path-project_root = os.path.abspath(- os.path.dirname(os.path.dirname(os.path.dirname(__file__)))-)-sys.path.insert(0, os.path.join(project_root, "src"))+from loguru import logger+from local_deep_research.api import quick_summaryfrom local_deep_research.benchmarks.datasets import load_dataset-from local_deep_research.benchmarks.graders import grade_results+from local_deep_research.benchmarks.graders import (+ extract_answer_from_response,+ grade_results,+)from local_deep_research.benchmarks.metrics import calculate_metrics, generate_report-from local_deep_research.api import quick_summaryfrom local_deep_research.benchmarks.runners import format_query-from local_deep_research.benchmarks.graders import extract_answer_from_response-# Configure logging-logging.basicConfig(- level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"+PROJECT_ROOT = os.path.abspath(+ os.path.dirname(os.path.dirname(os.path.dirname(__file__))))-logger = logging.getLogger(__name__)def load_existing_results(results_file: str) -> Dict[str, Dict]:@@ -75,13 +70,13 @@ def find_latest_results_file(output_dir: str, dataset_type: str) -> Optional[strif files:# Sort by filename (includes timestamp) and return the latestreturn str(sorted(files)[-1])-+# Then try root directorypattern = f"{dataset_type}_*_results.jsonl"files = list(Path(output_dir).glob(pattern))if files:return str(sorted(files)[-1])-+return None@@ -94,87 +89,101 @@ def run_resumable_benchmark(resume_from: Optional[str] = None,) -> Dict[str, Any]:"""Run a benchmark with resume capability."""-+# Create output directory if neededos.makedirs(output_dir, exist_ok=True)-+# Load datasetdataset = load_dataset(dataset_type=dataset_type,num_examples=num_examples,- seed=42 # Fixed seed for reproducibility+ seed=42, # Fixed seed for reproducibility)-+# Determine output filestimestamp = datetime.now().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")+ 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")-+# Load existing results if resumingexisting_results = {}if resume_from:existing_results_file = find_latest_results_file(resume_from, dataset_type)if existing_results_file:existing_results = load_existing_results(existing_results_file)- logger.info(f"Found {len(existing_results)} existing results for {dataset_type}")-+ logger.info(+ f"Found {len(existing_results)} existing results for {dataset_type}"+ )+# Process examplesall_results = []new_results_count = 0reused_results_count = 0error_count = 0-+for i, example in enumerate(dataset):# Extract ID and questionexample_id = example.get("id", f"example_{i}")-+# Extract question and answer based on dataset typeif dataset_type.lower() == "simpleqa":question = example.get("problem", "")correct_answer = example.get("answer", "")else: # browsecompquestion = example.get("problem", "")- correct_answer = example.get("correct_answer", "") or example.get("answer", "")-+ correct_answer = example.get("correct_answer", "") or example.get(+ "answer", ""+ )+# Check if we have existing resultexisting_result = existing_results.get(example_id)-+if existing_result and existing_result.get("response"):# Reuse existing result- logger.info(f"Reusing existing result for example {i+1}/{len(dataset)}: {example_id}")+ logger.info(+ f"Reusing existing result for example {i + 1}/{len(dataset)}: {example_id}"+ )all_results.append(existing_result)reused_results_count += 1-+# Write to new results filewith open(results_file, "a") as f:f.write(json.dumps(existing_result) + "\n")else:# Process new example- logger.info(f"Processing new example {i+1}/{len(dataset)}: {question[:50]}...")-+ logger.info(+ f"Processing new example {i + 1}/{len(dataset)}: {question[:50]}..."+ )+try:# Format queryformatted_query = format_query(question, dataset_type)-+# Time the searchstart_time = time.time()-+# Get response from LDRsearch_result = quick_summary(query=formatted_query,iterations=search_config.get("iterations", 3),- questions_per_iteration=search_config.get("questions_per_iteration", 3),+ questions_per_iteration=search_config.get(+ "questions_per_iteration", 3+ ),search_tool=search_config.get("search_tool", "searxng"),- search_strategy=search_config.get("search_strategy", "source_based"),+ search_strategy=search_config.get(+ "search_strategy", "source-based"+ ),)-+processing_time = time.time() - start_time-+# Extract responseresponse = search_result.get("summary", "")extracted = extract_answer_from_response(response, dataset_type)-+# Create resultresult = {"id": example_id,@@ -187,18 +196,18 @@ def run_resumable_benchmark("sources": search_result.get("sources", []),"search_config": search_config,}-+all_results.append(result)new_results_count += 1-+# Write to file immediatelywith open(results_file, "a") as f:f.write(json.dumps(result) + "\n")-+except Exception as e:- logger.error(f"Error processing example {i+1}: {str(e)}")+ logger.error(f"Error processing example {i + 1}: {str(e)}")error_count += 1-+# Create error resulterror_result = {"id": example_id,@@ -207,33 +216,35 @@ def run_resumable_benchmark("error": str(e),"processing_time": 0,}-+all_results.append(error_result)new_results_count += 1-+# Write error resultwith open(results_file, "a") as f:f.write(json.dumps(error_result) + "\n")-- logger.info(f"Completed {dataset_type}: {new_results_count} new, {reused_results_count} reused, {error_count} errors")-++ logger.info(+ f"Completed {dataset_type}: {new_results_count} new, {reused_results_count} reused, {error_count} errors"+ )+# Run evaluation on all resultslogger.info(f"Running evaluation for {dataset_type}")try:- evaluation_results = grade_results(+ grade_results(results_file=results_file,output_file=evaluation_file,dataset_type=dataset_type,evaluation_config=evaluation_config,)-+# Calculate metricsmetrics = calculate_metrics(evaluation_file)logger.info(f"Metrics for {dataset_type}: {metrics}")-+# Generate reportgenerate_report(metrics, evaluation_file, report_file, dataset_type)-+return {"accuracy": metrics.get("accuracy", 0),"metrics": metrics,@@ -258,10 +269,10 @@ def run_resumable_benchmark(def run_simpleqa_benchmark_wrapper(args: Tuple) -> Dict[str, Any]:"""Wrapper for running SimpleQA benchmark in parallel."""num_examples, output_dir, resume_from, search_config, evaluation_config = args-+logger.info(f"Starting SimpleQA benchmark with {num_examples} examples")start_time = time.time()-+results = run_resumable_benchmark(dataset_type="simpleqa",num_examples=num_examples,@@ -270,23 +281,23 @@ def run_simpleqa_benchmark_wrapper(args: Tuple) -> Dict[str, Any]:evaluation_config=evaluation_config,resume_from=resume_from,)-+duration = time.time() - start_timelogger.info(f"SimpleQA benchmark completed in {duration:.1f} seconds")-+return resultsdef run_browsecomp_benchmark_wrapper(args: Tuple) -> Dict[str, Any]:"""Wrapper for running BrowseComp benchmark in parallel."""num_examples, output_dir, resume_from, search_config, evaluation_config = args-+logger.info(f"Starting BrowseComp benchmark with {num_examples} examples")start_time = time.time()-+# BrowseComp needs more iterationsbrowsecomp_config = {**search_config, "iterations": 3}-+results = run_resumable_benchmark(dataset_type="browsecomp",num_examples=num_examples,@@ -295,43 +306,42 @@ def run_browsecomp_benchmark_wrapper(args: Tuple) -> Dict[str, Any]:evaluation_config=evaluation_config,resume_from=resume_from,)-+duration = time.time() - start_timelogger.info(f"BrowseComp benchmark completed in {duration:.1f} seconds")-+return resultsdef 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+ os.environ["LDR_LLM_MODEL"] = modellogger.info(f"Using LLM model: {model}")-+if provider:- os.environ["LDR_LLM__PROVIDER"] = provider+ os.environ["LDR_LLM_PROVIDER"] = providerlogger.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+ os.environ["LDR_LLM_OPENAI_ENDPOINT_URL"] = endpoint_url+ os.environ["LDR_LLM_OLLAMA_URL"] = endpoint_urllogger.info(f"Using endpoint URL: {endpoint_url}")-+if api_key:# Set the appropriate environment variable based on providerif provider == "openai":- os.environ["OPENAI_API_KEY"] = api_key- os.environ["LDR_LLM__OPENAI_API_KEY"] = api_key+ os.environ["LDR_LLM_OPENAI_API_KEY"] = api_keyelif provider == "openai_endpoint":- os.environ["OPENAI_ENDPOINT_API_KEY"] = api_key- os.environ["LDR_LLM__OPENAI_ENDPOINT_API_KEY"] = api_key+ os.environ["LDR_LLM_OPENAI_ENDPOINT_API_KEY"] = api_keyelif provider == "anthropic":os.environ["ANTHROPIC_API_KEY"] = api_key- os.environ["LDR_LLM__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 with resume capability"@@ -346,7 +356,7 @@ def main():"--resume-from",help="Path to previous benchmark results directory to resume from",)-+# LLM configuration optionsparser.add_argument("--model", help="Model name for the LLM (e.g., 'google/gemini-2.0-flash-001')"@@ -360,15 +370,15 @@ def main():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()-+# Determine output directoryif args.resume_from:# Create new directory but link to old resultstimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")output_dir = os.path.join(- project_root, "benchmark_results", f"resumed_benchmark_{timestamp}"+ PROJECT_ROOT, "benchmark_results", f"resumed_benchmark_{timestamp}")os.makedirs(output_dir, exist_ok=True)logger.info(f"Resuming from {args.resume_from}, new results in {output_dir}")@@ -376,17 +386,17 @@ def main():# Create new timestamp directorytimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")output_dir = os.path.join(- project_root, "benchmark_results", f"parallel_benchmark_{timestamp}"+ PROJECT_ROOT, "benchmark_results", f"parallel_benchmark_{timestamp}")os.makedirs(output_dir, exist_ok=True)logger.info(f"Starting new benchmark in: {output_dir}")-+# Display start informationprint(f"Starting parallel benchmarks with {args.examples} examples each")print(f"Results will be saved to: {output_dir}")if args.resume_from:print(f"Resuming from previous run: {args.resume_from}")-+# Set up LLM environment if specifiedsetup_llm_environment(model=args.model,@@ -394,15 +404,15 @@ def main():endpoint_url=args.endpoint_url,api_key=args.api_key,)-+# Set up configurationssearch_config = {"iterations": 2,"questions_per_iteration": 3,"search_tool": "searxng",- "search_strategy": "source_based",+ "search_strategy": "source-based",}-+# Add model configurations if providedif args.model:search_config["model_name"] = args.model@@ -410,77 +420,93 @@ def main():search_config["provider"] = args.providerif args.endpoint_url:search_config["openai_endpoint_url"] = args.endpoint_url-+evaluation_config = {"provider": "ANTHROPIC","model_name": "claude-3-7-sonnet-20250219","temperature": 0,}-+# Start time for total executiontotal_start_time = time.time()-+# Run benchmarks in parallelwith concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:# Submit both benchmark jobssimpleqa_future = executor.submit(run_simpleqa_benchmark_wrapper,- (args.examples, output_dir, args.resume_from, search_config, evaluation_config)+ (+ args.examples,+ output_dir,+ args.resume_from,+ search_config,+ evaluation_config,+ ),)-+browsecomp_future = executor.submit(run_browsecomp_benchmark_wrapper,- (args.examples, output_dir, args.resume_from, search_config, evaluation_config)+ (+ args.examples,+ output_dir,+ args.resume_from,+ search_config,+ evaluation_config,+ ),)-+# Get resultstry:simpleqa_results = simpleqa_future.result()- print(f"SimpleQA benchmark completed: {simpleqa_results['new_results']} new, {simpleqa_results['reused_results']} reused")+ print(+ f"SimpleQA benchmark completed: {simpleqa_results['new_results']} new, {simpleqa_results['reused_results']} reused"+ )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: {browsecomp_results['new_results']} new, {browsecomp_results['reused_results']} reused")+ print(+ f"BrowseComp benchmark completed: {browsecomp_results['new_results']} new, {browsecomp_results['reused_results']} reused"+ )except Exception as e:logger.error(f"Error in BrowseComp benchmark: {e}")browsecomp_results = None-+# Calculate total timetotal_duration = time.time() - total_start_time-+# Print summaryprint("\n" + "=" * 50)print(" PARALLEL BENCHMARK SUMMARY ")print("=" * 50)print(f"Total duration: {total_duration:.1f} seconds")- print(f"Examples per benchmark: {args.examples}")+ print("Examples per benchmark: {args.examples}")if args.resume_from:print(f"Resumed from: {args.resume_from}")-+if simpleqa_results:- print(f"\nSimpleQA:")+ print("\nSimpleQA:")print(f" - Accuracy: {simpleqa_results.get('accuracy', 'N/A')}")print(f" - New results: {simpleqa_results['new_results']}")print(f" - Reused results: {simpleqa_results['reused_results']}")print(f" - Errors: {simpleqa_results.get('errors', 0)}")else:print("\nSimpleQA: Failed or no results")-+if browsecomp_results:- print(f"\nBrowseComp:")+ print("\nBrowseComp:")print(f" - Accuracy: {browsecomp_results.get('accuracy', 'N/A')}")print(f" - New results: {browsecomp_results['new_results']}")print(f" - Reused results: {browsecomp_results['reused_results']}")print(f" - Errors: {browsecomp_results.get('errors', 0)}")else:print("\nBrowseComp: Failed or no results")-+print(f"\nResults saved to: {output_dir}")print("=" * 50)-+# Save summarytry:summary = {@@ -493,15 +519,17 @@ def main():"model": args.model,"provider": args.provider,}-- with open(os.path.join(output_dir, "parallel_benchmark_summary.json"), "w") as f:++ 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 0if __name__ == "__main__":- sys.exit(main())\ No newline at end of file+ sys.exit(main())diff --git a/src/local_deep_research/advanced_search_system/findings/repository.py b/src/local_deep_research/advanced_search_system/findings/repository.pyindex 0e1d66a0e8..1a8dcf9077 100644--- a/src/local_deep_research/advanced_search_system/findings/repository.py+++ b/src/local_deep_research/advanced_search_system/findings/repository.py@@ -291,9 +291,6 @@ Use IEEE style citations [1], [2], etc. Never make up your own citations.# Check if we're on Windowsif platform.system() == "Windows":- # Windows-compatible timeout using threading- class TimeoutError(Exception):- passdef timeout_handler(timeout_seconds, callback, args):def handler():diff --git a/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py b/src/local_deep_research/advanced_search_system/strategies/standard_strategy.pyindex 268775c65e..b5e1284dde 100644--- a/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py@@ -111,7 +111,10 @@ Iteration: {iteration + 1} of {total_iterations}"""# Call question generator with updated interfacequestions = self.question_generator.generate_questions(- query=query, context=context+ query=query,+ current_knowledge=context,+ questions_per_iteration=self.questions_per_iteration,+ questions_by_iteration=self.questions_by_iteration,)self.questions_by_iteration[iteration] = questionsdiff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.pyindex fc27c63319..ef2da25303 100644--- a/src/local_deep_research/api/research_functions.py+++ b/src/local_deep_research/api/research_functions.py@@ -23,6 +23,7 @@ def _init_search_system(search_tool: Optional[str] = None,iterations: int = 1,questions_per_iteration: int = 1,+ search_strategy: str = "source_based",) -> AdvancedSearchSystem:"""Initializes the advanced search system with specified parameters. This function sets up@@ -40,6 +41,7 @@ def _init_search_system(search_tool: Search engine to use (auto, wikipedia, arxiv, etc.). If None, uses defaultiterations: Number of research cycles to performquestions_per_iteration: Number of questions to generate per cycle+ search_strategy: The name of the search strategy to use.Returns:AdvancedSearchSystem: An instance of the configured AdvancedSearchSystem.@@ -63,7 +65,10 @@ def _init_search_system()# Create search system with custom parameters- system = AdvancedSearchSystem(llm=llm, search=search_engine)+ logger.info("Search strategy: {}", search_strategy)+ system = AdvancedSearchSystem(+ llm=llm, search=search_engine, strategy_name=search_strategy+ )# Override default settings with user-provided valuessystem.max_iterations = iterations