~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
Add adaptive rate limiting system and enhanced benchmarking capabilities
LearningCircuita94af439f7a4
diff --git a/README.md b/README.mdindex 78021be131..dc711cc374 100644--- a/README.md+++ b/README.md@@ -162,6 +162,7 @@ For more information on installation options, see [the wiki](https://github.com/- **Web Search**: Via SearXNG, Brave Search, SerpAPI (for Google results), and more- **Local Document Search**: Search through your private document collections with vector embeddings- **Cross-Engine Filtering**: Smart result ranking across search engines for better information quality+- **Adaptive Rate Limiting**: Intelligent retry system that learns optimal wait times for each search engine, automatically handling rate limits and improving reliability## 🤖 LLM Support@@ -281,6 +282,7 @@ The easiest way to configure Local Deep Research is through the web interface, w### Configuration DocumentationFor detailed configuration options, see our guides:+- [Benchmarking Guide](https://github.com/LearningCircuit/local-deep-research/blob/main/docs/BENCHMARKING.md) - Test and optimize your search configurations- [Environment Variables Guide](https://github.com/LearningCircuit/local-deep-research/blob/main/docs/env_configuration.md)- [SearXNG Setup Guide](https://github.com/LearningCircuit/local-deep-research/blob/main/docs/SearXNG-Setup.md)- [Docker Usage Guide](https://github.com/LearningCircuit/local-deep-research/blob/main/docs/docker-usage-readme.md)diff --git a/docs/BENCHMARKING.md b/docs/BENCHMARKING.mdnew file mode 100644index 0000000000..8afa3efc15--- /dev/null+++ b/docs/BENCHMARKING.md@@ -0,0 +1,91 @@+# Benchmarking System++The Local Deep Research benchmarking system evaluates search configurations, models, and strategies using standardized datasets to help you optimize performance.++**Important**: Benchmark results are indicators for configuration testing, not predictors of performance on your specific research topics. What works well on SimpleQA may perform differently on your actual research questions.++## Quick Start++### Web Interface+1. Navigate to **Benchmark** in the web interface+2. Configure your test:+ - Select datasets (SimpleQA recommended)+ - Set number of examples (start with 20-50)+ - Uses your current Settings configuration+3. Click **Start Benchmark** and monitor progress+4. View results in **Benchmark Results** page++## Datasets++### SimpleQA (Recommended)+- Fact-based questions with clear answers+- Best for testing general knowledge retrieval+- Good baseline for comparing configurations++### BrowseComp (Advanced)+- Complex browsing and comparison tasks+- Currently limited performance - use max 20 examples for testing++## Configuration Options++### Search Engines+- **Tavily**: AI-optimized commercial API+- **SearXNG**: Meta-search aggregating multiple engines+- **Brave**: Independent search engine+- **Specialized engines** (ArXiv, PubMed, Wikipedia): Not suitable for general SimpleQA testing++### Strategies+- **Focused Iteration**: Best for SimpleQA fact-based questions+- **Source-Based**: Better for comprehensive research++## Interpreting Results++### Key Metrics+- **Accuracy**: Percentage of correct answers+- **Processing Time**: Time per question (30-60s is typical)+- **Search Results**: Number of search results retrieved per query++### Performance Expectations+- **Focused iteration with SimpleQA**: Around 95% potential with optimal setup+- **Source-based strategy**: Around 70% accuracy, more comprehensive results++## Best Practices++### Testing Workflow+1. Start with 20 examples to verify configuration+2. Check that search results are being retrieved+3. Scale to 50-100 examples for reliable metrics+4. Adjust settings based on results++### Troubleshooting+- **Low accuracy**: Verify API keys and search engine connectivity+- **No search results**: Check API credentials and rate limiting+- **Very fast processing**: Usually indicates configuration issues++## Requirements++### API Keys Needed+- **Evaluation**: OpenRouter API key for automatic grading+- **Search**: API key for your chosen search engine+- **LLM**: API key for your language model provider++## Responsible Usage++- Start with small tests to verify configuration+- Use moderate example counts for shared resources+- Monitor API usage in the Metrics page+- Respect rate limits and shared infrastructure++## Important Limitations++Benchmarks test standardized questions and may not reflect performance on:+- Your specific domain or research topics+- Complex, multi-step research questions+- Real-time or recent information queries+- Specialized knowledge areas++Use benchmarks as configuration guidance, then test with your actual research topics to validate performance.++---++The benchmarking system helps you find starting configurations for reliable research results.diff --git a/examples/benchmarks/run_resumable_parallel_benchmark.py b/examples/benchmarks/run_resumable_parallel_benchmark.pyindex 6196c5686a..1d3b2e580a 100644--- a/examples/benchmarks/run_resumable_parallel_benchmark.py+++ b/examples/benchmarks/run_resumable_parallel_benchmark.py@@ -399,6 +399,12 @@ 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")+ parser.add_argument(+ "--datasets",+ choices=["simpleqa", "browsecomp", "both"],+ default="both",+ help="Which datasets to run (default: both)",+ )args = parser.parse_args()@@ -438,10 +444,10 @@ def main():# Set up configurationssearch_config = {- "iterations": 8, # Increased for BrowseComp with source-based strategy- "questions_per_iteration": 5, # Good for source-based strategy+ "iterations": 8, # Same as original 96% benchmark+ "questions_per_iteration": 5, # Same as original 96% benchmark"search_tool": "searxng",- "search_strategy": "source-based", # Test source-based strategy+ "search_strategy": "focused_iteration", # Same as original 96% benchmark# performance}@@ -462,49 +468,56 @@ def main():# Start time for total executiontotal_start_time = time.time()- # Run benchmarks in parallel- with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:- # Submit both benchmark jobs- simpleqa_future = executor.submit(- run_simpleqa_benchmark_wrapper,- (- 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,- ),- )-- # Get results- try:- simpleqa_results = simpleqa_future.result()- print(- f"SimpleQA benchmark completed: {simpleqa_results['new_results']} new, {simpleqa_results['reused_results']} reused"+ # Run benchmarks based on user selection+ futures = []++ if args.datasets in ["simpleqa", "both"]:+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:+ simpleqa_future = executor.submit(+ run_simpleqa_benchmark_wrapper,+ (+ args.examples,+ output_dir,+ args.resume_from,+ search_config,+ evaluation_config,+ ),)- except Exception as e:- logger.error(f"Error in SimpleQA benchmark: {e}")- simpleqa_results = None+ futures.append(("simpleqa", simpleqa_future))++ if args.datasets in ["browsecomp", "both"]:+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:+ browsecomp_future = executor.submit(+ run_browsecomp_benchmark_wrapper,+ (+ args.examples,+ output_dir,+ args.resume_from,+ search_config,+ evaluation_config,+ ),+ )+ futures.append(("browsecomp", browsecomp_future))++ # Get results from completed futures+ simpleqa_results = None+ browsecomp_results = None+ for dataset_name, future in futures:try:- browsecomp_results = browsecomp_future.result()- print(- f"BrowseComp benchmark completed: {browsecomp_results['new_results']} new, {browsecomp_results['reused_results']} reused"- )+ result = future.result()+ if dataset_name == "simpleqa":+ simpleqa_results = result+ print(+ f"SimpleQA benchmark completed: {result['new_results']} new, {result['reused_results']} reused"+ )+ elif dataset_name == "browsecomp":+ browsecomp_results = result+ print(+ f"BrowseComp benchmark completed: {result['new_results']} new, {result['reused_results']} reused"+ )except Exception as e:- logger.error(f"Error in BrowseComp benchmark: {e}")- browsecomp_results = None+ logger.error(f"Error in {dataset_name} benchmark: {e}")# Calculate total timetotal_duration = time.time() - total_start_timediff --git a/pyproject.toml b/pyproject.tomlindex 98230977e3..613373daae 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -66,6 +66,7 @@ dependencies = ["plotly>=6.0.1","kaleido==0.2.1","aiohttp>=3.9.0",+ "tenacity>=8.0.0",][project.urls]diff --git a/src/local_deep_research/advanced_search_system/questions/browsecomp_question.py b/src/local_deep_research/advanced_search_system/questions/browsecomp_question.pyindex c97797f2f1..63d2aebb9e 100644--- a/src/local_deep_research/advanced_search_system/questions/browsecomp_question.py+++ b/src/local_deep_research/advanced_search_system/questions/browsecomp_question.py@@ -144,15 +144,25 @@ DESCRIPTORS: [entity1], [entity2], ...# 1. Original query (always include)searches.append(query)+ # If only 1 question requested, return just the original query+ if num_questions <= 1:+ return searches[:1]+# 2. Domain exploration searches (combine key entities)- if entities["names"]:+ if entities["names"] and len(searches) < num_questions:for name in entities["names"][:2]: # Top 2 names+ if len(searches) >= num_questions:+ breaksearches.append(f"{name}")- if entities["descriptors"]:+ if entities["descriptors"] and len(searches) < num_questions:searches.append(f"{name} {entities['descriptors'][0]}")# 3. Temporal searches if years are important- if entities["temporal"] and len(entities["temporal"]) <= 10:+ if (+ entities["temporal"]+ and len(entities["temporal"]) <= 10+ and len(searches) < num_questions+ ):# For small year ranges, search each year with a key termkey_term = (entities["names"][0]@@ -162,14 +172,18 @@ DESCRIPTORS: [entity1], [entity2], ...else "")for year in entities["temporal"][:5]: # Limit to 5 years initially+ if len(searches) >= num_questions:+ breakif key_term:searches.append(f"{key_term} {year}")# 4. Location-based searches- if entities["locations"]:+ if entities["locations"] and len(searches) < num_questions:for location in entities["locations"][:2]:+ if len(searches) >= num_questions:+ breaksearches.append(f"{location}")- if entities["descriptors"]:+ if entities["descriptors"] and len(searches) < num_questions:searches.append(f"{location} {entities['descriptors'][0]}")# Remove duplicates and limit to requested number@@ -179,6 +193,8 @@ DESCRIPTORS: [entity1], [entity2], ...if s.lower() not in seen:seen.add(s.lower())unique_searches.append(s)+ if len(unique_searches) >= num_questions:+ breakreturn unique_searches[:num_questions]@@ -238,21 +254,26 @@ Format: One search per lineif line:searches.append(line)- # Ensure we have enough searches+ # Ensure we have enough searches, but respect the limitwhile len(searches) < num_questions:# Generate combinations programmaticallyif iteration <= 5 and entities["temporal"]:# Continue with year-based searches+ added_any = Falsefor year in entities["temporal"]:if not self._was_searched(year, questions_by_iteration):base_term = (entities["names"][0] if entities["names"] else "")searches.append(f"{base_term} {year}".strip())+ added_any = Trueif len(searches) >= num_questions:break+ if not added_any:+ break # No more year searches to addelse:# Combine multiple constraints+ added_any = Falseif entities["names"] and entities["descriptors"]:for name in entities["names"]:for desc in entities["descriptors"]:@@ -261,8 +282,13 @@ Format: One search per linecombo, questions_by_iteration):searches.append(combo)+ added_any = Trueif len(searches) >= num_questions:break+ if len(searches) >= num_questions:+ break+ if not added_any:+ break # No more combinations to addreturn searches[:num_questions]diff --git a/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py b/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.pyindex e1214ef080..e24c6f0d30 100644--- a/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py@@ -55,7 +55,7 @@ class FocusedIterationStrategy(BaseSearchStrategy):all_links_of_system=None,max_iterations: int = 8, # OPTIMAL FOR SIMPLEQA: 96.51% accuracy achievedquestions_per_iteration: int = 5, # OPTIMAL FOR SIMPLEQA: proven config- use_browsecomp_optimization: bool = False, # Can be False for pure SimpleQA+ use_browsecomp_optimization: bool = True, # True for 95%+ accuracy with forced_answer handler):"""Initialize with components optimized for focused iteration."""super().__init__(all_links_of_system)@@ -63,9 +63,9 @@ class FocusedIterationStrategy(BaseSearchStrategy):self.model = model or get_llm()self.progress_callback = None- # Configuration- self.max_iterations = max_iterations- self.questions_per_iteration = questions_per_iteration+ # Configuration - ensure these are integers+ self.max_iterations = int(max_iterations)+ self.questions_per_iteration = int(questions_per_iteration)self.use_browsecomp_optimization = use_browsecomp_optimization# Initialize specialized components@@ -158,9 +158,11 @@ class FocusedIterationStrategy(BaseSearchStrategy):questions_by_iteration=self.questions_by_iteration,)- # Always include original query in first iteration+ # Always include original query in first iteration, but respect question limitif iteration == 1 and query not in questions:questions = [query] + questions+ # Trim to respect questions_per_iteration limit+ questions = questions[: self.questions_per_iteration]self.questions_by_iteration[iteration] = questionslogger.info(f"Iteration {iteration} questions: {questions}")diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.pyindex ba67113771..5634dded8f 100644--- a/src/local_deep_research/api/research_functions.py+++ b/src/local_deep_research/api/research_functions.py@@ -3,7 +3,7 @@ API module for Local Deep Research.Provides programmatic access to search and research capabilities."""-from typing import Any, Callable, Dict, Optional+from typing import Any, Callable, Dict, Optional, Unionfrom loguru import logger@@ -84,6 +84,7 @@ def _init_search_system(def quick_summary(query: str,+ research_id: Optional[Union[int, str]] = None,**kwargs: Any,) -> Dict[str, Any]:"""@@ -91,6 +92,7 @@ def quick_summary(Args:query: The research query to analyze+ research_id: Optional research ID (int or UUID string) for tracking metrics**kwargs: Configuration for the search system. Will be forwarded to`_init_search_system()`.@@ -103,7 +105,29 @@ def quick_summary("""logger.info("Generating quick summary for query: %s", query)- system = _init_search_system(**kwargs)+ # Generate a research_id if none provided+ if research_id is None:+ import uuid++ research_id = str(uuid.uuid4())+ logger.debug(f"Generated research_id: {research_id}")++ # Set search context with research_id+ from ..metrics.search_tracker import set_search_context++ search_context = {+ "research_id": research_id, # Pass UUID or integer directly+ "research_query": query,+ "research_mode": kwargs.get("research_mode", "quick"),+ "research_phase": "init",+ "search_iteration": 0,+ "search_engine_selected": kwargs.get("search_tool"),+ }+ set_search_context(search_context)++ # Remove research_mode from kwargs before passing to _init_search_system+ init_kwargs = {k: v for k, v in kwargs.items() if k != "research_mode"}+ system = _init_search_system(**init_kwargs)# Perform the search and analysisresults = system.analyze_topic(query)diff --git a/src/local_deep_research/benchmarks/graders.py b/src/local_deep_research/benchmarks/graders.pyindex 7e2390dff6..c16eb06082 100644--- a/src/local_deep_research/benchmarks/graders.py+++ b/src/local_deep_research/benchmarks/graders.py@@ -65,15 +65,21 @@ def get_evaluation_llm(custom_config: Optional[Dict[str, Any]] = None):# Check if we're using openai_endpoint but don't have an API key configuredif filtered_config.get("provider") == "openai_endpoint":- # Try to get API key from environment or config- import os+ # Try to get API key from database settings first, then environment+ from ..utilities.db_utils import get_db_setting++ api_key = get_db_setting("llm.openai_endpoint.api_key")+ if not api_key:+ # Fall back to environment variable+ import os++ api_key = os.getenv("OPENAI_ENDPOINT_API_KEY")- 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."+ "Set the llm.openai_endpoint.api_key setting in the database or "+ "OPENAI_ENDPOINT_API_KEY environment variable.")# Try to fall back to LDR's config if API key not explicitly provided# The get_llm function will handle this case@@ -117,6 +123,150 @@ def extract_answer_from_response(}+def grade_single_result(+ result_data: Dict[str, Any],+ dataset_type: str = "simpleqa",+ evaluation_config: Optional[Dict[str, Any]] = None,+) -> Dict[str, Any]:+ """+ Grade a single benchmark result using LLM.++ Args:+ result_data: Dictionary containing result data with keys: id, problem, correct_answer, response, extracted_answer+ dataset_type: Type of dataset+ evaluation_config: Optional custom config for evaluation LLM++ Returns:+ Dictionary with grading 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+ )++ question = result_data.get("problem", "")+ correct_answer = result_data.get("correct_answer", "")+ response = result_data.get("response", "")++ logger.info(f"Grading single result: {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++ # Format graded result+ graded_result = {+ "extracted_by_grader": extracted_answer,+ "reasoning": reasoning,+ "is_correct": is_correct,+ "graded_confidence": confidence,+ "grader_response": grading_response,+ }++ return graded_result++ except Exception as e:+ logger.error(f"Error grading single result: {str(e)}")+ return {+ "grading_error": str(e),+ "is_correct": False,+ "graded_confidence": "0",+ "grader_response": f"Grading failed: {str(e)}",+ }++def grade_results(results_file: str,output_file: str,diff --git a/src/local_deep_research/benchmarks/models/__init__.py b/src/local_deep_research/benchmarks/models/__init__.pynew file mode 100644index 0000000000..4b31ab401b--- /dev/null+++ b/src/local_deep_research/benchmarks/models/__init__.py@@ -0,0 +1,19 @@+"""Benchmark database models for ORM."""++from .benchmark_models import (+ BenchmarkConfig,+ BenchmarkProgress,+ BenchmarkResult,+ BenchmarkRun,+ BenchmarkStatus,+ DatasetType,+)++__all__ = [+ "BenchmarkRun",+ "BenchmarkResult",+ "BenchmarkConfig",+ "BenchmarkProgress",+ "BenchmarkStatus",+ "DatasetType",+]diff --git a/src/local_deep_research/benchmarks/models/benchmark_models.py b/src/local_deep_research/benchmarks/models/benchmark_models.pynew file mode 100644index 0000000000..2d8d295673--- /dev/null+++ b/src/local_deep_research/benchmarks/models/benchmark_models.py@@ -0,0 +1,283 @@+"""Database models for benchmark system."""++import enum++from sqlalchemy import (+ JSON,+ Boolean,+ Column,+ DateTime,+ Enum,+ Float,+ ForeignKey,+ Integer,+ String,+ Text,+ UniqueConstraint,+ Index,+)+from sqlalchemy.ext.declarative import declarative_base+from sqlalchemy.orm import relationship+from sqlalchemy.sql import func++# Use the same base as the main app+try:+ from ...web.database.models import Base+except ImportError:+ # Fallback for different import contexts+ from sqlalchemy.ext.declarative import declarative_base++ Base = declarative_base()+++class BenchmarkStatus(enum.Enum):+ """Status of a benchmark run."""++ PENDING = "pending"+ IN_PROGRESS = "in_progress"+ COMPLETED = "completed"+ FAILED = "failed"+ CANCELLED = "cancelled"+ PAUSED = "paused"+++class DatasetType(enum.Enum):+ """Supported dataset types."""++ SIMPLEQA = "simpleqa"+ BROWSECOMP = "browsecomp"+ CUSTOM = "custom"+++class BenchmarkRun(Base):+ """Main benchmark run metadata."""++ __tablename__ = "benchmark_runs"++ id = Column(Integer, primary_key=True, index=True)++ # Run identification+ run_name = Column(String(255), nullable=True) # User-friendly name+ config_hash = Column(+ String(16), nullable=False, index=True+ ) # For compatibility matching+ query_hash_list = Column(+ JSON, nullable=False+ ) # List of query hashes to avoid duplication++ # Configuration+ search_config = Column(+ JSON, nullable=False+ ) # Complete search configuration+ evaluation_config = Column(JSON, nullable=False) # Evaluation settings+ datasets_config = Column(+ JSON, nullable=False+ ) # Dataset selection and quantities++ # Status and timing+ status = Column(+ Enum(BenchmarkStatus), default=BenchmarkStatus.PENDING, nullable=False+ )+ created_at = Column(DateTime, server_default=func.now(), nullable=False)+ updated_at = Column(+ DateTime, server_default=func.now(), onupdate=func.now(), nullable=False+ )+ start_time = Column(DateTime, nullable=True)+ end_time = Column(DateTime, nullable=True)++ # Progress tracking+ total_examples = Column(Integer, default=0, nullable=False)+ completed_examples = Column(Integer, default=0, nullable=False)+ failed_examples = Column(Integer, default=0, nullable=False)++ # Results summary+ overall_accuracy = Column(Float, nullable=True)+ processing_rate = Column(Float, nullable=True) # Examples per minute++ # Error handling+ error_message = Column(Text, nullable=True)++ # Relationships+ results = relationship(+ "BenchmarkResult",+ back_populates="benchmark_run",+ cascade="all, delete-orphan",+ lazy="dynamic",+ )+ progress_updates = relationship(+ "BenchmarkProgress",+ back_populates="benchmark_run",+ cascade="all, delete-orphan",+ lazy="dynamic",+ )++ # Indexes for performance and extend existing+ __table_args__ = (+ Index("idx_benchmark_runs_config_hash", "config_hash"),+ Index("idx_benchmark_runs_status_created", "status", "created_at"),+ {"extend_existing": True},+ )+++class BenchmarkResult(Base):+ """Individual benchmark result for a single question."""++ __tablename__ = "benchmark_results"++ id = Column(Integer, primary_key=True, index=True)++ # Foreign key+ benchmark_run_id = Column(+ Integer,+ ForeignKey("benchmark_runs.id", ondelete="CASCADE"),+ nullable=False,+ index=True,+ )++ # Question identification+ example_id = Column(String(255), nullable=False) # Original dataset ID+ query_hash = Column(+ String(32), nullable=False, index=True+ ) # For deduplication+ dataset_type = Column(Enum(DatasetType), nullable=False)+ research_id = Column(+ String(36), nullable=True, index=True+ ) # UUID string or converted integer++ # Question and answer+ question = Column(Text, nullable=False)+ correct_answer = Column(Text, nullable=False)++ # Research results+ response = Column(Text, nullable=True)+ extracted_answer = Column(Text, nullable=True)+ confidence = Column(String(10), nullable=True)+ processing_time = Column(Float, nullable=True)+ sources = Column(JSON, nullable=True)++ # Evaluation results+ is_correct = Column(Boolean, nullable=True)+ graded_confidence = Column(String(10), nullable=True)+ grader_response = Column(Text, nullable=True)++ # Timestamps+ created_at = Column(DateTime, server_default=func.now(), nullable=False)+ completed_at = Column(DateTime, nullable=True)++ # Error handling+ research_error = Column(Text, nullable=True)+ evaluation_error = Column(Text, nullable=True)++ # Additional metadata+ task_index = Column(Integer, nullable=True) # Order in processing+ result_metadata = Column(JSON, nullable=True) # Additional data++ # Relationships+ benchmark_run = relationship("BenchmarkRun", back_populates="results")++ # Indexes for performance+ __table_args__ = (+ Index(+ "idx_benchmark_results_run_dataset",+ "benchmark_run_id",+ "dataset_type",+ ),+ Index("idx_benchmark_results_query_hash", "query_hash"),+ Index("idx_benchmark_results_completed", "completed_at"),+ UniqueConstraint(+ "benchmark_run_id", "query_hash", name="uix_run_query"+ ),+ {"extend_existing": True},+ )+++class BenchmarkConfig(Base):+ """Saved benchmark configurations for reuse."""++ __tablename__ = "benchmark_configs"++ id = Column(Integer, primary_key=True, index=True)++ # Configuration details+ name = Column(String(255), nullable=False)+ description = Column(Text, nullable=True)+ config_hash = Column(String(16), nullable=False, index=True)++ # Configuration data+ search_config = Column(JSON, nullable=False)+ evaluation_config = Column(JSON, nullable=False)+ datasets_config = Column(JSON, nullable=False)++ # Metadata+ created_at = Column(DateTime, server_default=func.now(), nullable=False)+ updated_at = Column(+ DateTime, server_default=func.now(), onupdate=func.now(), nullable=False+ )+ is_default = Column(Boolean, default=False, nullable=False)+ is_public = Column(Boolean, default=True, nullable=False)++ # Usage tracking+ usage_count = Column(Integer, default=0, nullable=False)+ last_used = Column(DateTime, nullable=True)++ # Performance data (if available)+ best_accuracy = Column(Float, nullable=True)+ avg_processing_rate = Column(Float, nullable=True)++ # Indexes+ __table_args__ = (+ Index("idx_benchmark_configs_name", "name"),+ Index("idx_benchmark_configs_hash", "config_hash"),+ Index("idx_benchmark_configs_default", "is_default"),+ {"extend_existing": True},+ )+++class BenchmarkProgress(Base):+ """Real-time progress tracking for benchmark runs."""++ __tablename__ = "benchmark_progress"++ id = Column(Integer, primary_key=True, index=True)++ # Foreign key+ benchmark_run_id = Column(+ Integer,+ ForeignKey("benchmark_runs.id", ondelete="CASCADE"),+ nullable=False,+ index=True,+ )++ # Progress data+ timestamp = Column(DateTime, server_default=func.now(), nullable=False)+ completed_examples = Column(Integer, nullable=False)+ total_examples = Column(Integer, nullable=False)++ # Accuracy tracking+ overall_accuracy = Column(Float, nullable=True)+ dataset_accuracies = Column(JSON, nullable=True) # Per-dataset accuracy++ # Performance metrics+ processing_rate = Column(Float, nullable=True) # Examples per minute+ estimated_completion = Column(DateTime, nullable=True)++ # Current status+ current_dataset = Column(Enum(DatasetType), nullable=True)+ current_example_id = Column(String(255), nullable=True)++ # Additional metrics+ memory_usage = Column(Float, nullable=True) # MB+ cpu_usage = Column(Float, nullable=True) # Percentage++ # Relationships+ benchmark_run = relationship(+ "BenchmarkRun", back_populates="progress_updates"+ )++ # Indexes for real-time queries+ __table_args__ = (+ Index(+ "idx_benchmark_progress_run_time", "benchmark_run_id", "timestamp"+ ),+ {"extend_existing": True},+ )diff --git a/src/local_deep_research/benchmarks/ui/__init__.py b/src/local_deep_research/benchmarks/ui/__init__.pynew file mode 100644index 0000000000..92190068ad--- /dev/null+++ b/src/local_deep_research/benchmarks/ui/__init__.py@@ -0,0 +1 @@+"""Benchmark UI components package."""diff --git a/src/local_deep_research/benchmarks/web_api/__init__.py b/src/local_deep_research/benchmarks/web_api/__init__.pynew file mode 100644index 0000000000..02cb0cd252--- /dev/null+++ b/src/local_deep_research/benchmarks/web_api/__init__.py@@ -0,0 +1,6 @@+"""Benchmark web API package."""++from .benchmark_service import BenchmarkService+from .benchmark_routes import benchmark_bp++__all__ = ["BenchmarkService", "benchmark_bp"]diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_routes.py b/src/local_deep_research/benchmarks/web_api/benchmark_routes.pynew file mode 100644index 0000000000..c0367ee16a--- /dev/null+++ b/src/local_deep_research/benchmarks/web_api/benchmark_routes.py@@ -0,0 +1,767 @@+"""Flask routes for benchmark web interface."""++import time+from flask import Blueprint, request, jsonify+from loguru import logger++from .benchmark_service import benchmark_service+from ...web.utils.templates import render_template_with_defaults+from ...web.services.settings_manager import SettingsManager+from ...utilities.db_utils import get_db_session++# Create blueprint for benchmark routes+benchmark_bp = Blueprint("benchmark", __name__, url_prefix="/benchmark")+++@benchmark_bp.route("/")+def index():+ """Benchmark dashboard page."""+ return render_template_with_defaults("pages/benchmark.html")+++@benchmark_bp.route("/results")+def results():+ """Benchmark results history page."""+ return render_template_with_defaults("pages/benchmark_results.html")+++@benchmark_bp.route("/api/start", methods=["POST"])+def start_benchmark():+ """Start a new benchmark run."""+ try:+ data = request.get_json()++ if not data:+ return jsonify({"error": "No data provided"}), 400++ # Extract configuration+ run_name = data.get("run_name")++ # Get search config from database instead of request+ from ...web.services.settings_manager import SettingsManager+ from ...utilities.db_utils import get_db_session++ session = get_db_session()+ settings_manager = SettingsManager(db_session=session)++ # Build search config from database settings+ search_config = {+ "iterations": int(+ settings_manager.get_setting("search.iterations", 8)+ ),+ "questions_per_iteration": int(+ settings_manager.get_setting(+ "search.questions_per_iteration", 5+ )+ ),+ "search_tool": settings_manager.get_setting(+ "search.tool", "searxng"+ ),+ "search_strategy": settings_manager.get_setting(+ "search.search_strategy", "focused_iteration"+ ),+ "model_name": settings_manager.get_setting("llm.model"),+ "provider": settings_manager.get_setting("llm.provider"),+ "temperature": float(+ settings_manager.get_setting("llm.temperature", 0.7)+ ),+ }++ # Add provider-specific settings+ provider = search_config.get("provider")+ if provider == "openai_endpoint":+ search_config["openai_endpoint_url"] = settings_manager.get_setting(+ "llm.openai_endpoint.url"+ )+ search_config["openai_endpoint_api_key"] = (+ settings_manager.get_setting("llm.openai_endpoint.api_key")+ )+ elif provider == "openai":+ search_config["openai_api_key"] = settings_manager.get_setting(+ "llm.openai.api_key"+ )+ elif provider == "anthropic":+ search_config["anthropic_api_key"] = settings_manager.get_setting(+ "llm.anthropic.api_key"+ )++ # Get evaluation config from request or use OpenRouter default with settings API key+ if "evaluation_config" in data:+ evaluation_config = data["evaluation_config"]+ else:+ # Use database settings for API key (already have settings_manager from above)+ openrouter_api_key = settings_manager.get_setting(+ "llm.openai_endpoint.api_key"+ )++ evaluation_config = {+ "provider": "openai_endpoint",+ "model_name": "anthropic/claude-3.7-sonnet",+ "openai_endpoint_url": "https://openrouter.ai/api/v1",+ "openai_endpoint_api_key": openrouter_api_key,+ "temperature": 0,+ }+ datasets_config = data.get("datasets_config", {})++ # Close database session+ session.close()++ # Validate datasets config+ if not datasets_config or not any(+ config.get("count", 0) > 0 for config in datasets_config.values()+ ):+ return jsonify(+ {+ "error": "At least one dataset with count > 0 must be specified"+ }+ ), 400++ # Create benchmark run+ benchmark_run_id = benchmark_service.create_benchmark_run(+ run_name=run_name,+ search_config=search_config,+ evaluation_config=evaluation_config,+ datasets_config=datasets_config,+ )++ # Start benchmark+ success = benchmark_service.start_benchmark(benchmark_run_id)++ if success:+ return jsonify(+ {+ "success": True,+ "benchmark_run_id": benchmark_run_id,+ "message": "Benchmark started successfully",+ }+ )+ else:+ return jsonify(+ {"success": False, "error": "Failed to start benchmark"}+ ), 500++ except Exception as e:+ logger.error(f"Error starting benchmark: {e}")+ return jsonify({"success": False, "error": str(e)}), 500+++@benchmark_bp.route("/api/running", methods=["GET"])+def get_running_benchmark():+ """Check if there's a running benchmark and return its ID."""+ try:+ from ...utilities.db_utils import get_db_session+ from ..models.benchmark_models import BenchmarkRun, BenchmarkStatus++ session = get_db_session()++ # Find any benchmark that's currently running+ running_benchmark = (+ session.query(BenchmarkRun)+ .filter(BenchmarkRun.status == BenchmarkStatus.IN_PROGRESS)+ .order_by(BenchmarkRun.created_at.desc())+ .first()+ )++ session.close()++ if running_benchmark:+ return jsonify(+ {+ "success": True,+ "benchmark_run_id": running_benchmark.id,+ "run_name": running_benchmark.run_name,+ "total_examples": running_benchmark.total_examples,+ "completed_examples": running_benchmark.completed_examples,+ }+ )+ else:+ return jsonify(+ {"success": False, "message": "No running benchmark found"}+ )++ except Exception as e:+ logger.error(f"Error checking for running benchmark: {e}")+ return jsonify({"success": False, "error": str(e)}), 500+++@benchmark_bp.route("/api/status/<int:benchmark_run_id>", methods=["GET"])+def get_benchmark_status(benchmark_run_id: int):+ """Get status of a benchmark run."""+ try:+ status = benchmark_service.get_benchmark_status(benchmark_run_id)++ if status:+ return jsonify({"success": True, "status": status})+ else:+ return jsonify(+ {"success": False, "error": "Benchmark run not found"}+ ), 404++ except Exception as e:+ logger.error(f"Error getting benchmark status: {e}")+ return jsonify({"success": False, "error": str(e)}), 500+++@benchmark_bp.route("/api/cancel/<int:benchmark_run_id>", methods=["POST"])+def cancel_benchmark(benchmark_run_id: int):+ """Cancel a running benchmark."""+ try:+ success = benchmark_service.cancel_benchmark(benchmark_run_id)++ if success:+ return jsonify(+ {"success": True, "message": "Benchmark cancelled successfully"}+ )+ else:+ return jsonify(+ {"success": False, "error": "Failed to cancel benchmark"}+ ), 500++ except Exception as e:+ logger.error(f"Error cancelling benchmark: {e}")+ return jsonify({"success": False, "error": str(e)}), 500+++@benchmark_bp.route("/api/history", methods=["GET"])+def get_benchmark_history():+ """Get list of recent benchmark runs."""+ try:+ from ...utilities.db_utils import get_db_session+ from ..models.benchmark_models import BenchmarkRun++ session = get_db_session()++ # Get all benchmark runs (completed, failed, cancelled, or in-progress)+ runs = (+ session.query(BenchmarkRun)+ .order_by(BenchmarkRun.created_at.desc())+ .limit(50)+ .all()+ )++ # Format runs for display+ formatted_runs = []+ for run in runs:+ # Calculate average processing time from results+ avg_processing_time = None+ avg_search_results = None+ try:+ from ..models.benchmark_models import BenchmarkResult+ from sqlalchemy import func++ avg_result = (+ session.query(func.avg(BenchmarkResult.processing_time))+ .filter(+ BenchmarkResult.benchmark_run_id == run.id,+ BenchmarkResult.processing_time.isnot(None),+ BenchmarkResult.processing_time > 0,+ )+ .scalar()+ )++ if avg_result:+ avg_processing_time = float(avg_result)+ except Exception as e:+ logger.warning(+ f"Error calculating avg processing time for run {run.id}: {e}"+ )++ # Calculate average search results and total search requests from metrics+ total_search_requests = None+ try:+ from ...metrics.search_tracker import get_search_tracker+ from ...metrics.db_models import SearchCall++ # Get all results for this run to find research_ids+ results = (+ session.query(BenchmarkResult)+ .filter(BenchmarkResult.benchmark_run_id == run.id)+ .all()+ )++ research_ids = [r.research_id for r in results if r.research_id]++ if research_ids:+ tracker = get_search_tracker()+ with tracker.db.get_session() as metric_session:+ # Get all search calls for these research_ids+ search_calls = (+ metric_session.query(SearchCall)+ .filter(SearchCall.research_id.in_(research_ids))+ .all()+ )++ # Group by research_id and calculate metrics per research session+ research_results = {}+ research_requests = {}++ for call in search_calls:+ if call.research_id:+ if call.research_id not in research_results:+ research_results[call.research_id] = 0+ research_requests[call.research_id] = 0+ research_results[call.research_id] += (+ call.results_count or 0+ )+ research_requests[call.research_id] += 1++ # Calculate averages across research sessions+ if research_results:+ total_results = sum(research_results.values())+ avg_search_results = total_results / len(+ research_results+ )++ total_requests = sum(research_requests.values())+ total_search_requests = total_requests / len(+ research_requests+ )++ except Exception as e:+ logger.warning(+ f"Error calculating search metrics for run {run.id}: {e}"+ )++ formatted_runs.append(+ {+ "id": run.id,+ "run_name": run.run_name or f"Benchmark #{run.id}",+ "created_at": run.created_at.isoformat(),+ "total_examples": run.total_examples,+ "completed_examples": run.completed_examples,+ "overall_accuracy": run.overall_accuracy,+ "status": run.status.value,+ "search_config": run.search_config,+ "evaluation_config": run.evaluation_config,+ "datasets_config": run.datasets_config,+ "avg_processing_time": avg_processing_time,+ "avg_search_results": avg_search_results,+ "total_search_requests": total_search_requests,+ }+ )++ session.close()++ return jsonify({"success": True, "runs": formatted_runs})++ except Exception as e:+ logger.error(f"Error getting benchmark history: {e}")+ return jsonify({"success": False, "error": str(e)}), 500+++@benchmark_bp.route("/api/results/<int:benchmark_run_id>", methods=["GET"])+def get_benchmark_results(benchmark_run_id: int):+ """Get detailed results for a benchmark run."""+ try:+ from ...utilities.db_utils import get_db_session+ from ..models.benchmark_models import BenchmarkResult++ logger.info(f"Getting results for benchmark {benchmark_run_id}")+ session = get_db_session()++ # Get recent results (limit to last 10)+ limit = int(request.args.get("limit", 10))++ results = (+ session.query(BenchmarkResult)+ .filter(BenchmarkResult.benchmark_run_id == benchmark_run_id)+ # Temporarily show all results including pending evaluations+ # .filter(+ # BenchmarkResult.is_correct.isnot(None)+ # ) # Only completed evaluations+ .order_by(BenchmarkResult.id.desc()) # Most recent first+ .limit(limit)+ .all()+ )++ logger.info(f"Found {len(results)} results")++ # Build a map of research_id to total search results+ search_results_by_research_id = {}+ try:+ from ...metrics.search_tracker import get_search_tracker+ from ...metrics.db_models import SearchCall++ tracker = get_search_tracker()++ # Get all unique research_ids from our results+ research_ids = [r.research_id for r in results if r.research_id]++ if research_ids:+ with tracker.db.get_session() as metric_session:+ # Get all search calls for these research_ids+ all_search_calls = (+ metric_session.query(SearchCall)+ .filter(SearchCall.research_id.in_(research_ids))+ .all()+ )++ # Group search results by research_id+ for call in all_search_calls:+ if call.research_id:+ if (+ call.research_id+ not in search_results_by_research_id+ ):+ search_results_by_research_id[+ call.research_id+ ] = 0+ search_results_by_research_id[call.research_id] += (+ call.results_count or 0+ )++ logger.info(+ f"Found search metrics for {len(search_results_by_research_id)} research IDs from {len(all_search_calls)} total search calls"+ )+ except Exception as e:+ logger.error(+ f"Error getting search metrics for benchmark {benchmark_run_id}: {e}"+ )++ # Format results for UI display+ formatted_results = []+ for result in results:+ # Get search result count using research_id+ search_result_count = 0++ try:+ if (+ result.research_id+ and result.research_id in search_results_by_research_id+ ):+ search_result_count = search_results_by_research_id[+ result.research_id+ ]+ logger.debug(+ f"Found {search_result_count} search results for research_id {result.research_id}"+ )++ except Exception as e:+ logger.error(+ f"Error getting search results for result {result.example_id}: {e}"+ )++ # Fallback to sources if available and we didn't find metrics+ if search_result_count == 0 and result.sources:+ try:+ if isinstance(result.sources, list):+ search_result_count = len(result.sources)+ elif (+ isinstance(result.sources, dict)+ and "all_links_of_system" in result.sources+ ):+ search_result_count = len(+ result.sources["all_links_of_system"]+ )+ except:+ pass++ formatted_results.append(+ {+ "example_id": result.example_id,+ "dataset_type": result.dataset_type.value,+ "question": result.question,+ "correct_answer": result.correct_answer,+ "model_answer": result.extracted_answer,+ "full_response": result.response,+ "is_correct": result.is_correct,+ "confidence": result.confidence,+ "grader_response": result.grader_response,+ "processing_time": result.processing_time,+ "search_result_count": search_result_count,+ "sources": result.sources,+ "completed_at": result.completed_at.isoformat()+ if result.completed_at+ else None,+ }+ )++ session.close()++ return jsonify({"success": True, "results": formatted_results})++ except Exception as e:+ logger.error(f"Error getting benchmark results: {e}")+ return jsonify({"success": False, "error": str(e)}), 500+++@benchmark_bp.route("/api/configs", methods=["GET"])+def get_saved_configs():+ """Get list of saved benchmark configurations."""+ try:+ # TODO: Implement saved configs retrieval from database+ # For now return default configs+ default_configs = [+ {+ "id": 1,+ "name": "Quick Test",+ "description": "Fast benchmark with minimal examples",+ "search_config": {+ "iterations": 3,+ "questions_per_iteration": 3,+ "search_tool": "searxng",+ "search_strategy": "focused_iteration",+ },+ "datasets_config": {+ "simpleqa": {"count": 10},+ "browsecomp": {"count": 5},+ },+ },+ {+ "id": 2,+ "name": "Standard Evaluation",+ "description": "Comprehensive benchmark with standard settings",+ "search_config": {+ "iterations": 8,+ "questions_per_iteration": 5,+ "search_tool": "searxng",+ "search_strategy": "focused_iteration",+ },+ "datasets_config": {+ "simpleqa": {"count": 50},+ "browsecomp": {"count": 25},+ },+ },+ ]++ return jsonify({"success": True, "configs": default_configs})++ except Exception as e:+ logger.error(f"Error getting saved configs: {e}")+ return jsonify({"success": False, "error": str(e)}), 500+++@benchmark_bp.route("/api/start-simple", methods=["POST"])+def start_benchmark_simple():+ """Start a benchmark using current database settings."""+ try:+ data = request.get_json()+ datasets_config = data.get("datasets_config", {})++ # Validate datasets+ if not datasets_config or not any(+ config.get("count", 0) > 0 for config in datasets_config.values()+ ):+ return jsonify(+ {+ "error": "At least one dataset with count > 0 must be specified"+ }+ ), 400++ # Get current settings from database+ session = get_db_session()+ settings_manager = SettingsManager(db_session=session)++ # Build search config from database settings+ search_config = {+ "iterations": int(+ settings_manager.get_setting("search.iterations", 8)+ ),+ "questions_per_iteration": int(+ settings_manager.get_setting(+ "search.questions_per_iteration", 5+ )+ ),+ "search_tool": settings_manager.get_setting(+ "search.tool", "searxng"+ ),+ "search_strategy": settings_manager.get_setting(+ "search.search_strategy", "focused_iteration"+ ),+ "model_name": settings_manager.get_setting("llm.model"),+ "provider": settings_manager.get_setting("llm.provider"),+ "temperature": float(+ settings_manager.get_setting("llm.temperature", 0.7)+ ),+ }++ # Add provider-specific settings+ provider = search_config.get("provider")+ if provider == "openai_endpoint":+ search_config["openai_endpoint_url"] = settings_manager.get_setting(+ "llm.openai_endpoint.url"+ )+ search_config["openai_endpoint_api_key"] = (+ settings_manager.get_setting("llm.openai_endpoint.api_key")+ )+ elif provider == "openai":+ search_config["openai_api_key"] = settings_manager.get_setting(+ "llm.openai.api_key"+ )+ elif provider == "anthropic":+ search_config["anthropic_api_key"] = settings_manager.get_setting(+ "llm.anthropic.api_key"+ )++ session.close()++ # Use OpenRouter with Claude 3.7 Sonnet for evaluation (get API key from settings)+ openrouter_api_key = settings_manager.get_setting(+ "llm.openai_endpoint.api_key"+ )+ evaluation_config = {+ "provider": "openai_endpoint",+ "model_name": "anthropic/claude-3.7-sonnet",+ "openai_endpoint_url": "https://openrouter.ai/api/v1",+ "openai_endpoint_api_key": openrouter_api_key,+ "temperature": 0,+ }++ # Create and start benchmark+ benchmark_run_id = benchmark_service.create_benchmark_run(+ run_name=f"Quick Benchmark - {data.get('run_name', '')}",+ search_config=search_config,+ evaluation_config=evaluation_config,+ datasets_config=datasets_config,+ )++ success = benchmark_service.start_benchmark(benchmark_run_id)++ if success:+ return jsonify(+ {+ "success": True,+ "benchmark_run_id": benchmark_run_id,+ "message": "Benchmark started with current settings",+ }+ )+ else:+ return jsonify(+ {"success": False, "error": "Failed to start benchmark"}+ ), 500++ except Exception as e:+ logger.error(f"Error starting simple benchmark: {e}")+ return jsonify({"success": False, "error": str(e)}), 500+++@benchmark_bp.route("/api/validate-config", methods=["POST"])+def validate_config():+ """Validate a benchmark configuration."""+ try:+ data = request.get_json()++ if not data:+ return jsonify({"valid": False, "errors": ["No data provided"]})++ errors = []++ # Validate search config+ search_config = data.get("search_config", {})+ if not search_config.get("search_tool"):+ errors.append("Search tool is required")+ if not search_config.get("search_strategy"):+ errors.append("Search strategy is required")++ # Validate datasets config+ datasets_config = data.get("datasets_config", {})+ if not datasets_config:+ errors.append("At least one dataset must be configured")++ total_examples = sum(+ config.get("count", 0) for config in datasets_config.values()+ )+ if total_examples == 0:+ errors.append("Total examples must be greater than 0")++ if total_examples > 1000:+ errors.append(+ "Total examples should not exceed 1000 for web interface"+ )++ return jsonify(+ {+ "valid": len(errors) == 0,+ "errors": errors,+ "total_examples": total_examples,+ }+ )++ except Exception as e:+ logger.error(f"Error validating config: {e}")+ return jsonify({"valid": False, "errors": [str(e)]}), 500+++@benchmark_bp.route("/api/search-quality", methods=["GET"])+def get_search_quality():+ """Get current search quality metrics from rate limiting tracker."""+ try:+ from ...web_search_engines.rate_limiting import get_tracker++ tracker = get_tracker()+ quality_stats = tracker.get_search_quality_stats()++ return jsonify(+ {+ "success": True,+ "search_quality": quality_stats,+ "timestamp": time.time(),+ }+ )++ except Exception as e:+ logger.error(f"Error getting search quality: {e}")+ return jsonify({"success": False, "error": str(e)}), 500+++@benchmark_bp.route("/api/delete/<int:benchmark_run_id>", methods=["DELETE"])+def delete_benchmark_run(benchmark_run_id: int):+ """Delete a benchmark run and all its results."""+ try:+ from ...utilities.db_utils import get_db_session+ from ..models.benchmark_models import (+ BenchmarkRun,+ BenchmarkResult,+ BenchmarkProgress,+ )++ session = get_db_session()++ # Check if benchmark run exists+ benchmark_run = (+ session.query(BenchmarkRun)+ .filter(BenchmarkRun.id == benchmark_run_id)+ .first()+ )++ if not benchmark_run:+ session.close()+ return jsonify(+ {"success": False, "error": "Benchmark run not found"}+ ), 404++ # Prevent deletion of running benchmarks+ if benchmark_run.status.value == "in_progress":+ session.close()+ return jsonify(+ {+ "success": False,+ "error": "Cannot delete a running benchmark. Cancel it first.",+ }+ ), 400++ # Delete related records (cascade should handle this, but being explicit)+ session.query(BenchmarkResult).filter(+ BenchmarkResult.benchmark_run_id == benchmark_run_id+ ).delete()++ session.query(BenchmarkProgress).filter(+ BenchmarkProgress.benchmark_run_id == benchmark_run_id+ ).delete()++ # Delete the benchmark run+ session.delete(benchmark_run)+ session.commit()+ session.close()++ logger.info(f"Deleted benchmark run {benchmark_run_id}")+ return jsonify(+ {+ "success": True,+ "message": f"Benchmark run {benchmark_run_id} deleted successfully",+ }+ )++ except Exception as e:+ logger.error(f"Error deleting benchmark run {benchmark_run_id}: {e}")+ return jsonify({"success": False, "error": str(e)}), 500diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_service.py b/src/local_deep_research/benchmarks/web_api/benchmark_service.pynew file mode 100644index 0000000000..7546903bb4--- /dev/null+++ b/src/local_deep_research/benchmarks/web_api/benchmark_service.py@@ -0,0 +1,922 @@+"""Benchmark service for handling web-based benchmark execution."""++import hashlib+import json+import threading+import time+from datetime import datetime+from typing import Dict, List, Optional, Any++from loguru import logger++from ..models.benchmark_models import (+ BenchmarkRun,+ BenchmarkResult,+ BenchmarkStatus,+ DatasetType,+)+from ..datasets import load_dataset+from ..graders import extract_answer_from_response, grade_single_result+from ..runners import format_query+from ...api.research_functions import quick_summary+from ...utilities.db_utils import get_db_session+from ...web.services.socket_service import SocketIOService+++class BenchmarkService:+ """Service for managing benchmark runs through the web interface."""++ def __init__(self, socket_service=None):+ self.active_runs: Dict[int, Dict] = {}+ self.socket_service = socket_service or self._get_socket_service()+ self.rate_limit_detected: Dict[+ int, bool+ ] = {} # Track rate limiting per benchmark run++ def _get_socket_service(self):+ """Get socket service instance, handling cases where Flask app is not available."""+ try:+ return SocketIOService()+ except Exception:+ # Return a mock socket service for testing/standalone use+ class MockSocketService:+ def emit_to_room(self, room, event, data):+ pass++ return MockSocketService()++ def generate_config_hash(self, search_config: Dict[str, Any]) -> str:+ """Generate a hash for search configuration compatibility checking."""+ relevant_params = {+ "iterations": search_config.get("iterations"),+ "questions_per_iteration": search_config.get(+ "questions_per_iteration"+ ),+ "search_tool": search_config.get("search_tool"),+ "search_strategy": search_config.get("search_strategy"),+ "model_name": search_config.get("model_name"),+ "provider": search_config.get("provider"),+ }+ # Remove None values+ relevant_params = {+ k: v for k, v in relevant_params.items() if v is not None+ }+ config_str = json.dumps(relevant_params, sort_keys=True)+ return hashlib.md5(config_str.encode()).hexdigest()[:8]++ def generate_query_hash(self, question: str, dataset_type: str) -> str:+ """Generate a hash for a query to enable deduplication."""+ query_content = f"{question.strip()}|{dataset_type.lower()}"+ return hashlib.md5(query_content.encode()).hexdigest()++ def create_benchmark_run(+ self,+ run_name: Optional[str],+ search_config: Dict[str, Any],+ evaluation_config: Dict[str, Any],+ datasets_config: Dict[str, Dict],+ ) -> int:+ """Create a new benchmark run in the database."""+ session = get_db_session()++ try:+ config_hash = self.generate_config_hash(search_config)++ # Calculate total examples+ total_examples = sum(+ config.get("count", 0) for config in datasets_config.values()+ )++ benchmark_run = BenchmarkRun(+ run_name=run_name,+ config_hash=config_hash,+ query_hash_list=[], # Will be populated as we process+ search_config=search_config,+ evaluation_config=evaluation_config,+ datasets_config=datasets_config,+ total_examples=total_examples,+ status=BenchmarkStatus.PENDING,+ )++ session.add(benchmark_run)+ session.commit()++ logger.info(+ f"Created benchmark run {benchmark_run.id} with config hash {config_hash}"+ )+ return benchmark_run.id++ except Exception as e:+ session.rollback()+ logger.error(f"Error creating benchmark run: {e}")+ raise+ finally:+ session.close()++ def get_existing_results(self, config_hash: str) -> Dict[str, Dict]:+ """Get existing results with compatible configuration."""+ session = get_db_session()++ try:+ # Find compatible runs+ compatible_runs = (+ session.query(BenchmarkRun)+ .filter(BenchmarkRun.config_hash == config_hash)+ .filter(BenchmarkRun.status == BenchmarkStatus.COMPLETED)+ .all()+ )++ existing_results = {}+ for run in compatible_runs:+ results = (+ session.query(BenchmarkResult)+ .filter(BenchmarkResult.benchmark_run_id == run.id)+ .filter(+ BenchmarkResult.is_correct.isnot(None)+ ) # Only completed evaluations+ .all()+ )++ for result in results:+ existing_results[result.query_hash] = {+ "id": result.example_id,+ "dataset_type": result.dataset_type.value,+ "problem": result.question,+ "correct_answer": result.correct_answer,+ "response": result.response,+ "extracted_answer": result.extracted_answer,+ "confidence": result.confidence,+ "processing_time": result.processing_time,+ "sources": result.sources,+ "is_correct": result.is_correct,+ "graded_confidence": result.graded_confidence,+ "grader_response": result.grader_response,+ "query_hash": result.query_hash,+ }++ logger.info(+ f"Found {len(existing_results)} existing results for config hash {config_hash}"+ )+ return existing_results++ except Exception as e:+ logger.error(f"Error loading existing results: {e}")+ return {}+ finally:+ session.close()++ def start_benchmark(self, benchmark_run_id: int) -> bool:+ """Start a benchmark run in a background thread."""+ try:+ # Mark as in progress+ self.update_benchmark_status(+ benchmark_run_id, BenchmarkStatus.IN_PROGRESS+ )++ # Start background thread+ thread = threading.Thread(+ target=self._run_benchmark_thread,+ args=(benchmark_run_id,),+ daemon=True,+ )+ thread.start()++ self.active_runs[benchmark_run_id] = {+ "thread": thread,+ "start_time": datetime.now(),+ "status": "running",+ }++ logger.info(f"Started benchmark run {benchmark_run_id}")+ return True++ except Exception as e:+ logger.error(f"Error starting benchmark {benchmark_run_id}: {e}")+ self.update_benchmark_status(+ benchmark_run_id, BenchmarkStatus.FAILED, str(e)+ )+ return False++ def _run_benchmark_thread(self, benchmark_run_id: int):+ """Main benchmark execution thread."""+ session = get_db_session()++ try:+ # Get benchmark run details+ benchmark_run = (+ session.query(BenchmarkRun)+ .filter(BenchmarkRun.id == benchmark_run_id)+ .first()+ )+ if not benchmark_run:+ raise ValueError(f"Benchmark run {benchmark_run_id} not found")++ # Load existing results for deduplication+ existing_results = self.get_existing_results(+ benchmark_run.config_hash+ )++ # Create task queue+ task_queue = self._create_task_queue(+ benchmark_run.datasets_config,+ existing_results,+ benchmark_run_id,+ )++ # Update total with new tasks only+ benchmark_run.total_examples = len(task_queue) + len(+ existing_results+ )+ benchmark_run.completed_examples = len(existing_results)+ benchmark_run.start_time = datetime.now()+ session.commit()++ # Process tasks+ for i, task in enumerate(task_queue):+ try:+ # Process single task+ result = self._process_benchmark_task(+ task,+ benchmark_run.search_config,+ benchmark_run.evaluation_config,+ )++ # Save result+ self._save_benchmark_result(result, benchmark_run_id)++ # Update progress+ benchmark_run.completed_examples += 1+ session.commit()++ # Send real-time update+ self._send_progress_update(+ benchmark_run_id,+ benchmark_run.completed_examples,+ benchmark_run.total_examples,+ )++ except Exception as e:+ logger.error(f"Error processing task {i}: {e}")+ benchmark_run.failed_examples += 1+ session.commit()++ # Check if this is a rate limiting error+ error_str = str(e).lower()+ if (+ "403" in error_str+ or "rate limit" in error_str+ or "forbidden" in error_str+ ):+ self.rate_limit_detected[benchmark_run_id] = True+ # Send rate limit warning via WebSocket+ self.socket_service.emit_to_subscribers(+ "research_progress",+ benchmark_run_id,+ {+ "rate_limit_detected": True,+ "message": "SearXNG rate limiting detected",+ },+ )++ # Mark as completed+ benchmark_run.end_time = datetime.now()+ benchmark_run.status = BenchmarkStatus.COMPLETED++ # Calculate final accuracy+ self._calculate_final_accuracy(benchmark_run_id)+ session.commit()++ # Send completion notification+ self.socket_service.emit_to_subscribers(+ "research_progress",+ benchmark_run_id,+ {+ "status": "completed",+ "message": "Benchmark completed successfully",+ "progress": 100,+ "benchmark_run_id": benchmark_run_id,+ },+ )++ except Exception as e:+ logger.error(f"Benchmark run {benchmark_run_id} failed: {e}")+ self.update_benchmark_status(+ benchmark_run_id, BenchmarkStatus.FAILED, str(e)+ )+ finally:+ session.close()+ if benchmark_run_id in self.active_runs:+ del self.active_runs[benchmark_run_id]++ def _create_task_queue(+ self,+ datasets_config: Dict,+ existing_results: Dict,+ benchmark_run_id: int,+ ) -> List[Dict]:+ """Create list of tasks to process, excluding existing results."""+ tasks = []++ for dataset_name, config in datasets_config.items():+ if config.get("count", 0) > 0:+ dataset = load_dataset(+ dataset_type=dataset_name,+ num_examples=config["count"],+ seed=None,+ )++ for i, example in enumerate(dataset):+ # Extract question based on dataset type+ if dataset_name.lower() == "simpleqa":+ question = example.get("problem", "")+ correct_answer = example.get("answer", "")+ else: # browsecomp+ question = example.get("question", "")+ correct_answer = example.get("answer", "")++ # Generate query hash+ query_hash = self.generate_query_hash(+ question, dataset_name+ )++ # Skip if already processed+ if query_hash in existing_results:+ continue++ tasks.append(+ {+ "benchmark_run_id": benchmark_run_id,+ "example_id": example.get("id", f"example_{i}"),+ "dataset_type": dataset_name,+ "question": question,+ "correct_answer": correct_answer,+ "query_hash": query_hash,+ "task_index": len(tasks),+ }+ )++ return tasks++ def _process_benchmark_task(+ self, task: Dict, search_config: Dict, evaluation_config: Dict+ ) -> Dict:+ """Process a single benchmark task."""+ try:+ # Generate a unique tracking ID for this benchmark task+ import uuid++ tracking_id = str(uuid.uuid4())++ # Format query+ formatted_query = format_query(+ task["question"], task["dataset_type"]+ )++ # Run research with progress callback for WebSocket updates+ start_time = time.time()++ def benchmark_progress_callback(+ status: str, progress: int, data: dict+ ):+ """Progress callback to emit detailed research progress via WebSocket"""+ try:+ timestamp = datetime.now().isoformat()++ # Create research-compatible log entry+ log_entry = {+ "time": timestamp,+ "message": f"Example {task['example_id']}: {status}",+ "progress": progress,+ "metadata": {+ "phase": data.get("phase", "benchmark_processing"),+ "type": data.get("type", "info"),+ "example_id": task["example_id"],+ "benchmark_run_id": task["benchmark_run_id"],+ **data, # Include all other data+ },+ }++ # Determine log type based on status/message content+ if (+ "complete" in status.lower()+ or "finished" in status.lower()+ ):+ log_entry["metadata"]["type"] = "milestone"+ elif (+ "error" in status.lower() or "failed" in status.lower()+ ):+ log_entry["metadata"]["type"] = "error"+ elif (+ "starting" in status.lower()+ or "begin" in status.lower()+ ):+ log_entry["metadata"]["type"] = "milestone"++ # Create progress data in research format+ progress_data = {+ "progress": progress,+ "message": status,+ "status": "in_progress",+ "log_entry": log_entry,+ "progress_log": json.dumps(+ [log_entry]+ ), # Array format expected by socket.js+ }++ # Emit using research_progress format that the UI expects+ self.socket_service.emit_to_subscribers(+ "research_progress",+ task["benchmark_run_id"],+ progress_data,+ )++ except Exception as e:+ logger.error(+ f"Error sending benchmark progress update: {e}"+ )++ search_result = quick_summary(+ query=formatted_query,+ research_id=tracking_id, # Pass the tracking ID+ iterations=search_config.get("iterations", 8),+ questions_per_iteration=search_config.get(+ "questions_per_iteration", 5+ ),+ search_tool=search_config.get("search_tool", "searxng"),+ search_strategy=search_config.get(+ "search_strategy", "focused_iteration"+ ),+ progress_callback=benchmark_progress_callback,+ )+ processing_time = time.time() - start_time++ # Extract answer+ response = search_result.get("summary", "")+ extracted_data = extract_answer_from_response(+ response, task["dataset_type"]+ )+ extracted_answer = (+ extracted_data.get("extracted_answer", "")+ if isinstance(extracted_data, dict)+ else str(extracted_data)+ )++ # Extract sources - handle both direct sources and all_links_of_system+ sources = search_result.get("sources", [])+ if not sources and "all_links_of_system" in search_result:+ sources = search_result.get("all_links_of_system", [])++ # Log for debugging+ logger.debug(f"Search result keys: {list(search_result.keys())}")+ logger.debug(f"Sources found: {len(sources)} items")++ # Prepare result+ result = {+ **task,+ "response": response,+ "extracted_answer": extracted_answer,+ "confidence": str(+ extracted_data.get("confidence", "100")+ if isinstance(extracted_data, dict)+ else "100"+ ),+ "processing_time": processing_time,+ "sources": json.dumps(sources), # Convert to JSON string+ "completed_at": datetime.now(),+ "research_id": tracking_id, # Store the UUID in the research_id field+ }++ # Evaluate result - requires proper grading model+ try:+ # Check if we have a proper evaluation model configured+ eval_provider = evaluation_config.get("provider", "").lower()+ eval_model = evaluation_config.get("model_name", "")++ if (+ eval_provider in ["ollama", "local"]+ or "gemma" in eval_model.lower()+ ):+ # Local models are not reliable enough for grading+ result.update(+ {+ "is_correct": None,+ "graded_confidence": "0",+ "grader_response": "🔑 Evaluation requires OpenRouter API key. Set llm.openai_endpoint.api_key in database settings to use Claude 3.7 Sonnet for accurate grading via OpenRouter.",+ "evaluation_error": "Local models not suitable for grading",+ }+ )+ else:+ # Try to evaluate with proper model+ result_data = {+ "id": task["example_id"],+ "problem": task["question"],+ "correct_answer": task["correct_answer"],+ "response": response,+ "extracted_answer": extracted_answer,+ }++ eval_result = grade_single_result(+ result_data, task["dataset_type"], evaluation_config+ )+ if eval_result and not eval_result.get("grading_error"):+ result.update(+ {+ "is_correct": eval_result.get(+ "is_correct", False+ ),+ "graded_confidence": eval_result.get(+ "graded_confidence", "0"+ ),+ "grader_response": eval_result.get(+ "grader_response", ""+ ),+ }+ )+ else:+ error_msg = (+ eval_result.get(+ "grading_error", "Unknown evaluation error"+ )+ if eval_result+ else "No evaluation results returned"+ )+ result.update(+ {+ "is_correct": None,+ "graded_confidence": "0",+ "grader_response": f"🔑 Evaluation failed: {error_msg}. Set llm.openai_endpoint.api_key in database settings to use Claude 3.7 Sonnet via OpenRouter.",+ "evaluation_error": error_msg,+ }+ )++ except Exception as e:+ logger.error(f"Evaluation error: {e}")+ result.update(+ {+ "is_correct": None,+ "graded_confidence": "0",+ "grader_response": f"🔑 Evaluation failed: {str(e)}. Set llm.openai_endpoint.api_key in database settings to use Claude 3.7 Sonnet via OpenRouter.",+ "evaluation_error": str(e),+ }+ )++ return result++ except Exception as e:+ logger.error(f"Research error: {e}")+ return {+ **task,+ "research_error": str(e),+ "completed_at": datetime.now(),+ }++ def _save_benchmark_result(self, result: Dict, benchmark_run_id: int):+ """Save benchmark result to database."""+ session = get_db_session()++ try:+ benchmark_result = BenchmarkResult(+ benchmark_run_id=benchmark_run_id,+ example_id=result["example_id"],+ query_hash=result["query_hash"],+ dataset_type=DatasetType(result["dataset_type"]),+ research_id=result.get(+ "research_id"+ ), # Include the research_id (UUID)+ question=result["question"],+ correct_answer=result["correct_answer"],+ response=result.get("response"),+ extracted_answer=result.get("extracted_answer"),+ confidence=result.get("confidence"),+ processing_time=result.get("processing_time"),+ sources=result.get("sources"),+ is_correct=result.get("is_correct"),+ graded_confidence=result.get("graded_confidence"),+ grader_response=result.get("grader_response"),+ completed_at=result.get("completed_at"),+ research_error=result.get("research_error"),+ evaluation_error=result.get("evaluation_error"),+ task_index=result.get("task_index"),+ )++ session.add(benchmark_result)+ session.commit()++ except Exception as e:+ session.rollback()+ logger.error(f"Error saving benchmark result: {e}")+ raise+ finally:+ session.close()++ def _send_progress_update(+ self, benchmark_run_id: int, completed: int, total: int+ ):+ """Send real-time progress update via websocket."""+ try:+ percentage = (completed / total * 100) if total > 0 else 0++ # Create log entry for milestone progress+ log_entry = {+ "time": datetime.now().isoformat(),+ "message": f"Completed {completed}/{total} examples ({percentage:.1f}%)",+ "progress": percentage,+ "metadata": {+ "phase": "benchmark_progress",+ "type": "milestone",+ "completed": completed,+ "total": total,+ "benchmark_run_id": benchmark_run_id,+ },+ }++ progress_data = {+ "status": "in_progress",+ "message": f"Processing examples: {completed}/{total}",+ "progress": percentage,+ "completed": completed,+ "total": total,+ "benchmark_run_id": benchmark_run_id,+ "log_entry": log_entry,+ "progress_log": json.dumps([log_entry]),+ }++ self.socket_service.emit_to_subscribers(+ "research_progress", benchmark_run_id, progress_data+ )++ except Exception as e:+ logger.error(f"Error sending progress update: {e}")++ def _calculate_final_accuracy(self, benchmark_run_id: int):+ """Calculate and save final accuracy metrics."""+ session = get_db_session()++ try:+ # Get all results for this run+ results = (+ session.query(BenchmarkResult)+ .filter(BenchmarkResult.benchmark_run_id == benchmark_run_id)+ .filter(BenchmarkResult.is_correct.isnot(None))+ .all()+ )++ if results:+ correct_count = sum(1 for r in results if r.is_correct)+ overall_accuracy = (correct_count / len(results)) * 100++ # Calculate processing rate+ total_time = sum(r.processing_time or 0 for r in results)+ processing_rate = (+ (len(results) / (total_time / 60)) if total_time > 0 else 0+ )++ # Update benchmark run+ benchmark_run = (+ session.query(BenchmarkRun)+ .filter(BenchmarkRun.id == benchmark_run_id)+ .first()+ )+ if benchmark_run:+ benchmark_run.overall_accuracy = overall_accuracy+ benchmark_run.processing_rate = processing_rate+ session.commit()++ except Exception as e:+ logger.error(f"Error calculating final accuracy: {e}")+ finally:+ session.close()++ def update_benchmark_status(+ self,+ benchmark_run_id: int,+ status: BenchmarkStatus,+ error_message: str = None,+ ):+ """Update benchmark run status."""+ session = get_db_session()++ try:+ benchmark_run = (+ session.query(BenchmarkRun)+ .filter(BenchmarkRun.id == benchmark_run_id)+ .first()+ )+ if benchmark_run:+ benchmark_run.status = status+ benchmark_run.updated_at = datetime.now()++ if error_message:+ benchmark_run.error_message = error_message++ if (+ status == BenchmarkStatus.IN_PROGRESS+ and not benchmark_run.start_time+ ):+ benchmark_run.start_time = datetime.now()+ elif (+ status+ in [BenchmarkStatus.COMPLETED, BenchmarkStatus.FAILED]+ and not benchmark_run.end_time+ ):+ benchmark_run.end_time = datetime.now()++ session.commit()++ except Exception as e:+ session.rollback()+ logger.error(f"Error updating benchmark status: {e}")+ finally:+ session.close()++ def get_benchmark_status(self, benchmark_run_id: int) -> Optional[Dict]:+ """Get current status of a benchmark run."""+ session = get_db_session()++ try:+ benchmark_run = (+ session.query(BenchmarkRun)+ .filter(BenchmarkRun.id == benchmark_run_id)+ .first()+ )+ if not benchmark_run:+ return None++ # Calculate running accuracy from current results AND reused results from compatible runs+ # First get results specifically for this benchmark run+ current_results = (+ session.query(BenchmarkResult)+ .filter(BenchmarkResult.benchmark_run_id == benchmark_run_id)+ .filter(BenchmarkResult.is_correct.isnot(None))+ .all()+ )++ # Then get reused results from compatible benchmark runs (same config hash)+ # Only count results up to the number we say we've "completed"+ if benchmark_run.completed_examples > len(current_results):+ # We have reused results, get them from compatible runs+ reused_count_needed = benchmark_run.completed_examples - len(+ current_results+ )++ compatible_results = (+ session.query(BenchmarkResult)+ .join(+ BenchmarkRun,+ BenchmarkResult.benchmark_run_id == BenchmarkRun.id,+ )+ .filter(+ BenchmarkRun.config_hash == benchmark_run.config_hash+ )+ .filter(+ BenchmarkRun.id != benchmark_run_id+ ) # Exclude current run+ .filter(BenchmarkRun.status == BenchmarkStatus.COMPLETED)+ .filter(BenchmarkResult.is_correct.isnot(None))+ .order_by(BenchmarkResult.id) # Consistent ordering+ .limit(reused_count_needed)+ .all()+ )++ # Combine current and reused results+ results = (+ current_results + compatible_results[:reused_count_needed]+ )+ else:+ # No reused results, just use current results+ results = current_results++ running_accuracy = None+ simpleqa_accuracy = None+ browsecomp_accuracy = None++ if results:+ # Overall running accuracy+ correct_count = sum(1 for r in results if r.is_correct)+ running_accuracy = (correct_count / len(results)) * 100++ # Per-dataset accuracy+ simpleqa_results = [+ r for r in results if r.dataset_type.value == "simpleqa"+ ]+ if simpleqa_results:+ simpleqa_correct = sum(+ 1 for r in simpleqa_results if r.is_correct+ )+ simpleqa_accuracy = (+ simpleqa_correct / len(simpleqa_results)+ ) * 100++ browsecomp_results = [+ r for r in results if r.dataset_type.value == "browsecomp"+ ]+ if browsecomp_results:+ browsecomp_correct = sum(+ 1 for r in browsecomp_results if r.is_correct+ )+ browsecomp_accuracy = (+ browsecomp_correct / len(browsecomp_results)+ ) * 100++ # Calculate time estimates and reliability metrics+ estimated_time_remaining = None+ total_elapsed_time = None+ avg_time_per_example = None+ accuracy_confidence = None++ if (+ benchmark_run.start_time+ and benchmark_run.completed_examples > 0+ ):+ # Calculate elapsed time+ current_time = datetime.now()+ total_elapsed_time = (+ current_time - benchmark_run.start_time+ ).total_seconds()++ # Calculate average processing time per example+ avg_time_per_example = (+ total_elapsed_time / benchmark_run.completed_examples+ )++ # Estimate remaining time+ remaining_examples = (+ benchmark_run.total_examples+ - benchmark_run.completed_examples+ )+ if remaining_examples > 0:+ estimated_time_remaining = (+ avg_time_per_example * remaining_examples+ )++ # Calculate accuracy confidence interval (95% confidence)+ if results and len(results) >= 3:+ import math++ n = len(results)+ p = running_accuracy / 100 if running_accuracy else 0+ # Standard error for proportion+ se = math.sqrt(p * (1 - p) / n)+ # 95% confidence interval (±1.96 * SE)+ margin_of_error = 1.96 * se * 100+ accuracy_confidence = {+ "lower_bound": max(0, running_accuracy - margin_of_error),+ "upper_bound": min(100, running_accuracy + margin_of_error),+ "margin_of_error": margin_of_error,+ "sample_size": n,+ }++ return {+ "id": benchmark_run.id,+ "run_name": benchmark_run.run_name,+ "status": benchmark_run.status.value,+ "completed_examples": benchmark_run.completed_examples,+ "total_examples": benchmark_run.total_examples,+ "failed_examples": benchmark_run.failed_examples,+ "overall_accuracy": benchmark_run.overall_accuracy+ or running_accuracy, # Use running accuracy if final not calculated+ "running_accuracy": running_accuracy, # Current running accuracy+ "simpleqa_accuracy": simpleqa_accuracy, # Per-dataset accuracy+ "browsecomp_accuracy": browsecomp_accuracy,+ "processing_rate": benchmark_run.processing_rate,+ "estimated_time_remaining": estimated_time_remaining, # seconds+ "total_elapsed_time": total_elapsed_time, # seconds+ "avg_time_per_example": avg_time_per_example, # seconds+ "accuracy_confidence": accuracy_confidence, # confidence interval+ "created_at": benchmark_run.created_at.isoformat()+ if benchmark_run.created_at+ else None,+ "start_time": benchmark_run.start_time.isoformat()+ if benchmark_run.start_time+ else None,+ "end_time": benchmark_run.end_time.isoformat()+ if benchmark_run.end_time+ else None,+ "error_message": benchmark_run.error_message,+ }++ except Exception as e:+ logger.error(f"Error getting benchmark status: {e}")+ return None+ finally:+ session.close()++ def cancel_benchmark(self, benchmark_run_id: int) -> bool:+ """Cancel a running benchmark."""+ try:+ if benchmark_run_id in self.active_runs:+ self.active_runs[benchmark_run_id]["status"] = "cancelled"++ self.update_benchmark_status(+ benchmark_run_id, BenchmarkStatus.CANCELLED+ )+ logger.info(f"Cancelled benchmark run {benchmark_run_id}")+ return True++ except Exception as e:+ logger.error(f"Error cancelling benchmark {benchmark_run_id}: {e}")+ return False+++# Global service instance+benchmark_service = BenchmarkService()diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.jsonindex 0ed130b50d..d0d87ba453 100644--- a/src/local_deep_research/defaults/default_settings.json+++ b/src/local_deep_research/defaults/default_settings.json@@ -4065,6 +4065,197 @@"value": false,"visible": true},+ "search.engine.web.tavily.display_name": {+ "category": "tavily",+ "description": "Display name to use in the U.I. for this search engine.",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "Display Name",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "text",+ "value": "Tavily",+ "visible": false+ },+ "search.engine.web.tavily.description": {+ "category": "tavily",+ "description": "Human-readable description of the search engine.",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "Description",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "text",+ "value": "AI-powered search engine optimized for research with built-in answer extraction.",+ "visible": false+ },+ "search.engine.web.tavily.api_key": {+ "category": "tavily",+ "description": "The Tavily API key to use.",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Api Key",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "password",+ "value": "TAVILY_API_KEY",+ "visible": true+ },+ "search.engine.web.tavily.class_name": {+ "category": "tavily",+ "description": "Setting for tavily.class_name",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Class Name",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "text",+ "value": "TavilySearchEngine",+ "visible": true+ },+ "search.engine.web.tavily.default_params.search_depth": {+ "category": "tavily",+ "description": "Search depth - basic for speed, advanced for quality",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Search Depth",+ "options": ["basic", "advanced"],+ "step": null,+ "type": "SEARCH",+ "ui_element": "select",+ "value": "basic",+ "visible": true+ },+ "search.engine.web.tavily.default_params.include_full_content": {+ "category": "tavily",+ "description": "Include full webpage content in results",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Include Full Content",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": true,+ "visible": true+ },+ "search.engine.web.tavily.module_path": {+ "category": "tavily",+ "description": "Setting for tavily.module_path",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Module Path",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "text",+ "value": ".engines.search_engine_tavily",+ "visible": true+ },+ "search.engine.web.tavily.requires_api_key": {+ "category": "tavily",+ "description": "Setting for tavily.requires_api_key",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Requires Api Key",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": true,+ "visible": true+ },+ "search.engine.web.tavily.reliability": {+ "category": "tavily",+ "description": "Setting for tavily.reliability",+ "editable": true,+ "max_value": 1.0,+ "min_value": 0.0,+ "name": "Reliability",+ "options": null,+ "step": 0.05,+ "type": "SEARCH",+ "ui_element": "range",+ "value": 0.8,+ "visible": true+ },+ "search.engine.web.tavily.strengths": {+ "category": "tavily",+ "description": "Setting for tavily.strengths",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Strengths",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "json",+ "value": [+ "AI-powered search optimization",+ "built-in answer extraction",+ "research-focused results",+ "high-quality content filtering",+ "fast response times"+ ],+ "visible": true+ },+ "search.engine.web.tavily.supports_full_search": {+ "category": "tavily",+ "description": "Setting for tavily.supports_full_search",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Supports Full Search",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": true,+ "visible": true+ },+ "search.engine.web.tavily.weaknesses": {+ "category": "tavily",+ "description": "Setting for tavily.weaknesses",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Weaknesses",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "json",+ "value": [+ "requires API key with usage limits",+ "newer service with smaller historical data"+ ],+ "visible": true+ },+ "search.engine.web.tavily.use_in_auto_search": {+ "category": "tavily",+ "description": "Include Tavily in auto search mode",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Include in Auto Search",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": false,+ "visible": true+ },"search.engine.local.local_all.use_in_auto_search": {"category": "local_all","description": "Include local documents in auto search mode",@@ -4213,5 +4404,88 @@"ui_element": "checkbox","value": false,"visible": true+ },+ "rate_limiting.enabled": {+ "category": "rate_limiting",+ "description": "Enable adaptive rate limiting system that learns optimal wait times for each search engine",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Enable Rate Limiting",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": true,+ "visible": true+ },+ "rate_limiting.exploration_rate": {+ "category": "rate_limiting",+ "description": "Percentage of attempts that will explore faster rates to discover improvements (0.0-1.0)",+ "editable": true,+ "max_value": 1.0,+ "min_value": 0.0,+ "name": "Exploration Rate",+ "options": null,+ "step": 0.05,+ "type": "APP",+ "ui_element": "slider",+ "value": 0.1,+ "visible": true+ },+ "rate_limiting.learning_rate": {+ "category": "rate_limiting",+ "description": "How quickly to adapt to new rate limit information (higher = faster adaptation)",+ "editable": true,+ "max_value": 1.0,+ "min_value": 0.05,+ "name": "Learning Rate",+ "options": null,+ "step": 0.05,+ "type": "APP",+ "ui_element": "slider",+ "value": 0.3,+ "visible": true+ },+ "rate_limiting.memory_window": {+ "category": "rate_limiting",+ "description": "Number of recent attempts to keep in memory for learning",+ "editable": true,+ "max_value": 1000,+ "min_value": 10,+ "name": "Memory Window",+ "options": null,+ "step": 10,+ "type": "APP",+ "ui_element": "number",+ "value": 100,+ "visible": true+ },+ "rate_limiting.profile": {+ "category": "rate_limiting",+ "description": "Rate limiting aggressiveness profile",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Rate Limiting Profile",+ "options": [+ {+ "label": "Conservative (slower, more reliable)",+ "value": "conservative"+ },+ {+ "label": "Balanced (default)",+ "value": "balanced"+ },+ {+ "label": "Aggressive (faster, higher risk)",+ "value": "aggressive"+ }+ ],+ "step": null,+ "type": "APP",+ "ui_element": "select",+ "value": "balanced",+ "visible": true}}diff --git a/src/local_deep_research/error_handling/report_generator.py b/src/local_deep_research/error_handling/report_generator.pyindex 064f5add0c..316d818616 100644--- a/src/local_deep_research/error_handling/report_generator.py+++ b/src/local_deep_research/error_handling/report_generator.py@@ -346,6 +346,16 @@ We're here to help you get this working:"- Check search engine settings in Advanced Options\n""- Ensure required API keys are set for external search engines"),+ "No search results found|All search engines.*blocked.*rate.*limited": (+ "No search results were found for your query. This could mean all search engines are unavailable.\n\n"+ "**Try this:**\n"+ "- **If using SearXNG:** Check if your SearXNG Docker container is running: `docker ps`\n"+ "- **Start SearXNG:** `docker run -d -p 8080:8080 searxng/searxng` then set URL to `http://localhost:8080`\n"+ "- **Try different search terms:** Use broader, more general keywords\n"+ "- **Check network connection:** Ensure you can access the internet\n"+ "- **Switch search engines:** Try DuckDuckGo, Brave, or Google (if API key configured)\n"+ "- **Check for typos** in your research query"+ ),"TypeError.*Context.*Size|'<' not supported between": ("Model configuration issue. The context size setting might not be compatible with your model.\n\n""**Try this:**\n"diff --git a/src/local_deep_research/metrics/db_models.py b/src/local_deep_research/metrics/db_models.pyindex a0b3a4dd01..fb543c7aad 100644--- a/src/local_deep_research/metrics/db_models.py+++ b/src/local_deep_research/metrics/db_models.py@@ -20,9 +20,7 @@ class TokenUsage(Base):__tablename__ = "token_usage"id = Column(Integer, primary_key=True)- research_id = Column(- Integer- ) # Removed foreign key constraint to fix token tracking+ research_id = Column(String(36), index=True) # UUID stringmodel_name = Column(String)provider = Column(String@@ -63,9 +61,7 @@ class ModelUsage(Base):__table_args__ = (UniqueConstraint("research_id", "model_name"),)id = Column(Integer, primary_key=True)- research_id = Column(- Integer- ) # Removed foreign key constraint to fix token tracking+ research_id = Column(String(36), index=True) # UUID stringmodel_name = Column(String)provider = Column(String)prompt_tokens = Column(Integer, default=0)@@ -95,7 +91,7 @@ class SearchCall(Base):__tablename__ = "search_calls"id = Column(Integer, primary_key=True)- research_id = Column(Integer)+ research_id = Column(String(36), index=True) # UUID stringresearch_query = Column(Text)research_mode = Column(String)research_phase = Column(String)diff --git a/src/local_deep_research/metrics/search_tracker.py b/src/local_deep_research/metrics/search_tracker.pyindex bf5747a167..edd6b573b5 100644--- a/src/local_deep_research/metrics/search_tracker.py+++ b/src/local_deep_research/metrics/search_tracker.py@@ -3,6 +3,7 @@ Search call tracking system for metrics collection.Similar to token_counter.py but tracks search engine usage."""+import threadingfrom typing import Any, Dict, List, Optionalfrom loguru import logger@@ -19,12 +20,20 @@ class SearchTracker:def __init__(self, db: Optional[MetricsDatabase] = None):"""Initialize the search tracker."""self.db = db or MetricsDatabase()- self.research_context = {}+ self._local = threading.local()def set_research_context(self, context: Dict[str, Any]) -> None:- """Set the current research context for search tracking."""- self.research_context = context or {}- logger.debug(f"Search tracker context updated: {self.research_context}")+ """Set the current research context for search tracking (thread-safe)."""+ self._local.research_context = context or {}+ logger.debug(+ f"Search tracker context updated (thread {threading.current_thread().ident}): {self._local.research_context}"+ )++ def _get_research_context(self) -> Dict[str, Any]:+ """Get the research context for the current thread."""+ if not hasattr(self._local, "research_context"):+ self._local.research_context = {}+ return self._local.research_contextdef record_search(self,@@ -37,12 +46,17 @@ class SearchTracker:) -> None:"""Record a completed search operation directly to database."""- # Extract research context- research_id = self.research_context.get("research_id")- research_query = self.research_context.get("research_query")- research_mode = self.research_context.get("research_mode", "unknown")- research_phase = self.research_context.get("research_phase", "search")- search_iteration = self.research_context.get("search_iteration", 0)+ # Extract research context (thread-safe)+ context = self._get_research_context()+ research_id = context.get("research_id")++ # Convert research_id to string if it's an integer (for backward compatibility)+ if isinstance(research_id, int):+ research_id = str(research_id)+ research_query = context.get("research_query")+ research_mode = context.get("research_mode", "unknown")+ research_phase = context.get("research_phase", "search")+ search_iteration = context.get("search_iteration", 0)# Determine success statussuccess_status = "success" if success else "error"@@ -59,7 +73,7 @@ class SearchTracker:with self.db.get_session() as session:# Create search call recordsearch_call = SearchCall(- research_id=research_id,+ research_id=research_id, # String research_id (UUID or converted integer)research_query=research_query,research_mode=research_mode,research_phase=research_phase,diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.pyindex 0abad1ace5..a64882393b 100644--- a/src/local_deep_research/search_system.py+++ b/src/local_deep_research/search_system.py@@ -465,15 +465,14 @@ class AdvancedSearchSystem:)logger.info("Creating FocusedIterationStrategy instance")- # PRESERVE SIMPLEQA PERFORMANCE: Keep proven 96.51% accuracy configuration- # Original optimal settings: max_iterations=8, questions_per_iteration=5+ # Use database settings for iterations and questions_per_iterationself.strategy = FocusedIterationStrategy(model=self.model,search=self.search,all_links_of_system=self.all_links_of_system,- max_iterations=8, # PROVEN OPTIMAL FOR SIMPLEQA (96.51% accuracy)- questions_per_iteration=5, # PROVEN OPTIMAL FOR SIMPLEQA- use_browsecomp_optimization=True, # Enable BrowseComp optimizations+ max_iterations=self.max_iterations, # Use database setting+ questions_per_iteration=self.questions_per_iteration, # Use database setting+ use_browsecomp_optimization=True, # Enable BrowseComp optimizations for 95% accuracy)elif strategy_name.lower() in ["browsecomp-entity",diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.pyindex 62a3fae6eb..c326325a3c 100644--- a/src/local_deep_research/web/app_factory.py+++ b/src/local_deep_research/web/app_factory.py@@ -61,8 +61,10 @@ def create_app():# Disable CSRF for API routes@app.before_requestdef disable_csrf_for_api():- if request.path.startswith("/api/v1/") or request.path.startswith(- "/research/api/"+ if (+ request.path.startswith("/api/v1/")+ or request.path.startswith("/research/api/")+ or request.path.startswith("/benchmark/api/")):csrf.protect = lambda: None@@ -171,6 +173,7 @@ def register_blueprints(app):from .routes.metrics_routes import metrics_bpfrom .routes.research_routes import research_bpfrom .routes.settings_routes import settings_bp+ from ..benchmarks.web_api.benchmark_routes import benchmark_bp# Add root route@app.route("/")@@ -188,6 +191,7 @@ def register_blueprints(app):app.register_blueprint(api_bp, url_prefix="/research/api") # Register API blueprint with prefix+ app.register_blueprint(benchmark_bp) # Register benchmark blueprint# Register API v1 blueprintapp.register_blueprint(api_blueprint) # Already has url_prefix='/api/v1'diff --git a/src/local_deep_research/web/database/benchmark_schema.py b/src/local_deep_research/web/database/benchmark_schema.pynew file mode 100644index 0000000000..84182ef7ea--- /dev/null+++ b/src/local_deep_research/web/database/benchmark_schema.py@@ -0,0 +1,230 @@+"""Simple benchmark table definitions for schema creation."""++import enum++from sqlalchemy import (+ JSON,+ Boolean,+ Column,+ DateTime,+ Enum,+ Float,+ ForeignKey,+ Integer,+ String,+ Text,+ UniqueConstraint,+ Index,+)+from sqlalchemy.sql import func+++class BenchmarkStatus(enum.Enum):+ """Status of a benchmark run."""++ PENDING = "pending"+ IN_PROGRESS = "in_progress"+ COMPLETED = "completed"+ FAILED = "failed"+ CANCELLED = "cancelled"+ PAUSED = "paused"+++class DatasetType(enum.Enum):+ """Supported dataset types."""++ SIMPLEQA = "simpleqa"+ BROWSECOMP = "browsecomp"+ CUSTOM = "custom"+++# Simple table definitions for creation+benchmark_runs_table = {+ "table_name": "benchmark_runs",+ "columns": [+ Column("id", Integer, primary_key=True, index=True),+ Column("run_name", String(255), nullable=True),+ Column("config_hash", String(16), nullable=False, index=True),+ Column("query_hash_list", JSON, nullable=False),+ Column("search_config", JSON, nullable=False),+ Column("evaluation_config", JSON, nullable=False),+ Column("datasets_config", JSON, nullable=False),+ Column(+ "status",+ Enum(BenchmarkStatus),+ default=BenchmarkStatus.PENDING,+ nullable=False,+ ),+ Column(+ "created_at", DateTime, server_default=func.now(), nullable=False+ ),+ Column(+ "updated_at",+ DateTime,+ server_default=func.now(),+ onupdate=func.now(),+ nullable=False,+ ),+ Column("start_time", DateTime, nullable=True),+ Column("end_time", DateTime, nullable=True),+ Column("total_examples", Integer, default=0, nullable=False),+ Column("completed_examples", Integer, default=0, nullable=False),+ Column("failed_examples", Integer, default=0, nullable=False),+ Column("overall_accuracy", Float, nullable=True),+ Column("processing_rate", Float, nullable=True),+ Column("error_message", Text, nullable=True),+ ],+ "indexes": [+ Index("idx_benchmark_runs_config_hash", "config_hash"),+ Index("idx_benchmark_runs_status_created", "status", "created_at"),+ ],+}++benchmark_results_table = {+ "table_name": "benchmark_results",+ "columns": [+ Column("id", Integer, primary_key=True, index=True),+ Column(+ "benchmark_run_id",+ Integer,+ ForeignKey("benchmark_runs.id", ondelete="CASCADE"),+ nullable=False,+ index=True,+ ),+ Column("example_id", String(255), nullable=False),+ Column("query_hash", String(32), nullable=False, index=True),+ Column("dataset_type", Enum(DatasetType), nullable=False),+ Column("question", Text, nullable=False),+ Column("correct_answer", Text, nullable=False),+ Column("response", Text, nullable=True),+ Column("extracted_answer", Text, nullable=True),+ Column("confidence", String(10), nullable=True),+ Column("processing_time", Float, nullable=True),+ Column("sources", JSON, nullable=True),+ Column("is_correct", Boolean, nullable=True),+ Column("graded_confidence", String(10), nullable=True),+ Column("grader_response", Text, nullable=True),+ Column(+ "created_at", DateTime, server_default=func.now(), nullable=False+ ),+ Column("completed_at", DateTime, nullable=True),+ Column("research_error", Text, nullable=True),+ Column("evaluation_error", Text, nullable=True),+ Column("task_index", Integer, nullable=True),+ Column("result_metadata", JSON, nullable=True),+ ],+ "indexes": [+ Index(+ "idx_benchmark_results_run_dataset",+ "benchmark_run_id",+ "dataset_type",+ ),+ Index("idx_benchmark_results_query_hash", "query_hash"),+ Index("idx_benchmark_results_completed", "completed_at"),+ ],+ "constraints": [+ UniqueConstraint(+ "benchmark_run_id", "query_hash", name="uix_run_query"+ ),+ ],+}++benchmark_configs_table = {+ "table_name": "benchmark_configs",+ "columns": [+ Column("id", Integer, primary_key=True, index=True),+ Column("name", String(255), nullable=False),+ Column("description", Text, nullable=True),+ Column("config_hash", String(16), nullable=False, index=True),+ Column("search_config", JSON, nullable=False),+ Column("evaluation_config", JSON, nullable=False),+ Column("datasets_config", JSON, nullable=False),+ Column(+ "created_at", DateTime, server_default=func.now(), nullable=False+ ),+ Column(+ "updated_at",+ DateTime,+ server_default=func.now(),+ onupdate=func.now(),+ nullable=False,+ ),+ Column("is_default", Boolean, default=False, nullable=False),+ Column("is_public", Boolean, default=True, nullable=False),+ Column("usage_count", Integer, default=0, nullable=False),+ Column("last_used", DateTime, nullable=True),+ Column("best_accuracy", Float, nullable=True),+ Column("avg_processing_rate", Float, nullable=True),+ ],+ "indexes": [+ Index("idx_benchmark_configs_name", "name"),+ Index("idx_benchmark_configs_hash", "config_hash"),+ Index("idx_benchmark_configs_default", "is_default"),+ ],+}++benchmark_progress_table = {+ "table_name": "benchmark_progress",+ "columns": [+ Column("id", Integer, primary_key=True, index=True),+ Column(+ "benchmark_run_id",+ Integer,+ ForeignKey("benchmark_runs.id", ondelete="CASCADE"),+ nullable=False,+ index=True,+ ),+ Column(+ "timestamp", DateTime, server_default=func.now(), nullable=False+ ),+ Column("completed_examples", Integer, nullable=False),+ Column("total_examples", Integer, nullable=False),+ Column("overall_accuracy", Float, nullable=True),+ Column("dataset_accuracies", JSON, nullable=True),+ Column("processing_rate", Float, nullable=True),+ Column("estimated_completion", DateTime, nullable=True),+ Column("current_dataset", Enum(DatasetType), nullable=True),+ Column("current_example_id", String(255), nullable=True),+ Column("memory_usage", Float, nullable=True),+ Column("cpu_usage", Float, nullable=True),+ ],+ "indexes": [+ Index(+ "idx_benchmark_progress_run_time", "benchmark_run_id", "timestamp"+ ),+ ],+}+++def create_benchmark_tables_simple(engine):+ """Create benchmark tables using simple table definitions."""+ from sqlalchemy import Table, MetaData++ metadata = MetaData()++ # Create tables+ tables_to_create = [+ benchmark_runs_table,+ benchmark_results_table,+ benchmark_configs_table,+ benchmark_progress_table,+ ]++ for table_def in tables_to_create:+ table = Table(+ table_def["table_name"],+ metadata,+ *table_def["columns"],+ extend_existing=True,+ )++ # Add indexes+ for index in table_def.get("indexes", []):+ index.table = table++ # Add constraints+ for constraint in table_def.get("constraints", []):+ table.append_constraint(constraint)++ # Create all tables+ metadata.create_all(engine, checkfirst=True)diff --git a/src/local_deep_research/web/database/convert_research_id_to_string.py b/src/local_deep_research/web/database/convert_research_id_to_string.pynew file mode 100644index 0000000000..c55064043d--- /dev/null+++ b/src/local_deep_research/web/database/convert_research_id_to_string.py@@ -0,0 +1,161 @@+"""+Convert research_id columns from Integer to String.++This migration converts existing integer research_id values to string format+while preserving all existing data. New records will use UUID strings.+"""++import sqlite3+from pathlib import Path+from loguru import logger+++def get_database_path():+ """Get the path to the SQLite database."""+ data_dir = Path(__file__).parents[3] / "data"+ return data_dir / "ldr.db"+++def convert_research_id_to_string():+ """+ Convert research_id columns from Integer to String in all tables.+ Preserves existing data by converting integer IDs to string format.+ """+ db_path = get_database_path()++ if not db_path.exists():+ logger.info("Database doesn't exist yet, migration not needed")+ return++ logger.info(f"Converting research_id columns to string in {db_path}")++ conn = sqlite3.connect(db_path)+ conn.execute(+ "PRAGMA foreign_keys = OFF"+ ) # Disable FK constraints during migration++ try:+ cursor = conn.cursor()++ # List of tables that have research_id columns+ tables_to_migrate = [+ "token_usage",+ "model_usage",+ "search_calls",+ "benchmark_results", # If it exists+ ]++ for table_name in tables_to_migrate:+ logger.info(f"Converting {table_name} table...")++ # Check if table exists+ cursor.execute(+ "SELECT name FROM sqlite_master WHERE type='table' AND name=?",+ (table_name,),+ )+ if not cursor.fetchone():+ logger.info(f"Table {table_name} does not exist, skipping")+ continue++ # Check if research_id column exists+ cursor.execute(f"PRAGMA table_info({table_name})")+ columns = cursor.fetchall()+ has_research_id = any(col[1] == "research_id" for col in columns)++ if not has_research_id:+ logger.info(+ f"Table {table_name} does not have research_id column, skipping"+ )+ continue++ # For SQLite, we need to recreate the table to change column type+ # 1. Create new table with string research_id+ # 2. Copy data with research_id converted to string+ # 3. Drop old table and rename new table++ # Get the current table schema+ cursor.execute(+ f"SELECT sql FROM sqlite_master WHERE type='table' AND name='{table_name}'"+ )+ create_sql = cursor.fetchone()[0]++ # Create new table name+ new_table_name = f"{table_name}_new"++ # Modify the CREATE TABLE statement to change research_id to TEXT+ new_create_sql = create_sql.replace(+ f"CREATE TABLE {table_name}", f"CREATE TABLE {new_table_name}"+ )+ new_create_sql = new_create_sql.replace(+ "research_id INTEGER", "research_id TEXT"+ )+ new_create_sql = new_create_sql.replace(+ "research_id INT", "research_id TEXT"+ )++ # Create the new table+ cursor.execute(new_create_sql)++ # Copy data from old table to new table, converting research_id to string+ cursor.execute(f"SELECT * FROM {table_name}")+ old_rows = cursor.fetchall()++ if old_rows:+ # Get column names+ cursor.execute(f"PRAGMA table_info({table_name})")+ columns = cursor.fetchall()+ column_names = [col[1] for col in columns]+ research_id_index = (+ column_names.index("research_id")+ if "research_id" in column_names+ else -1+ )++ # Prepare insert statement+ placeholders = ",".join(["?" for _ in column_names])+ insert_sql = f"INSERT INTO {new_table_name} ({','.join(column_names)}) VALUES ({placeholders})"++ # Convert rows and insert+ converted_rows = []+ for row in old_rows:+ row_list = list(row)+ # Convert research_id to string if it's not None+ if (+ research_id_index >= 0+ and row_list[research_id_index] is not None+ ):+ row_list[research_id_index] = str(+ row_list[research_id_index]+ )+ converted_rows.append(tuple(row_list))++ cursor.executemany(insert_sql, converted_rows)+ logger.info(+ f"Converted {len(converted_rows)} rows in {table_name}"+ )++ # Drop old table and rename new table+ cursor.execute(f"DROP TABLE {table_name}")+ cursor.execute(+ f"ALTER TABLE {new_table_name} RENAME TO {table_name}"+ )++ logger.info(+ f"Successfully converted {table_name} research_id to string"+ )++ # Commit all changes+ conn.commit()+ logger.info("All research_id columns converted to string successfully!")++ except Exception as e:+ logger.error(f"Error during research_id conversion: {e}")+ conn.rollback()+ raise+ finally:+ conn.execute("PRAGMA foreign_keys = ON") # Re-enable FK constraints+ conn.close()+++if __name__ == "__main__":+ convert_research_id_to_string()diff --git a/src/local_deep_research/web/database/models.py b/src/local_deep_research/web/database/models.pyindex da922796d9..650c206982 100644--- a/src/local_deep_research/web/database/models.py+++ b/src/local_deep_research/web/database/models.py@@ -39,8 +39,10 @@ class ResearchHistory(Base):__tablename__ = "research_history"- # Unique identifier for each record.+ # Legacy integer ID (kept for migration compatibility)id = Column(Integer, primary_key=True, autoincrement=True)+ # New UUID identifier (primary field to use for new records)+ uuid_id = Column(String(36), unique=True, index=True)# The search query.query = Column(Text, nullable=False)# The mode of research (e.g., 'quick_summary', 'detailed_report').@@ -184,3 +186,37 @@ class Journal(Base):quality_model = Column(String(255), nullable=True, index=True)# Time at which the quality was last analyzed.quality_analysis_time = Column(Integer, nullable=False)+++class RateLimitAttempt(Base):+ """Database model for tracking individual rate limit retry attempts."""++ __tablename__ = "rate_limit_attempts"++ id = Column(Integer, primary_key=True, index=True)+ engine_type = Column(String(100), nullable=False, index=True)+ timestamp = Column(Float, nullable=False, index=True)+ wait_time = Column(Float, nullable=False)+ retry_count = Column(Integer, nullable=False)+ success = Column(Boolean, nullable=False)+ error_type = Column(String(100), nullable=True)+ created_at = Column(DateTime, server_default=func.now(), nullable=False)+++class RateLimitEstimate(Base):+ """Database model for storing current rate limit estimates per engine."""++ __tablename__ = "rate_limit_estimates"++ id = Column(Integer, primary_key=True, index=True)+ engine_type = Column(String(100), nullable=False, unique=True, index=True)+ base_wait_seconds = Column(Float, nullable=False)+ min_wait_seconds = Column(Float, nullable=False)+ max_wait_seconds = Column(Float, nullable=False)+ last_updated = Column(Float, nullable=False)+ total_attempts = Column(Integer, default=0, nullable=False)+ success_rate = Column(Float, default=0.0, nullable=False)+ created_at = Column(DateTime, server_default=func.now(), nullable=False)+ updated_at = Column(+ DateTime, server_default=func.now(), onupdate=func.now(), nullable=False+ )diff --git a/src/local_deep_research/web/database/schema_upgrade.py b/src/local_deep_research/web/database/schema_upgrade.pyindex 09a7f35a24..3f04cab599 100644--- a/src/local_deep_research/web/database/schema_upgrade.py+++ b/src/local_deep_research/web/database/schema_upgrade.py@@ -24,7 +24,7 @@ except ImportError:)DB_PATH = os.path.join(project_root, "src", "data", "ldr.db")-from .models import Base, ResearchStrategy+from .models import Base, ResearchStrategy, RateLimitAttempt, RateLimitEstimatedef remove_research_log_table(engine):@@ -87,6 +87,286 @@ def create_research_strategy_table(engine):return False+def create_benchmark_tables(engine):+ """+ Create benchmark tables if they don't exist++ Args:+ engine: SQLAlchemy engine++ Returns:+ bool: True if operation was successful, False otherwise+ """+ try:+ from .benchmark_schema import create_benchmark_tables_simple++ inspector = inspect(engine)++ # Check if benchmark tables already exist+ if not inspector.has_table("benchmark_runs"):+ # Create all benchmark tables using simple schema+ create_benchmark_tables_simple(engine)+ logger.info("Successfully created benchmark tables")+ return True+ else:+ logger.info("Benchmark tables already exist, no action needed")+ return True+ except Exception:+ logger.exception("Error creating benchmark tables")+ return False+++def create_rate_limiting_tables(engine):+ """+ Create rate limiting tables if they don't exist++ Args:+ engine: SQLAlchemy engine++ Returns:+ bool: True if operation was successful, False otherwise+ """+ try:+ inspector = inspect(engine)++ tables_to_create = []++ # Check if rate_limit_attempts table exists+ if not inspector.has_table("rate_limit_attempts"):+ tables_to_create.append(RateLimitAttempt.__table__)+ logger.info("Need to create 'rate_limit_attempts' table")++ # Check if rate_limit_estimates table exists+ if not inspector.has_table("rate_limit_estimates"):+ tables_to_create.append(RateLimitEstimate.__table__)+ logger.info("Need to create 'rate_limit_estimates' table")++ if tables_to_create:+ # Create the tables using ORM+ Base.metadata.create_all(engine, tables=tables_to_create)+ logger.info(+ f"Successfully created {len(tables_to_create)} rate limiting tables"+ )+ else:+ logger.info("Rate limiting tables already exist, no action needed")++ return True+ except Exception:+ logger.exception("Error creating rate limiting tables")+ return False+++def add_research_id_to_benchmark_results(engine):+ """+ Add research_id column to benchmark_results table if it doesn't exist.+ """+ try:+ import sqlite3++ # Get database path from engine+ db_path = engine.url.database++ logger.info("Checking if benchmark_results needs research_id column...")++ conn = sqlite3.connect(db_path)++ try:+ cursor = conn.cursor()++ # Check if table exists+ cursor.execute(+ "SELECT name FROM sqlite_master WHERE type='table' AND name='benchmark_results'"+ )+ if not cursor.fetchone():+ logger.info("benchmark_results table does not exist, skipping")+ return True++ # Check if research_id column already exists+ cursor.execute("PRAGMA table_info(benchmark_results)")+ columns = cursor.fetchall()+ has_research_id = any(col[1] == "research_id" for col in columns)++ if has_research_id:+ logger.info("benchmark_results already has research_id column")+ return True++ # Add research_id column+ logger.info("Adding research_id column to benchmark_results table")+ cursor.execute(+ "ALTER TABLE benchmark_results ADD COLUMN research_id TEXT"+ )++ conn.commit()+ logger.info(+ "Successfully added research_id column to benchmark_results"+ )+ return True++ finally:+ conn.close()++ except Exception:+ logger.exception("Error adding research_id column to benchmark_results")+ return False+++def convert_research_id_to_string_if_needed(engine):+ """+ Convert research_id columns from Integer to String in all tables.+ Preserves existing data by converting integer IDs to string format.+ Only runs if integer research_id columns are detected.+ """+ try:+ import sqlite3++ # Get database path from engine+ db_path = engine.url.database++ logger.info(+ "Checking if research_id columns need conversion to string..."+ )++ conn = sqlite3.connect(db_path)+ conn.execute("PRAGMA foreign_keys = OFF")++ try:+ cursor = conn.cursor()++ # List of tables that might have research_id columns+ tables_to_check = [+ "token_usage",+ "model_usage",+ "search_calls",+ "benchmark_results",+ ]++ tables_needing_conversion = []++ # Check which tables need conversion+ for table_name in tables_to_check:+ # Check if table exists+ cursor.execute(+ "SELECT name FROM sqlite_master WHERE type='table' AND name=?",+ (table_name,),+ )+ if not cursor.fetchone():+ continue++ # Check if research_id column exists and is integer type+ cursor.execute(f"PRAGMA table_info({table_name})")+ columns = cursor.fetchall()++ for col in columns:+ col_name, col_type = col[1], col[2]+ if col_name == "research_id" and (+ "INTEGER" in col_type.upper()+ or "INT" in col_type.upper()+ ):+ tables_needing_conversion.append(table_name)+ break++ if not tables_needing_conversion:+ logger.info(+ "All research_id columns are already string type, no conversion needed"+ )+ return True++ logger.info(+ f"Converting research_id to string in tables: {tables_needing_conversion}"+ )++ # Convert each table+ for table_name in tables_needing_conversion:+ logger.info(f"Converting {table_name} table...")++ # Get the current table schema+ cursor.execute(+ f"SELECT sql FROM sqlite_master WHERE type='table' AND name='{table_name}'"+ )+ create_sql = cursor.fetchone()[0]++ # Create new table name+ new_table_name = f"{table_name}_new"++ # Modify the CREATE TABLE statement to change research_id to TEXT+ new_create_sql = create_sql.replace(+ f"CREATE TABLE {table_name}",+ f"CREATE TABLE {new_table_name}",+ )+ new_create_sql = new_create_sql.replace(+ "research_id INTEGER", "research_id TEXT"+ )+ new_create_sql = new_create_sql.replace(+ "research_id INT", "research_id TEXT"+ )++ # Create the new table+ cursor.execute(new_create_sql)++ # Copy data from old table to new table, converting research_id to string+ cursor.execute(f"SELECT * FROM {table_name}")+ old_rows = cursor.fetchall()++ if old_rows:+ # Get column names+ cursor.execute(f"PRAGMA table_info({table_name})")+ columns = cursor.fetchall()+ column_names = [col[1] for col in columns]+ research_id_index = (+ column_names.index("research_id")+ if "research_id" in column_names+ else -1+ )++ # Prepare insert statement+ placeholders = ",".join(["?" for _ in column_names])+ insert_sql = f"INSERT INTO {new_table_name} ({','.join(column_names)}) VALUES ({placeholders})"++ # Convert rows and insert+ converted_rows = []+ for row in old_rows:+ row_list = list(row)+ # Convert research_id to string if it's not None+ if (+ research_id_index >= 0+ and row_list[research_id_index] is not None+ ):+ row_list[research_id_index] = str(+ row_list[research_id_index]+ )+ converted_rows.append(tuple(row_list))++ cursor.executemany(insert_sql, converted_rows)+ logger.info(+ f"Converted {len(converted_rows)} rows in {table_name}"+ )++ # Drop old table and rename new table+ cursor.execute(f"DROP TABLE {table_name}")+ cursor.execute(+ f"ALTER TABLE {new_table_name} RENAME TO {table_name}"+ )++ logger.info(+ f"Successfully converted {table_name} research_id to string"+ )++ # Commit all changes+ conn.commit()+ logger.info(+ "All research_id columns converted to string successfully!"+ )+ return True++ finally:+ conn.execute("PRAGMA foreign_keys = ON")+ conn.close()++ except Exception:+ logger.exception("Error converting research_id columns to string")+ return False++def run_schema_upgrades():"""Run all schema upgrade operations on the database@@ -113,6 +393,18 @@ def run_schema_upgrades():# 2. Create research_strategies tablecreate_research_strategy_table(engine)+ # 3. Create benchmark tables+ create_benchmark_tables(engine)++ # 4. Create rate limiting tables+ create_rate_limiting_tables(engine)++ # 5. Add research_id column to benchmark_results if missing+ add_research_id_to_benchmark_results(engine)++ # 6. Convert research_id columns from integer to string+ convert_research_id_to_string_if_needed(engine)+logger.info("Schema upgrades completed successfully")return Trueexcept Exception:diff --git a/src/local_deep_research/web/database/uuid_migration.py b/src/local_deep_research/web/database/uuid_migration.pynew file mode 100644index 0000000000..2645e1022e--- /dev/null+++ b/src/local_deep_research/web/database/uuid_migration.py@@ -0,0 +1,265 @@+"""+UUID Migration Script++Migrates all research_id fields from Integer to String (UUID) format.+This creates a more consistent and scalable ID system across the application.+"""++import sqlite3+import uuid+from pathlib import Path+from loguru import logger+++def get_database_path():+ """Get the path to the SQLite database."""+ data_dir = Path(__file__).parents[3] / "data"+ return data_dir / "ldr.db"+++def migrate_to_uuid():+ """+ Migrate all research_id fields from integers to UUIDs.++ Strategy:+ 1. Add new UUID columns alongside existing integer columns+ 2. Generate UUIDs for existing data (or keep as string versions of integers)+ 3. Update foreign key relationships+ 4. Drop old integer columns and rename UUID columns+ """+ db_path = get_database_path()++ if not db_path.exists():+ logger.info("Database doesn't exist yet, migration not needed")+ return++ logger.info(f"Starting UUID migration on {db_path}")++ conn = sqlite3.connect(db_path)+ conn.execute(+ "PRAGMA foreign_keys = OFF"+ ) # Disable FK constraints during migration++ try:+ cursor = conn.cursor()++ # 1. Migrate research_history table (main research IDs)+ logger.info("Migrating research_history table...")++ # Check if the table exists and has the old structure+ cursor.execute("PRAGMA table_info(research_history)")+ columns = cursor.fetchall()+ has_uuid_id = any(col[1] == "uuid_id" for col in columns)++ if not has_uuid_id:+ # Add UUID column+ cursor.execute(+ "ALTER TABLE research_history ADD COLUMN uuid_id TEXT"+ )++ # Generate UUIDs for existing records (convert integer ID to UUID format)+ cursor.execute("SELECT id FROM research_history")+ existing_ids = cursor.fetchall()++ for (old_id,) in existing_ids:+ # Generate a deterministic UUID based on the old ID+ new_uuid = str(+ uuid.uuid5(uuid.NAMESPACE_OID, f"research_{old_id}")+ )+ cursor.execute(+ "UPDATE research_history SET uuid_id = ? WHERE id = ?",+ (new_uuid, old_id),+ )++ logger.info(+ f"Generated UUIDs for {len(existing_ids)} research records"+ )++ # 2. Migrate metrics tables+ logger.info("Migrating metrics tables...")++ # Token usage table+ cursor.execute("PRAGMA table_info(token_usage)")+ columns = cursor.fetchall()+ has_uuid_research_id = any(+ col[1] == "uuid_research_id" for col in columns+ )++ if not has_uuid_research_id:+ cursor.execute(+ "ALTER TABLE token_usage ADD COLUMN uuid_research_id TEXT"+ )++ # Convert existing research_ids to UUIDs (deterministic conversion)+ cursor.execute(+ "SELECT DISTINCT research_id FROM token_usage WHERE research_id IS NOT NULL"+ )+ research_ids = cursor.fetchall()++ for (research_id,) in research_ids:+ if research_id:+ new_uuid = str(+ uuid.uuid5(+ uuid.NAMESPACE_OID, f"research_{research_id}"+ )+ )+ cursor.execute(+ "UPDATE token_usage SET uuid_research_id = ? WHERE research_id = ?",+ (new_uuid, research_id),+ )++ logger.info(+ f"Migrated {len(research_ids)} research IDs in token_usage"+ )++ # Model usage table+ cursor.execute("PRAGMA table_info(model_usage)")+ columns = cursor.fetchall()+ has_uuid_research_id = any(+ col[1] == "uuid_research_id" for col in columns+ )++ if not has_uuid_research_id:+ cursor.execute(+ "ALTER TABLE model_usage ADD COLUMN uuid_research_id TEXT"+ )++ cursor.execute(+ "SELECT DISTINCT research_id FROM model_usage WHERE research_id IS NOT NULL"+ )+ research_ids = cursor.fetchall()++ for (research_id,) in research_ids:+ if research_id:+ new_uuid = str(+ uuid.uuid5(+ uuid.NAMESPACE_OID, f"research_{research_id}"+ )+ )+ cursor.execute(+ "UPDATE model_usage SET uuid_research_id = ? WHERE research_id = ?",+ (new_uuid, research_id),+ )++ logger.info(+ f"Migrated {len(research_ids)} research IDs in model_usage"+ )++ # Search calls table+ cursor.execute("PRAGMA table_info(search_calls)")+ columns = cursor.fetchall()+ has_uuid_research_id = any(+ col[1] == "uuid_research_id" for col in columns+ )++ if not has_uuid_research_id:+ cursor.execute(+ "ALTER TABLE search_calls ADD COLUMN uuid_research_id TEXT"+ )++ cursor.execute(+ "SELECT DISTINCT research_id FROM search_calls WHERE research_id IS NOT NULL"+ )+ research_ids = cursor.fetchall()++ for (research_id,) in research_ids:+ if research_id:+ new_uuid = str(+ uuid.uuid5(+ uuid.NAMESPACE_OID, f"research_{research_id}"+ )+ )+ cursor.execute(+ "UPDATE search_calls SET uuid_research_id = ? WHERE research_id = ?",+ (new_uuid, research_id),+ )++ logger.info(+ f"Migrated {len(research_ids)} research IDs in search_calls"+ )++ # 3. Migrate benchmark tables+ logger.info("Migrating benchmark tables...")++ # Check if benchmark_results table exists+ cursor.execute(+ "SELECT name FROM sqlite_master WHERE type='table' AND name='benchmark_results'"+ )+ if cursor.fetchone():+ cursor.execute("PRAGMA table_info(benchmark_results)")+ columns = cursor.fetchall()+ has_uuid_research_id = any(+ col[1] == "uuid_research_id" for col in columns+ )++ if not has_uuid_research_id:+ cursor.execute(+ "ALTER TABLE benchmark_results ADD COLUMN uuid_research_id TEXT"+ )++ cursor.execute(+ "SELECT DISTINCT research_id FROM benchmark_results WHERE research_id IS NOT NULL"+ )+ research_ids = cursor.fetchall()++ for (research_id,) in research_ids:+ if research_id:+ new_uuid = str(+ uuid.uuid5(+ uuid.NAMESPACE_OID, f"research_{research_id}"+ )+ )+ cursor.execute(+ "UPDATE benchmark_results SET uuid_research_id = ? WHERE research_id = ?",+ (new_uuid, research_id),+ )++ logger.info(+ f"Migrated {len(research_ids)} research IDs in benchmark_results"+ )++ # Commit all changes+ conn.commit()+ logger.info("UUID migration completed successfully!")++ # Note: We're keeping both old and new columns for now+ # The application will use the new UUID columns+ # Old columns can be dropped in a future migration once everything is stable++ except Exception as e:+ logger.error(f"Error during UUID migration: {e}")+ conn.rollback()+ raise+ finally:+ conn.execute("PRAGMA foreign_keys = ON") # Re-enable FK constraints+ conn.close()+++def cleanup_old_columns():+ """+ Cleanup migration - drops old integer columns after UUID migration is stable.+ Run this only after confirming the UUID migration is working correctly.+ """+ logger.warning(+ "This will permanently remove old integer research_id columns!"+ )+ logger.warning("Make sure to backup your database before running this!")++ db_path = get_database_path()+ conn = sqlite3.connect(db_path)+ conn.execute("PRAGMA foreign_keys = OFF")++ try:+ # For SQLite, we need to recreate tables to drop columns+ # This is complex, so we'll leave old columns for now+ # They can be cleaned up manually if needed++ logger.info("Cleanup deferred - old columns remain for safety")++ finally:+ conn.execute("PRAGMA foreign_keys = ON")+ conn.close()+++if __name__ == "__main__":+ migrate_to_uuid()diff --git a/src/local_deep_research/web/routes/api_routes.py b/src/local_deep_research/web/routes/api_routes.pyindex 1ca3ed8119..8faa1de820 100644--- a/src/local_deep_research/web/routes/api_routes.py+++ b/src/local_deep_research/web/routes/api_routes.py@@ -5,6 +5,7 @@ import requestsfrom flask import Blueprint, current_app, jsonify, requestfrom ...utilities.url_utils import normalize_url+from ...utilities.db_utils import get_db_sessionfrom ..models.database import get_db_connectionfrom ..routes.research_routes import active_research, termination_flagsfrom ..services.research_service import (@@ -17,12 +18,48 @@ from ..services.resource_service import (delete_resource,get_resources_for_research,)+from ..services.settings_manager import SettingsManager# Create blueprintapi_bp = Blueprint("api", __name__)logger = logging.getLogger(__name__)+@api_bp.route("/settings/current-config", methods=["GET"])+def get_current_config():+ """Get the current configuration from database settings."""+ try:+ session = get_db_session()+ settings_manager = SettingsManager(db_session=session)++ config = {+ "provider": settings_manager.get_setting(+ "llm.provider", "Not configured"+ ),+ "model": settings_manager.get_setting(+ "llm.model", "Not configured"+ ),+ "search_tool": settings_manager.get_setting(+ "search.tool", "searxng"+ ),+ "iterations": settings_manager.get_setting("search.iterations", 8),+ "questions_per_iteration": settings_manager.get_setting(+ "search.questions_per_iteration", 5+ ),+ "search_strategy": settings_manager.get_setting(+ "search.search_strategy", "focused_iteration"+ ),+ }++ session.close()++ return jsonify({"success": True, "config": config})++ except Exception as e:+ logger.error(f"Error getting current config: {e}")+ return jsonify({"success": False, "error": str(e)}), 500++# API Routes@api_bp.route("/start", methods=["POST"])def api_start_research():diff --git a/src/local_deep_research/web/routes/metrics_routes.py b/src/local_deep_research/web/routes/metrics_routes.pyindex 397c5fb10e..ec89627eb8 100644--- a/src/local_deep_research/web/routes/metrics_routes.py+++ b/src/local_deep_research/web/routes/metrics_routes.py@@ -11,7 +11,13 @@ from ...metrics.db_models import ResearchRating, TokenUsagefrom ...metrics.query_utils import get_time_filter_conditionfrom ...metrics.search_tracker import get_search_trackerfrom ...utilities.db_utils import get_db_session-from ..database.models import Research, ResearchStrategy+from ...web_search_engines.rate_limiting import get_tracker+from ..database.models import (+ Research,+ ResearchStrategy,+ RateLimitAttempt,+ RateLimitEstimate,+)from ..utils.templates import render_template_with_defaults# Create a Blueprint for metrics@@ -296,6 +302,161 @@ def get_strategy_analytics(period="30d"):}+def get_rate_limiting_analytics(period="30d"):+ """Get rate limiting analytics for the specified period."""+ try:+ session = get_db_session()++ # Calculate date range+ days_map = {"7d": 7, "30d": 30, "90d": 90, "365d": 365, "all": None}+ days = days_map.get(period, 30)++ try:+ # Get current rate limit estimates+ estimates = session.query(RateLimitEstimate).all()++ # Get recent attempts for analytics+ attempts_query = session.query(RateLimitAttempt)+ if days:+ cutoff_timestamp = (+ datetime.now() - timedelta(days=days)+ ).timestamp()+ attempts_query = attempts_query.filter(+ RateLimitAttempt.timestamp >= cutoff_timestamp+ )++ attempts = attempts_query.all()++ # Calculate analytics+ total_attempts = len(attempts)+ successful_attempts = len([a for a in attempts if a.success])+ failed_attempts = total_attempts - successful_attempts++ # Engine-specific analytics+ engine_stats = {}+ for estimate in estimates:+ engine_attempts = [+ a for a in attempts if a.engine_type == estimate.engine_type+ ]+ engine_success = len([a for a in engine_attempts if a.success])+ engine_total = len(engine_attempts)++ engine_stats[estimate.engine_type] = {+ "base_wait_seconds": round(estimate.base_wait_seconds, 2),+ "min_wait_seconds": round(estimate.min_wait_seconds, 2),+ "max_wait_seconds": round(estimate.max_wait_seconds, 2),+ "success_rate": round(estimate.success_rate * 100, 1),+ "total_attempts": estimate.total_attempts,+ "recent_attempts": engine_total,+ "recent_success_rate": round(+ (engine_success / engine_total * 100)+ if engine_total > 0+ else 0,+ 1,+ ),+ "last_updated": datetime.fromtimestamp(+ estimate.last_updated+ ).strftime("%Y-%m-%d %H:%M:%S"),+ "status": "healthy"+ if estimate.success_rate > 0.8+ else "degraded"+ if estimate.success_rate > 0.5+ else "poor",+ }++ # Overall success rate trend+ success_rate = round(+ (successful_attempts / total_attempts * 100)+ if total_attempts > 0+ else 0,+ 1,+ )++ # Rate limiting events (failures)+ rate_limit_events = len(+ [+ a+ for a in attempts+ if not a.success and a.error_type == "RateLimitError"+ ]+ )++ # Calculate average wait times+ if attempts:+ avg_wait_time = sum(a.wait_time for a in attempts) / len(+ attempts+ )+ successful_wait_times = [+ a.wait_time for a in attempts if a.success+ ]+ avg_successful_wait = (+ sum(successful_wait_times) / len(successful_wait_times)+ if successful_wait_times+ else 0+ )+ else:+ avg_wait_time = 0+ avg_successful_wait = 0++ return {+ "rate_limiting_analytics": {+ "total_attempts": total_attempts,+ "successful_attempts": successful_attempts,+ "failed_attempts": failed_attempts,+ "success_rate": success_rate,+ "rate_limit_events": rate_limit_events,+ "avg_wait_time": round(avg_wait_time, 2),+ "avg_successful_wait": round(avg_successful_wait, 2),+ "engine_stats": engine_stats,+ "total_engines_tracked": len(estimates),+ "healthy_engines": len(+ [+ s+ for s in engine_stats.values()+ if s["status"] == "healthy"+ ]+ ),+ "degraded_engines": len(+ [+ s+ for s in engine_stats.values()+ if s["status"] == "degraded"+ ]+ ),+ "poor_engines": len(+ [+ s+ for s in engine_stats.values()+ if s["status"] == "poor"+ ]+ ),+ }+ }++ finally:+ session.close()++ except Exception as e:+ logger.exception(f"Error getting rate limiting analytics: {e}")+ return {+ "rate_limiting_analytics": {+ "total_attempts": 0,+ "successful_attempts": 0,+ "failed_attempts": 0,+ "success_rate": 0,+ "rate_limit_events": 0,+ "avg_wait_time": 0,+ "avg_successful_wait": 0,+ "engine_stats": {},+ "total_engines_tracked": 0,+ "healthy_engines": 0,+ "degraded_engines": 0,+ "poor_engines": 0,+ "error": str(e),+ }+ }++@metrics_bp.route("/")def metrics_dashboard():"""Render the metrics dashboard page."""@@ -355,11 +516,15 @@ def api_metrics():# Get strategy analyticsstrategy_data = get_strategy_analytics(period)+ # Get rate limiting analytics+ rate_limiting_data = get_rate_limiting_analytics(period)+# Combine metricscombined_metrics = {**token_metrics,**search_metrics,**strategy_data,+ **rate_limiting_data,"user_satisfaction": user_satisfaction,}@@ -384,6 +549,80 @@ def api_metrics():)+@metrics_bp.route("/api/rate-limiting")+def api_rate_limiting_metrics():+ """Get detailed rate limiting metrics."""+ try:+ period = request.args.get("period", "30d")+ rate_limiting_data = get_rate_limiting_analytics(period)++ return jsonify(+ {"status": "success", "data": rate_limiting_data, "period": period}+ )+ except Exception as e:+ logger.exception(f"Error getting rate limiting metrics: {e}")+ return jsonify(+ {+ "status": "error",+ "message": "Failed to retrieve rate limiting metrics",+ }+ ), 500+++@metrics_bp.route("/api/rate-limiting/current")+def api_current_rate_limits():+ """Get current rate limit estimates for all engines."""+ try:+ tracker = get_tracker()+ stats = tracker.get_stats()++ current_limits = []+ for stat in stats:+ (+ engine_type,+ base_wait,+ min_wait,+ max_wait,+ last_updated,+ total_attempts,+ success_rate,+ ) = stat+ current_limits.append(+ {+ "engine_type": engine_type,+ "base_wait_seconds": round(base_wait, 2),+ "min_wait_seconds": round(min_wait, 2),+ "max_wait_seconds": round(max_wait, 2),+ "success_rate": round(success_rate * 100, 1),+ "total_attempts": total_attempts,+ "last_updated": datetime.fromtimestamp(+ last_updated+ ).strftime("%Y-%m-%d %H:%M:%S"),+ "status": "healthy"+ if success_rate > 0.8+ else "degraded"+ if success_rate > 0.5+ else "poor",+ }+ )++ return jsonify(+ {+ "status": "success",+ "current_limits": current_limits,+ "timestamp": datetime.now().isoformat(),+ }+ )+ except Exception as e:+ logger.exception(f"Error getting current rate limits: {e}")+ return jsonify(+ {+ "status": "error",+ "message": "Failed to retrieve current rate limits",+ }+ ), 500++@metrics_bp.route("/api/metrics/research/<int:research_id>")def api_research_metrics(research_id):"""Get metrics for a specific research."""diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex f2ec96afee..a153aaef7f 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -105,38 +105,6 @@ def calculate_warnings():})- # SearXNG recommendation: more questions instead of more iterations- search_engine = get_setting(- "search.tool", "wikipedia", db_session- ).lower()- iterations = int(get_setting("search.iterations", 2, db_session))- questions_per_iteration = int(- get_setting("search.questions_per_iteration", 3, db_session)- )- dismiss_searxng_recommendation = get_setting(- "app.warnings.dismiss_searxng_recommendation", False, db_session- )-- logger.info(- f"SearXNG warning check: engine={search_engine}, iterations={iterations}, dismissed={dismiss_searxng_recommendation}"- )-- if (- search_engine == "searxng"- and iterations > 2- and not dismiss_searxng_recommendation- ):- logger.info("Adding SearXNG optimization warning")- warnings.append(- {- "type": "searxng_recommendation",- "icon": "💡",- "title": "SearXNG Optimization Tip",- "message": f"For SearXNG, we recommend using more questions per iteration ({questions_per_iteration} → 10) instead of more iterations ({iterations}). SearXNG handles multiple questions efficiently in a single iteration.",- "dismissKey": "app.warnings.dismiss_searxng_recommendation",- }- )-except Exception as e:logger.warning(f"Error calculating warnings: {e}")@@ -1761,3 +1729,94 @@ def check_ollama_status():except requests.exceptions.RequestException as e:logger.exception("Ollama check failed")return jsonify({"running": False, "error": str(e)})+++@settings_bp.route("/api/rate-limiting/status", methods=["GET"])+def api_get_rate_limiting_status():+ """Get current rate limiting status and statistics"""+ try:+ from ...web_search_engines.rate_limiting import get_tracker++ tracker = get_tracker()++ # Get basic status+ status = {+ "enabled": tracker.enabled,+ "exploration_rate": tracker.exploration_rate,+ "learning_rate": tracker.learning_rate,+ "memory_window": tracker.memory_window,+ }++ # Get engine statistics+ engine_stats = tracker.get_stats()+ engines = []++ for stat in engine_stats:+ (+ engine_type,+ base_wait,+ min_wait,+ max_wait,+ last_updated,+ total_attempts,+ success_rate,+ ) = stat+ engines.append(+ {+ "engine_type": engine_type,+ "base_wait_seconds": round(base_wait, 2),+ "min_wait_seconds": round(min_wait, 2),+ "max_wait_seconds": round(max_wait, 2),+ "last_updated": last_updated,+ "total_attempts": total_attempts,+ "success_rate": round(success_rate * 100, 1)+ if success_rate+ else 0.0,+ }+ )++ return jsonify({"status": status, "engines": engines})++ except Exception as e:+ logger.exception("Error getting rate limiting status")+ return jsonify({"error": str(e)}), 500+++@settings_bp.route(+ "/api/rate-limiting/engines/<engine_type>/reset", methods=["POST"]+)+def api_reset_engine_rate_limiting(engine_type):+ """Reset rate limiting data for a specific engine"""+ try:+ from ...web_search_engines.rate_limiting import get_tracker++ tracker = get_tracker()+ tracker.reset_engine(engine_type)++ return jsonify(+ {"message": f"Rate limiting data reset for {engine_type}"}+ )++ except Exception as e:+ logger.exception(f"Error resetting rate limiting for {engine_type}")+ return jsonify({"error": str(e)}), 500+++@settings_bp.route("/api/rate-limiting/cleanup", methods=["POST"])+def api_cleanup_rate_limiting():+ """Clean up old rate limiting data"""+ try:+ from ...web_search_engines.rate_limiting import get_tracker++ days = request.json.get("days", 30) if request.is_json else 30++ tracker = get_tracker()+ tracker.cleanup_old_data(days)++ return jsonify(+ {"message": f"Cleaned up rate limiting data older than {days} days"}+ )++ except Exception as e:+ logger.exception("Error cleaning up rate limiting data")+ return jsonify({"error": str(e)}), 500diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 39e59200fb..3ab14cf967 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -423,12 +423,14 @@ def run_research_process(# Override search engine if specifiedif search_engine:try:- if iterations:- system.max_iterations = int(iterations)- if questions_per_iteration:- system.questions_per_iteration = int(- questions_per_iteration- )+ # For focused-iteration strategy, don't override iterations/questions - use database settings+ if strategy != "focused-iteration":+ if iterations:+ system.max_iterations = int(iterations)+ if questions_per_iteration:+ system.questions_per_iteration = int(+ questions_per_iteration+ )# Create a new search object with these settingssystem.search = get_search(diff --git a/src/local_deep_research/web/static/css/styles.css b/src/local_deep_research/web/static/css/styles.cssindex 40d009e7c3..7b18c6357b 100644--- a/src/local_deep_research/web/static/css/styles.css+++ b/src/local_deep_research/web/static/css/styles.css@@ -1678,6 +1678,14 @@ textarea:focus, input[type="text"]:focus {transition: all 0.3s ease;}+/* Allow form controls to be interactive even when panel is collapsed */+.advanced-options-panel select,+.advanced-options-panel input,+.advanced-options-panel button,+.advanced-options-panel textarea {+ pointer-events: auto;+}+.advanced-options-toggle.open + .advanced-options-panel,.advanced-options-panel.expanded {max-height: 1000px;diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.jsindex 0dead96539..a33ac52f9a 100644--- a/src/local_deep_research/web/static/js/components/research.js+++ b/src/local_deep_research/web/static/js/components/research.js@@ -145,7 +145,6 @@const lastSearchEngine = localStorage.getItem('lastUsedSearchEngine');const lastStrategy = localStorage.getItem('lastUsedStrategy') || 'source-based';- console.log('Local storage values:', { provider: lastProvider, model: lastModel, searchEngine: lastSearchEngine, strategy: lastStrategy });// Apply local storage values if availableif (lastProvider && modelProviderSelect) {@@ -160,7 +159,6 @@// Apply saved strategyconst strategySelect = document.getElementById('strategy');if (strategySelect && lastStrategy) {- console.log('Setting strategy from localStorage:', lastStrategy);strategySelect.value = lastStrategy;}@@ -195,8 +193,6 @@loadModelOptions(false),loadSearchEngineOptions(false)]).then(([modelData, searchEngineData]) => {- console.log('Data loaded successfully');-// After loading model data, update the UI with the loaded dataconst currentProvider = modelProviderSelect ? modelProviderSelect.value : (lastProvider || 'OLLAMA');updateModelOptionsForProvider(currentProvider, false);@@ -204,7 +200,6 @@// Update search engine optionsif (searchEngineData && Array.isArray(searchEngineData)) {searchEngineOptions = searchEngineData;- console.log('Loaded search engines:', searchEngineData.length);// Force search engine dropdown to update with new dataif (searchEngineDropdownList && window.setupCustomDropdown) {@@ -214,7 +209,6 @@searchEngineDropdownList,() => searchEngineOptions.length > 0 ? searchEngineOptions : [{ value: '', label: 'No search engines available' }],(value, item) => {- console.log('Search engine selected:', value, item);selectedSearchEngineValue = value;// Update the input field@@ -235,13 +229,11 @@// If we have a last selected search engine, try to select itif (lastSearchEngine) {- console.log('Trying to select last search engine:', lastSearchEngine);// Find the matching engineconst matchingEngine = searchEngineOptions.find(engine =>engine.value === lastSearchEngine || engine.id === lastSearchEngine);if (matchingEngine) {- console.log('Found matching search engine:', matchingEngine);searchEngineInput.value = matchingEngine.label;selectedSearchEngineValue = matchingEngine.value;@@ -1213,6 +1205,9 @@console.log('Loading settings from database...');let numApiCallsPending = 1;+ // Increase the API calls counter to include strategy loading+ numApiCallsPending = 3;+// Fetch the current settings from the settings APIfetch('/research/settings/api', {method: 'GET',@@ -1388,6 +1383,51 @@numApiCallsPending--;isInitializing = (numApiCallsPending === 0);});++ // Load search strategy setting+ fetch('/research/settings/api/search.search_strategy', {+ method: 'GET',+ headers: {+ 'Content-Type': 'application/json'+ }+ })+ .then(response => {+ if (!response.ok) {+ throw new Error(`API error: ${response.status}`);+ }+ return response.json();+ })+ .then(data => {+ console.log('Loaded strategy from database:', data);++ const strategySelect = document.getElementById('strategy');+ if (data && data.setting && data.setting.value && strategySelect) {+ const strategyValue = data.setting.value;+ console.log('Setting strategy to:', strategyValue);++ // Update the select element+ strategySelect.value = strategyValue;++ // Save to localStorage+ localStorage.setItem('lastUsedStrategy', strategyValue);+ }++ numApiCallsPending--;+ isInitializing = (numApiCallsPending === 0);+ })+ .catch(error => {+ console.error('Error loading strategy:', error);++ // Fallback to localStorage+ const lastStrategy = localStorage.getItem('lastUsedStrategy');+ const strategySelect = document.getElementById('strategy');+ if (lastStrategy && strategySelect) {+ strategySelect.value = lastStrategy;+ }++ numApiCallsPending--;+ isInitializing = (numApiCallsPending === 0);+ });}// Add a fallback function to use localStorage settingsdiff --git a/src/local_deep_research/web/static/js/components/results.js b/src/local_deep_research/web/static/js/components/results.jsindex 0120f9388d..2469e28c0f 100644--- a/src/local_deep_research/web/static/js/components/results.js+++ b/src/local_deep_research/web/static/js/components/results.js@@ -98,7 +98,7 @@resultsContainer.innerHTML = '<div class="text-center my-5"><i class="fas fa-spinner fa-pulse"></i><p class="mt-3">Loading research results...</p></div>';// Fetch result from API- const response = await fetch(`/research/api/history/report/${researchId}`);+ const response = await fetch(`/research/api/report/${researchId}`);if (!response.ok) {throw new Error(`HTTP error ${response.status}`);diff --git a/src/local_deep_research/web/static/js/research_form.js b/src/local_deep_research/web/static/js/research_form.jsindex 217c7235bf..2e69ba9929 100644--- a/src/local_deep_research/web/static/js/research_form.js+++ b/src/local_deep_research/web/static/js/research_form.js@@ -7,7 +7,6 @@ let globalSettings = {};document.addEventListener('DOMContentLoaded', function() {// Initialize the research form- console.log('DOM loaded, initializing research form');initResearchForm();});@@ -15,7 +14,6 @@ document.addEventListener('DOMContentLoaded', function() {* Initialize the research form with values from settings*/function initResearchForm() {- console.log('Initializing research form...');// Get form elementsconst iterationsInput = document.getElementById('iterations');const questionsInput = document.getElementById('questions_per_iteration');@@ -29,7 +27,6 @@ function initResearchForm() {return response.json();}).then(data => {- console.log('Loaded settings:', data);if (data && data.status === 'success' && data.settings) {// Find our specific settingsconst settings = data.settings;@@ -41,12 +38,10 @@ function initResearchForm() {for (const key in settings) {const setting = settings[key];if (key === 'search.iterations') {- console.log('Found iterations setting:', setting.value);iterationsInput.value = setting.value;}if (key === 'search.questions_per_iteration') {- console.log('Found questions setting:', setting.value);questionsInput.value = setting.value;}}@@ -56,7 +51,6 @@ function initResearchForm() {}}).catch(error => {- console.warn('Error loading research settings:', error);// Form will use default values if settings can't be loaded});@@ -88,7 +82,6 @@ function saveResearchSettings() {const iterations = document.getElementById('iterations').value;const questions = document.getElementById('questions_per_iteration').value;- console.log('Saving research settings:', { iterations, questions });// Get CSRF tokenconst csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');@@ -107,10 +100,8 @@ function saveResearchSettings() {}).then(response => response.json()).then(data => {- console.log('Settings saved:', data);}).catch(error => {- console.warn('Error saving research settings:', error);});}@@ -118,13 +109,17 @@ function saveResearchSettings() {* Initialize warning system*/function initializeWarnings() {- console.log('Initializing warning system...');// Check warnings on form loadcheckAndDisplayWarnings();// Monitor form changes for dynamic warningssetupWarningListeners();++ // Clear any stale warnings immediately when initializing+ setTimeout(() => {+ checkAndDisplayWarnings();+ }, 100);}/**@@ -135,7 +130,6 @@ function setupWarningListeners() {const providerSelect = document.getElementById('model_provider');if (providerSelect) {providerSelect.addEventListener('change', function() {- console.log('Provider changed to:', providerSelect.value);// Wait a bit longer for the saveProviderSetting API call to completesetTimeout(refetchSettingsAndUpdateWarnings, 500);});@@ -146,7 +140,6 @@ function setupWarningListeners() {if (typeof window.saveProviderSetting === 'function') {const originalSaveProviderSetting = window.saveProviderSetting;window.saveProviderSetting = function(providerValue) {- console.log('Intercepted saveProviderSetting call:', providerValue);// Call the original functionconst result = originalSaveProviderSetting.apply(this, arguments);// After it completes, refetch settings and update warnings@@ -155,10 +148,38 @@ function setupWarningListeners() {};}+ // Monitor search engine changes+ const searchEngineInput = document.getElementById('search_engine');+ if (searchEngineInput) {+ searchEngineInput.addEventListener('change', function() {+ // Refresh warnings immediately when search engine changes+ setTimeout(checkAndDisplayWarnings, 100);+ });+ }+const strategySelect = document.getElementById('strategy');if (strategySelect) {strategySelect.addEventListener('change', function() {- console.log('Strategy changed to:', strategySelect.value);++ // Save strategy to localStorage+ localStorage.setItem('lastUsedStrategy', strategySelect.value);++ // Save strategy to database+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;+ fetch('/research/settings/api/search.search_strategy', {+ method: 'PUT',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': csrfToken+ },+ body: JSON.stringify({ value: strategySelect.value })+ })+ .then(response => response.json())+ .then(data => {+ })+ .catch(error => {+ });+setTimeout(checkAndDisplayWarnings, 100);});}@@ -167,7 +188,6 @@ function setupWarningListeners() {if (typeof io !== 'undefined') {const socket = io();socket.on('settings_changed', function(data) {- console.log('Settings changed via WebSocket:', data);// Update global settings cacheif (data.settings) {Object.assign(globalSettings, data.settings);@@ -177,7 +197,6 @@ function setupWarningListeners() {});socket.on('connect', function() {- console.log('Connected to settings WebSocket');});}}@@ -186,7 +205,6 @@ function setupWarningListeners() {* Refetch settings from the server and update warnings*/function refetchSettingsAndUpdateWarnings() {- console.log('Refetching settings from server...');fetch('/research/settings/api').then(response => {@@ -196,7 +214,6 @@ function refetchSettingsAndUpdateWarnings() {return response.json();}).then(data => {- console.log('Refetched settings:', data);if (data && data.status === 'success' && data.settings) {// Update global settings cacheglobalSettings = data.settings;@@ -205,21 +222,28 @@ function refetchSettingsAndUpdateWarnings() {setTimeout(checkAndDisplayWarnings, 100);}).catch(error => {- console.warn('Error refetching settings:', error);// Still try to check warnings from backendsetTimeout(checkAndDisplayWarnings, 100);});}+/**+ * Manually clear all warnings (useful for debugging stale warnings)+ */+function clearAllWarnings() {+ displayWarnings([]);+}+// Make functions globally available for other scriptswindow.refetchSettingsAndUpdateWarnings = refetchSettingsAndUpdateWarnings;window.displayWarnings = displayWarnings;+window.clearAllWarnings = clearAllWarnings;+window.checkAndDisplayWarnings = checkAndDisplayWarnings;/*** Check warning conditions by fetching from backend*/function checkAndDisplayWarnings() {- console.log('Checking warning conditions from backend...');// Get warnings from backend API instead of calculating locallyfetch('/research/settings/api/warnings')@@ -237,7 +261,6 @@ function checkAndDisplayWarnings() {}}).catch(error => {- console.warn('Error fetching warnings from backend:', error);// Clear warnings on errordisplayWarnings([]);});@@ -304,7 +327,6 @@ function displayWarnings(warnings) {* Dismiss a warning by updating the setting*/function dismissWarning(dismissKey) {- console.log('Dismissing warning:', dismissKey);// Get CSRF tokenconst csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');@@ -322,14 +344,12 @@ function dismissWarning(dismissKey) {}).then(response => response.json()).then(data => {- console.log('Warning dismissed:', data);// Update global settings cacheglobalSettings[dismissKey] = { value: true };// Recheck warningscheckAndDisplayWarnings();}).catch(error => {- console.warn('Error dismissing warning:', error);});}diff --git a/src/local_deep_research/web/templates/components/sidebar.html b/src/local_deep_research/web/templates/components/sidebar.htmlindex 5984015898..1b86e1b0c8 100644--- a/src/local_deep_research/web/templates/components/sidebar.html+++ b/src/local_deep_research/web/templates/components/sidebar.html@@ -10,6 +10,12 @@<li {% if active_page == 'history' %}class="active"{% endif %} data-page="history"><a href="{{ url_for('research.history_page') }}"><i class="fas fa-history"></i> History</a></li>+ <li {% if active_page == 'benchmark' %}class="active"{% endif %} data-page="benchmark">+ <a href="{{ url_for('benchmark.index') }}"><i class="fas fa-tachometer-alt"></i> Benchmark</a>+ </li>+ <li {% if active_page == 'benchmark-results' %}class="active"{% endif %} data-page="benchmark-results">+ <a href="{{ url_for('benchmark.results') }}"><i class="fas fa-chart-line"></i> Benchmark Results</a>+ </li><li {% if active_page == 'metrics' %}class="active"{% endif %} data-page="metrics"><a href="{{ url_for('metrics.metrics_dashboard') }}"><i class="fas fa-chart-bar"></i> Metrics</a></li>diff --git a/src/local_deep_research/web/templates/pages/benchmark.html b/src/local_deep_research/web/templates/pages/benchmark.htmlnew file mode 100644index 0000000000..80dc572e50--- /dev/null+++ b/src/local_deep_research/web/templates/pages/benchmark.html@@ -0,0 +1,1959 @@+{% extends "base.html" %}+{% from "components/custom_dropdown.html" import render_dropdown %}++{% set active_page = 'benchmark' %}++{% block title %}Benchmark Configuration - Deep Research System{% endblock %}++{% block extra_head %}+<meta name="csrf-token" content="{{ csrf_token() }}">+<link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/custom_dropdown.css') }}">+<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>+<style>+.benchmark-card {+ width: 100%;+ margin: 0;+}++.dataset-config {+ border: 1px solid var(--border-color);+ border-radius: 8px;+ padding: 20px;+ margin-bottom: 20px;+ background: var(--card-bg);+}++.dataset-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: 15px;+}++.dataset-toggle {+ display: flex;+ align-items: center;+ gap: 10px;+}++.benchmark-progress {+ margin-top: 20px;+ padding: 20px;+ background: var(--card-bg);+ border-radius: 8px;+ border: 1px solid var(--border-color);+ display: none;+}++.progress-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: 15px;+}++.progress-bar {+ width: 100%;+ height: 20px;+ background: var(--bg-color);+ border-radius: 10px;+ overflow: hidden;+ margin-bottom: 15px;+}++.progress-fill {+ height: 100%;+ background: linear-gradient(90deg, var(--primary-color), var(--accent-color));+ width: 0%;+ transition: width 0.3s ease;+}++.metrics-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));+ gap: 15px;+ margin-top: 15px;+}++.metric-card {+ padding: 15px;+ background: var(--bg-color);+ border-radius: 6px;+ text-align: center;+}++.metric-value {+ font-size: 1.5rem;+ font-weight: bold;+ color: var(--primary-color);+}++.metric-label {+ font-size: 0.9rem;+ color: var(--text-muted);+ margin-top: 5px;+}++.dataset-accuracy {+ display: flex;+ justify-content: space-between;+ margin-top: 10px;+ padding: 10px;+ background: var(--bg-color);+ border-radius: 6px;+}++.alert {+ padding: 15px;+ border-radius: 6px;+ margin-bottom: 15px;+}++.alert-warning {+ background-color: #fff3cd;+ border: 1px solid #ffeaa7;+ color: #856404;+}++.alert i {+ margin-right: 8px;+}++/* Question and Results Display Styles */+.benchmark-section {+ margin-top: 20px;+}++.question-card {+ background: #1a1a1a;+ border: 1px solid #333;+ border-radius: 8px;+ padding: 15px;+ margin-bottom: 10px;+}++.question-content {+ margin-bottom: 10px;+}++.question-text {+ font-size: 1rem;+ line-height: 1.4;+ color: #e0e0e0;+ margin-bottom: 8px;+ padding: 10px;+ background: #2a2a2a;+ border-radius: 4px;+ border-left: 4px solid var(--primary-color);+}++.question-meta {+ display: flex;+ gap: 10px;+ font-size: 0.85rem;+ color: var(--text-muted);+}++.dataset-badge {+ background: var(--primary-color);+ color: white;+ padding: 2px 8px;+ border-radius: 12px;+ font-size: 0.8rem;+ font-weight: 500;+}++.search-count-badge {+ color: white;+ padding: 2px 6px;+ border-radius: 10px;+ font-size: 0.75rem;+ font-weight: 500;+ margin-left: 8px;+}++.search-count-badge.critical {+ background: #f44336; /* Red for 0-1 results */+}++.search-count-badge.warning {+ background: #ff9800; /* Orange for 2-4 results */+}++.search-count-badge.good {+ background: #4caf50; /* Green for 5+ results */+}++.processing-status {+ padding: 8px 12px;+ background: var(--bg-secondary);+ border-radius: 4px;+ font-size: 0.9rem;+ color: var(--text-muted);+}++.processing-status.processing {+ background: #e3f2fd;+ color: #1976d2;+}++.processing-status.completed {+ background: #e8f5e8;+ color: #2e7d32;+}++.result-card {+ background: #1a1a1a;+ border: 1px solid #333;+ border-radius: 6px;+ padding: 12px;+ margin-bottom: 8px;+ transition: border-color 0.2s;+}++.result-card.correct {+ border-left: 4px solid #4caf50;+}++.result-card.incorrect {+ border-left: 4px solid #f44336;+}++.result-header {+ display: flex;+ justify-content: between;+ align-items: center;+ margin-bottom: 8px;+ font-size: 0.85rem;+ color: #a0a0a0;+}++.result-status {+ font-weight: 600;+}++.result-status.correct {+ color: #4caf50;+}++.result-status.incorrect {+ color: #f44336;+}++.answer-comparison {+ display: grid;+ gap: 8px;+}++.answer-box {+ padding: 12px;+ border-radius: 4px;+ font-size: 0.95rem;+ line-height: 1.5;+ white-space: pre-wrap;+ word-break: break-word;+ min-height: 60px;+ color: #e0e0e0 !important;+}++.answer-box > div {+ margin-top: 5px;+ color: #e0e0e0 !important;+}++.model-answer {+ background: #1e2a3a;+ border-left: 4px solid #2196f3;+ color: #e0e0e0 !important;+}++.correct-answer {+ background: #1e3a1e;+ border-left: 4px solid #4caf50;+ color: #e0e0e0 !important;+}++.answer-label {+ font-size: 0.75rem;+ font-weight: 600;+ color: #a0a0a0;+ margin-bottom: 4px;+ text-transform: uppercase;+ letter-spacing: 0.5px;+}++.no-results {+ text-align: center;+ color: var(--text-muted);+ padding: 20px;+ font-style: italic;+}++#recent-results-container {+ max-height: 600px;+ overflow-y: auto;+}++/* Improved layout structure */+.page-content {+ width: 100%;+ max-width: none;+}++.benchmark-progress .card {+ width: 100%;+ max-width: none;+}++.form-group {+ width: 100%;+}++/* Better visual hierarchy */+.benchmark-guidelines {+ background: linear-gradient(135deg, #1e1e1e 0%, #2a2a2a 100%);+ border: 1px solid #404040;+ border-left: 4px solid var(--primary-color);+ border-radius: 8px;+ margin-bottom: 25px;+ box-shadow: 0 2px 8px rgba(0,0,0,0.3);+}++.guidelines-content {+ display: grid;+ grid-template-columns: 1fr auto;+ gap: 25px;+ align-items: start;+}++.guidelines-text {+ padding: 25px;+}++.guidelines-sidebar {+ min-width: 200px;+ background: rgba(var(--primary-color-rgb), 0.1);+ padding: 20px;+ border-radius: 0 8px 8px 0;+ text-align: center;+ border-left: 1px solid rgba(var(--primary-color-rgb), 0.2);+}++/* Enhanced form sections */+.form-section {+ background: #1a1a1a;+ border: 1px solid #333;+ border-radius: 8px;+ margin-bottom: 20px;+ overflow: hidden;+}++.form-section-header {+ background: linear-gradient(90deg, #2a2a2a 0%, #333 100%);+ padding: 15px 20px;+ border-bottom: 1px solid #404040;+}++.form-section-title {+ color: var(--primary-color);+ font-size: 1.1rem;+ font-weight: 600;+ margin: 0;+ display: flex;+ align-items: center;+ gap: 8px;+}++.form-section-content {+ padding: 20px;+}++/* Improved dataset configuration cards */+.dataset-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));+ gap: 20px;+}++.dataset-card {+ background: #1e1e1e;+ border: 2px solid #333;+ border-radius: 10px;+ padding: 20px;+ transition: all 0.3s ease;+ position: relative;+}++.dataset-card:hover {+ border-color: var(--primary-color);+ box-shadow: 0 4px 12px rgba(var(--primary-color-rgb), 0.2);+}++.dataset-card.disabled {+ opacity: 0.6;+ border-color: #555;+}++.dataset-header {+ display: flex;+ justify-content: space-between;+ align-items: flex-start;+ margin-bottom: 15px;+}++.dataset-info h3 {+ color: #e0e0e0;+ margin: 0 0 5px 0;+ font-size: 1.2rem;+}++.dataset-info p {+ color: #a0a0a0;+ margin: 0;+ font-size: 0.9rem;+}++.dataset-toggle {+ display: flex;+ align-items: center;+ gap: 8px;+}++/* Modern toggle switch */+.toggle-switch {+ position: relative;+ width: 50px;+ height: 24px;+ background: #555;+ border-radius: 12px;+ cursor: pointer;+ transition: background 0.3s;+}++.toggle-switch.active {+ background: var(--primary-color);+}++.toggle-switch::after {+ content: '';+ position: absolute;+ top: 2px;+ left: 2px;+ width: 20px;+ height: 20px;+ background: white;+ border-radius: 50%;+ transition: transform 0.3s;+}++.toggle-switch.active::after {+ transform: translateX(26px);+}++/* Enhanced input styling */+.form-control {+ background: #2a2a2a;+ border: 2px solid #404040;+ border-radius: 6px;+ padding: 10px 12px;+ color: #e0e0e0;+ font-size: 0.95rem;+ transition: border-color 0.3s, box-shadow 0.3s;+}++.form-control:focus {+ border-color: var(--primary-color);+ box-shadow: 0 0 0 3px rgba(var(--primary-color-rgb), 0.2);+ outline: none;+}++/* Responsive improvements */+@media (max-width: 1200px) {+ .guidelines-content {+ grid-template-columns: 1fr;+ }++ .guidelines-sidebar {+ border-radius: 0 0 8px 8px;+ border-left: none;+ border-top: 1px solid rgba(var(--primary-color-rgb), 0.2);+ }+}++@media (max-width: 768px) {+ .dataset-grid {+ grid-template-columns: 1fr;+ }++ .guidelines-text {+ padding: 20px;+ }++ .form-section-content {+ padding: 15px;+ }+}+++/* Performance Charts Styles */+.charts-section {+ margin-top: 20px;+}++.charts-grid {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 20px;+ margin-top: 15px;+}++.chart-container {+ background: #1a1a1a;+ border: 1px solid #333;+ border-radius: 8px;+ padding: 15px;+ height: 300px;+}++.chart-title {+ color: #e0e0e0;+ font-size: 1rem;+ font-weight: 600;+ margin-bottom: 10px;+ text-align: center;+}++.chart-canvas {+ width: 100% !important;+ height: 250px !important;+}++@media (max-width: 768px) {+ .charts-grid {+ grid-template-columns: 1fr;+ }+}+</style>+{% endblock %}++{% block content %}+<div class="page active" id="benchmark">+ <div class="page-header">+ <h1>Benchmark Configuration</h1>+ <p class="page-subtitle">Test and optimize your search configurations</p>+ <div style="margin-top: 10px;">+ <a href="{{ url_for('benchmark.results') }}" class="btn btn-secondary">+ <i class="fas fa-chart-line"></i> View Past Results+ </a>+ </div>+ </div>++ <!-- Benchmark Usage Guidelines -->+ <div class="benchmark-guidelines">+ <div class="guidelines-content">+ <div class="guidelines-text">+ <h3 style="color: var(--primary-color); margin-bottom: 15px; font-size: 1.3rem;">+ <i class="fas fa-info-circle"></i> Benchmark Guidelines+ </h3>+ <p style="margin-bottom: 12px; line-height: 1.6; color: #e0e0e0;">+ <strong>Purpose:</strong> Benchmarks are designed to help you evaluate if your configuration works well, not for research papers or production use.+ </p>+ <p style="margin-bottom: 12px; line-height: 1.6; color: #e0e0e0;">+ <strong>Responsible Usage:</strong> Please use reasonable example counts to avoid overwhelming search engines. The default of 75 examples provides a good balance for configuration testing.+ </p>+ <p style="margin-bottom: 18px; line-height: 1.6; color: #e0e0e0;">+ <strong>Requirements:</strong> Benchmarks require an OpenRouter API key for evaluation (Claude 3.7 Sonnet). Set <code style="background: #444; padding: 3px 6px; border-radius: 4px; color: #ffa726;">llm.openai_endpoint.api_key</code> in Settings.+ </p>+ <div style="background: rgba(255, 167, 38, 0.1); border: 1px solid rgba(255, 167, 38, 0.3); padding: 15px; border-radius: 8px; margin-top: 15px;">+ <h4 style="color: #ffa726; margin-bottom: 10px; font-size: 1rem; display: flex; align-items: center; gap: 8px;">+ <i class="fas fa-search"></i> Search Engine Recommendations+ </h4>+ <ul style="margin: 0; padding-left: 20px; font-size: 0.95rem; line-height: 1.5; color: #e0e0e0;">+ <li style="margin-bottom: 8px;"><strong style="color: #4caf50;">Tavily:</strong> Recommended for general knowledge benchmarks - AI-optimized search API, reliable results</li>+ <li style="margin-bottom: 8px;"><strong style="color: #2196f3;">Brave:</strong> Independent search engine but unknown why performance is lower - could be smaller index, different ranking algorithm, or API limitations</li>+ <li style="margin-bottom: 8px;"><strong style="color: #ff9800;">SearXNG:</strong> Often outperforms commercial APIs by aggregating multiple sources - shared resource, use moderate example counts</li>+ <li style="margin-bottom: 8px;"><strong style="color: #f44336;">Specialized engines (ArXiv, PubMed, Wikipedia):</strong> Shared resources that are useless for general SimpleQA questions - should not be used for this test</li>+ </ul>+ <div style="background: rgba(33, 150, 243, 0.1); border: 1px solid rgba(33, 150, 243, 0.3); padding: 12px; border-radius: 6px; margin-top: 12px;">+ <p style="margin: 0; font-size: 0.9rem; color: #e0e0e0;">+ <strong style="color: #2196f3;">🔧 For Shared Resources:</strong> When using SearXNG or other shared engines, reduce iterations and questions per iteration in Settings to minimize load on shared infrastructure.+ </p>+ </div>+ </div>+ </div>+ <div class="guidelines-sidebar">+ <div style="font-size: 2.5rem; color: var(--primary-color); margin-bottom: 12px;">+ <i class="fas fa-tachometer-alt"></i>+ </div>+ <div style="font-size: 1.2rem; font-weight: 600; color: #e0e0e0; margin-bottom: 8px;">+ Quick Check+ </div>+ <div style="font-size: 0.9rem; color: #a0a0a0; line-height: 1.4; margin-bottom: 15px;">+ Test your config with reasonable limits+ </div>+ <div style="background: rgba(var(--primary-color-rgb), 0.2); padding: 8px 12px; border-radius: 6px; font-size: 0.85rem; color: var(--primary-color); font-weight: 500;">+ 🎯 Configuration Testing+ </div>+ </div>+ </div>+ </div>++ <!-- Alert container -->+ <div id="benchmark-alert" class="settings-alert-container" style="display:none"></div>++ <div class="card benchmark-card">+ <div class="card-content">+ <form id="benchmark-form">++ <!-- Benchmark Name -->+ <div class="form-group">+ <label for="run_name">Benchmark Name (Optional)</label>+ <input type="text" id="run_name" name="run_name" class="form-control" placeholder="e.g., 'Test new search strategy'">+ <span class="input-help">Give your benchmark run a descriptive name</span>+ </div>++ <!-- Dataset Configuration -->+ <div class="form-group">+ <fieldset>+ <legend>Dataset Selection</legend>++ <!-- SimpleQA Dataset -->+ <div class="dataset-config">+ <div class="dataset-header">+ <div>+ <h3>SimpleQA</h3>+ <p>Fact-based questions with clear answers</p>+ </div>+ <div class="dataset-toggle">+ <input type="checkbox" id="simpleqa_enabled" checked>+ <label for="simpleqa_enabled">Enable</label>+ </div>+ </div>+ <div class="form-group">+ <label for="simpleqa_count">Number of Examples</label>+ <input type="number" id="simpleqa_count" name="simpleqa_count" value="50" min="1" max="500" class="form-control">+ <span class="input-help">Recommended: 50 examples provides good balance for configuration testing</span>+ </div>+ </div>++ <!-- BrowseComp Dataset -->+ <div class="dataset-config" style="border: 2px solid #f44336; background: #2a1e1e;">+ <div class="dataset-header">+ <div>+ <h3 style="color: #f44336;">BrowseComp</h3>+ <p style="color: #ccc;">Complex browsing and comparison tasks</p>+ <div style="background: #3a1e1e; border: 1px solid #f44336; color: #f44336; padding: 10px 12px; border-radius: 4px; margin-top: 10px; font-size: 0.85rem; line-height: 1.4;">+ <i class="fas fa-exclamation-triangle"></i> <strong>Poor Performance Warning:</strong> We currently achieve close to 0% accuracy on BrowseComp.+ <br><strong>For testing only:</strong> Limited to 20 examples max to see what this benchmark is about.+ </div>+ </div>+ <div class="dataset-toggle">+ <input type="checkbox" id="browsecomp_enabled">+ <label for="browsecomp_enabled">Enable (Testing Only)</label>+ </div>+ </div>+ <div class="form-group">+ <label for="browsecomp_count">Number of Examples (Max 20)</label>+ <input type="number" id="browsecomp_count" name="browsecomp_count" value="0" min="0" max="20" class="form-control" disabled>+ <span class="input-help" style="color: #f44336;">Restricted to max 20 examples due to poor performance - for curiosity testing only</span>+ </div>+ </div>+ </fieldset>+ </div>++ <!-- Current Database Settings -->+ <div class="form-group">+ <fieldset>+ <legend>Current Configuration</legend>+ <div class="dataset-config" style="background: var(--bg-color); border: 1px solid var(--border-color);">+ <div class="dataset-header">+ <div>+ <h3>Active Database Settings</h3>+ <p>Benchmark will use all settings from your database configuration</p>+ </div>+ </div>++ <div id="current-settings-display" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px; margin-bottom: 15px;">+ <div class="metric-card" style="text-align: left; padding: 10px;">+ <div class="metric-label">Provider</div>+ <div class="metric-value" style="font-size: 0.9rem;" id="current-provider">Loading...</div>+ </div>+ <div class="metric-card" style="text-align: left; padding: 10px;">+ <div class="metric-label">Model</div>+ <div class="metric-value" style="font-size: 0.9rem;" id="current-model">Loading...</div>+ </div>+ <div class="metric-card" style="text-align: left; padding: 10px;">+ <div class="metric-label">Search Tool</div>+ <div class="metric-value" style="font-size: 0.9rem;" id="current-search-tool">Loading...</div>+ </div>+ <div class="metric-card" style="text-align: left; padding: 10px;">+ <div class="metric-label">Iterations</div>+ <div class="metric-value" style="font-size: 0.9rem;" id="current-iterations">Loading...</div>+ </div>+ <div class="metric-card" style="text-align: left; padding: 10px;">+ <div class="metric-label">Questions/Iter</div>+ <div class="metric-value" style="font-size: 0.9rem;" id="current-questions">Loading...</div>+ </div>+ <div class="metric-card" style="text-align: left; padding: 10px;">+ <div class="metric-label">Strategy</div>+ <div class="metric-value" style="font-size: 0.9rem;" id="current-strategy">Loading...</div>+ </div>+ </div>++ <div style="font-size: 0.9rem; color: var(--text-muted); text-align: center;">+ <i class="fas fa-info-circle"></i> To change any settings, go to <a href="/research/" target="_blank" style="color: var(--primary-color);">Settings Dashboard</a>+ </div>+ </div>+ </fieldset>+ </div>++ <!-- Search Engine Warning -->+ <div class="form-group" id="search-engine-warning" style="display: none;">+ <div class="alert" style="background: #2d1b1b; border: 1px solid #f44336; color: #ffffff; padding: 15px; border-radius: 6px;">+ <i class="fas fa-exclamation-triangle" style="color: #f44336; margin-right: 8px;"></i>+ <strong style="color: #f44336;">Search Engine Notice:</strong>+ <span id="search-warning-text" style="color: #ffffff;"></span>+ </div>+ </div>++ <!-- Configuration Summary -->+ <div class="form-group">+ <div id="config-summary" class="metric-card">+ <div class="metric-value" id="total-examples">50</div>+ <div class="metric-label">Total Examples</div>+ <div style="margin-top: 10px; font-size: 0.9rem; color: var(--text-muted);">+ Estimated time: <span id="estimated-time">40-60 minutes</span>+ </div>+ </div>+ </div>+++ <!-- Action Buttons -->+ <div class="form-actions">+ <button type="button" id="validate-config-btn" class="btn btn-secondary">+ <i class="fas fa-check-circle"></i> Validate Configuration+ </button>+ <button type="submit" id="start-benchmark-btn" class="btn btn-primary">+ <i class="fas fa-play"></i> Start Benchmark+ </button>+ </div>+ </form>+ </div>+ </div>++ <!-- Progress Panel - Reusing research progress component -->+ <div id="benchmark-progress" class="benchmark-progress">+ <div class="card benchmark-card">+ <div class="card-content">+ <div class="progress-info">+ <div class="current-query-container">+ <div class="current-query-label">Current Benchmark:</div>+ <div id="current-benchmark" class="current-query"></div>+ </div>+ <div class="progress-container">+ <div class="progress-bar">+ <div id="progress-bar" class="progress-fill"></div>+ </div>+ <div id="progress-percentage" class="progress-percentage">0%</div>+ </div>+ <div class="status-container">+ <div class="status-label">Status:</div>+ <div id="status-text" class="status-indicator">Initializing</div>+ </div>+ <div class="task-container">+ <div class="task-label">Current Task:</div>+ <div id="current-task" class="task-text">Starting benchmark...</div>+ </div>++ <!-- Benchmark-specific metrics -->+ <div class="metrics-grid">+ <div class="metric-card">+ <div class="metric-value" id="overall-accuracy">--%</div>+ <div class="metric-label">Overall Accuracy</div>+ <div class="metric-subtitle" id="accuracy-confidence" style="font-size: 0.8rem; color: var(--text-muted); margin-top: 2px;">--</div>+ </div>+ <div class="metric-card">+ <div class="metric-value" id="estimated-time">--</div>+ <div class="metric-label">Est. Time Left</div>+ <div class="metric-subtitle" id="elapsed-time" style="font-size: 0.8rem; color: var(--text-muted); margin-top: 2px;">--</div>+ </div>+ <div class="metric-card">+ <div class="metric-value" id="completed-count">0</div>+ <div class="metric-label">Completed</div>+ </div>+ <div class="metric-card">+ <div class="metric-value" id="processing-rate">--</div>+ <div class="metric-label">Avg Time/Example</div>+ </div>+ </div>++ <!-- SearXNG Rate Limiting Warning in Progress -->+ <div id="rate-limit-warning" class="alert alert-warning" style="margin-top: 15px; margin-bottom: 15px; display: none;">+ <i class="fas fa-exclamation-triangle"></i>+ <strong>Rate Limiting Detected!</strong> SearXNG is blocking requests due to too many parallel searches.+ <br><small><strong>Quick fix:</strong> <code>docker restart searxng</code> or wait 5-10 minutes for limits to reset.</small>+ <br><small><strong>Prevention:</strong> Reduce iterations/questions per iteration in Settings.</small>+ </div>++ <div id="dataset-accuracies">+ <div class="dataset-accuracy">+ <span>SimpleQA: <strong id="simpleqa-accuracy">--%</strong></span>+ <span>BrowseComp: <strong id="browsecomp-accuracy">--%</strong></span>+ </div>+ </div>++ <!-- Benchmark Control Actions -->+ <div class="progress-actions" style="margin: 20px 0; text-align: center;">+ <button id="cancel-benchmark-btn" class="btn btn-outline terminate-btn">+ <i class="fas fa-stop-circle"></i> Cancel Benchmark+ </button>+ <button id="view-results-btn" class="btn btn-primary" style="display: none;">+ <i class="fas fa-eye"></i> View Results+ </button>+ </div>++ <!-- Current Question Display -->+ <div id="current-question-section" class="benchmark-section" style="margin-top: 20px;">+ <h4 style="color: var(--primary-color); margin-bottom: 15px;">+ <i class="fas fa-question-circle"></i> Current Question+ </h4>+ <div id="current-question-card" class="question-card">+ <div class="question-content">+ <div class="question-text" id="current-question-text">No question being processed...</div>+ <div class="question-meta">+ <span class="dataset-badge" id="current-dataset">--</span>+ <span class="example-id" id="current-example-id">--</span>+ </div>+ </div>+ <div class="processing-status" id="current-processing-status">+ <i class="fas fa-clock"></i> Waiting for benchmark to start...+ </div>+ </div>+ </div>++ <!-- Performance Charts -->+ <div id="performance-charts-section" class="charts-section" style="display: none;">+ <h4 style="color: var(--primary-color); margin-bottom: 15px;">+ <i class="fas fa-chart-line"></i> Performance Analysis+ </h4>+ <div class="charts-grid">+ <div class="chart-container">+ <div class="chart-title">Accuracy Trend</div>+ <canvas id="accuracy-chart" class="chart-canvas"></canvas>+ </div>+ <div class="chart-container">+ <div class="chart-title">Processing Time per Example</div>+ <canvas id="timing-chart" class="chart-canvas"></canvas>+ </div>+ </div>+ <div class="charts-grid" style="margin-top: 20px;">+ <div class="chart-container">+ <div class="chart-title">Search Results Count</div>+ <canvas id="search-results-chart" class="chart-canvas"></canvas>+ </div>+ <div class="chart-container">+ <div class="chart-title">Search Quality Alert</div>+ <div id="search-quality-status" style="padding: 20px; text-align: center; color: #e0e0e0;">+ <div id="search-status-icon" style="font-size: 2rem; margin-bottom: 10px;">+ <i class="fas fa-search"></i>+ </div>+ <div id="search-status-text" style="font-size: 1.1rem; margin-bottom: 10px;">+ Waiting for data...+ </div>+ <div id="search-status-details" style="font-size: 0.9rem; color: #a0a0a0;">+ Search result monitoring will begin when benchmark starts+ </div>+ </div>+ </div>+ </div>+ </div>++ <!-- All Results Display -->+ <div id="recent-results-section" class="benchmark-section" style="margin-top: 20px;">+ <h4 style="color: var(--primary-color); margin-bottom: 15px;">+ <i class="fas fa-history"></i> All Results+ </h4>+ <div id="recent-results-container">+ <div class="no-results">No results yet...</div>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+</div>++<script>+// Benchmark configuration and progress tracking+let currentBenchmarkId = null;+let progressInterval = null;++// Charts for performance tracking+let accuracyChart = null;+let timingChart = null;+let searchResultsChart = null;+let chartData = {+ examples: [],+ accuracies: [],+ processingTimes: [],+ timestamps: [],+ searchResultCounts: []+};++// Search quality monitoring+let recentSearchCounts = [];+let searchQualityAlert = false;++document.addEventListener('DOMContentLoaded', function() {+ // Initialize socket service first+ if (window.socket && typeof window.socket.initializeSocket === 'function') {+ console.log('Initializing socket service...');+ window.socket.initializeSocket();+ }++ initializeBenchmarkForm();+ loadCurrentSettings();+ updateConfigSummary();+ checkForRunningBenchmark(); // Check if there's already a benchmark running+});++function initializeBenchmarkForm() {+ const form = document.getElementById('benchmark-form');+ const validateBtn = document.getElementById('validate-config-btn');+ const cancelBtn = document.getElementById('cancel-benchmark-btn');++ // Form submission+ form.addEventListener('submit', function(e) {+ e.preventDefault();+ startBenchmark();+ });++ // Validate configuration+ validateBtn.addEventListener('click', validateConfiguration);++ // Cancel benchmark+ cancelBtn.addEventListener('click', cancelBenchmark);++ // Update summary when inputs change+ const inputs = form.querySelectorAll('input, select');+ inputs.forEach(input => {+ input.addEventListener('change', updateConfigSummary);+ });++ // Toggle dataset sections+ document.getElementById('simpleqa_enabled').addEventListener('change', function() {+ document.getElementById('simpleqa_count').disabled = !this.checked;+ updateConfigSummary();+ });++ // BrowseComp is disabled, so no event listener needed++}++function updateConfigSummary() {+ const simpleqaEnabled = document.getElementById('simpleqa_enabled').checked;+ const browsecompEnabled = document.getElementById('browsecomp_enabled').checked;+ const simpleqaCount = simpleqaEnabled ? parseInt(document.getElementById('simpleqa_count').value) || 0 : 0;+ const browsecompCount = browsecompEnabled ? parseInt(document.getElementById('browsecomp_count').value) || 0 : 0;++ const totalExamples = simpleqaCount + browsecompCount;+ document.getElementById('total-examples').textContent = totalExamples;++ // Estimate time (roughly 1-2 minutes per example)+ const estimatedMinutes = Math.round(totalExamples * 1.5);+ const estimatedTime = estimatedMinutes < 60 ?+ `${estimatedMinutes} minutes` :+ `${Math.round(estimatedMinutes/60)} hour${estimatedMinutes >= 120 ? 's' : ''}`;+ document.getElementById('estimated-time').textContent = estimatedTime;+}++function validateConfiguration() {+ const config = getConfigurationData();++ fetch('/benchmark/api/validate-config', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(config)+ })+ .then(response => response.json())+ .then(data => {+ if (data.valid) {+ showAlert('Configuration is valid! Ready to start benchmark.', 'success');+ } else {+ showAlert('Configuration errors: ' + data.errors.join(', '), 'error');+ }+ })+ .catch(error => {+ console.error('Validation error:', error);+ showAlert('Error validating configuration: ' + error.message, 'error');+ });+}++function getConfigurationData() {+ const simpleqaEnabled = document.getElementById('simpleqa_enabled').checked;+ const browsecompEnabled = document.getElementById('browsecomp_enabled').checked;++ const datasets_config = {};+ if (simpleqaEnabled) {+ datasets_config.simpleqa = {+ count: parseInt(document.getElementById('simpleqa_count').value) || 0+ };+ }+ if (browsecompEnabled) {+ datasets_config.browsecomp = {+ count: parseInt(document.getElementById('browsecomp_count').value) || 0+ };+ }++ return {+ run_name: document.getElementById('run_name').value,+ datasets_config: datasets_config+ // All other config will be taken from database by the backend+ };+}++function startBenchmark() {+ const config = getConfigurationData();++ // Disable form+ document.getElementById('benchmark-form').style.display = 'none';+ document.getElementById('benchmark-progress').style.display = 'block';++ fetch('/benchmark/api/start', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(config)+ })+ .then(response => response.json())+ .then(data => {+ if (data.success) {+ currentBenchmarkId = data.benchmark_run_id;+ showAlert('Benchmark started successfully!', 'success');+ startProgressTracking();+ } else {+ showAlert('Error starting benchmark: ' + data.error, 'error');+ resetForm();+ }+ })+ .catch(error => {+ console.error('Start error:', error);+ showAlert('Error starting benchmark: ' + error.message, 'error');+ resetForm();+ });+}++function startProgressTracking() {+ if (!currentBenchmarkId) return;++ // Initialize charts+ initializeCharts();++ // Show charts section+ document.getElementById('performance-charts-section').style.display = 'block';++ // Load historical data if reconnecting to running benchmark+ setTimeout(() => {+ loadHistoricalChartData();+ }, 1000);++ progressInterval = setInterval(() => {+ updateBenchmarkProgress();+ }, 2000); // Update every 2 seconds++ // Initialize socket if not already done+ if (!window.socket || !window.socket.initializeSocket) {+ console.log('Socket service not available');+ } else if (!window.socket.socket) {+ console.log('Socket not initialized, initializing now...');+ window.socket.initializeSocket();+ }++ // Connect to WebSocket for detailed progress updates (reuse socket service)+ setTimeout(() => {+ if (window.socket && typeof window.socket.subscribeToResearch === 'function') {+ console.log('Subscribing to benchmark progress for ID:', currentBenchmarkId);+ // Subscribe to benchmark progress events using research subscription (same format)+ window.socket.subscribeToResearch(currentBenchmarkId, (eventData) => {+ handleDetailedProgress(eventData);+ });+ } else {+ console.warn('Socket service not available, falling back to polling only');+ }+ }, 500); // Small delay to ensure socket is ready+}++function handleDetailedProgress(data) {+ // Update current task display+ const currentTask = document.getElementById('current-task');+ if (currentTask && data.status) {+ currentTask.textContent = `Example ${data.example_id}: ${data.status}`;+ }++}++function updateBenchmarkProgress() {+ if (!currentBenchmarkId) return;++ fetch(`/benchmark/api/status/${currentBenchmarkId}`)+ .then(response => response.json())+ .then(data => {+ if (data.success) {+ const status = data.status;+ updateProgressDisplay(status);++ // Update question/answer displays+ updateCurrentQuestion(status);+ updateRecentResults();++ // Update charts with current data+ updateCharts(status);++ // Update search result monitoring+ updateSearchQualityMonitoring();++ // Update rate limiting status+ updateRateLimitingStatus();++ if (status.status === 'completed' || status.status === 'failed' || status.status === 'cancelled') {+ clearInterval(progressInterval);+ progressInterval = null;++ if (status.status === 'completed') {+ showAlert('Benchmark completed successfully!', 'success');+ } else {+ showAlert(`Benchmark ${status.status}: ${status.error_message || ''}`, 'error');+ }+ }+ }+ })+ .catch(error => {+ console.error('Progress update error:', error);+ });+}++function updateProgressDisplay(status) {+ const percentage = status.total_examples > 0 ?+ (status.completed_examples / status.total_examples * 100) : 0;++ // Update progress bar (using research progress component IDs)+ const progressBar = document.getElementById('progress-bar');+ const progressPercentage = document.getElementById('progress-percentage');+ const statusText = document.getElementById('status-text');+ const currentTask = document.getElementById('current-task');+ const currentBenchmark = document.getElementById('current-benchmark');++ if (progressBar) progressBar.style.width = percentage + '%';+ if (progressPercentage) progressPercentage.textContent = Math.round(percentage) + '%';+ if (statusText) statusText.textContent = status.status || 'Running';+ if (currentTask) currentTask.textContent = `Processing example ${status.completed_examples} of ${status.total_examples}`;+ if (currentBenchmark && status.run_name) currentBenchmark.textContent = status.run_name;++ // Update benchmark-specific metrics+ const overallAccuracy = document.getElementById('overall-accuracy');+ const accuracyConfidence = document.getElementById('accuracy-confidence');+ const estimatedTime = document.getElementById('estimated-time');+ const elapsedTime = document.getElementById('elapsed-time');+ const processingRate = document.getElementById('processing-rate');+ const completedCount = document.getElementById('completed-count');++ // Overall accuracy with confidence interval+ if (overallAccuracy) overallAccuracy.textContent =+ status.overall_accuracy ? status.overall_accuracy.toFixed(1) + '%' : '--%';++ if (accuracyConfidence && status.accuracy_confidence) {+ const conf = status.accuracy_confidence;+ accuracyConfidence.textContent =+ `±${conf.margin_of_error.toFixed(1)}% (95% CI, n=${conf.sample_size})`;+ } else if (accuracyConfidence) {+ accuracyConfidence.textContent = '--';+ }++ // Time estimates+ if (estimatedTime && status.estimated_time_remaining) {+ const minutes = Math.round(status.estimated_time_remaining / 60);+ estimatedTime.textContent = minutes > 0 ? `${minutes}m` : '<1m';+ } else if (estimatedTime) {+ estimatedTime.textContent = '--';+ }++ if (elapsedTime && status.total_elapsed_time) {+ const minutes = Math.round(status.total_elapsed_time / 60);+ elapsedTime.textContent = `${minutes}m elapsed`;+ } else if (elapsedTime) {+ elapsedTime.textContent = '--';+ }++ // Average processing time per example+ if (processingRate && status.avg_time_per_example) {+ const avgMinutes = (status.avg_time_per_example / 60).toFixed(1);+ processingRate.textContent = `${avgMinutes}m`;+ } else if (processingRate) {+ processingRate.textContent = '--';+ }++ if (completedCount) completedCount.textContent = status.completed_examples;++ // Update per-dataset accuracy displays+ const simpleqaAccuracy = document.getElementById('simpleqa-accuracy');+ const browsecompAccuracy = document.getElementById('browsecomp-accuracy');++ if (simpleqaAccuracy) simpleqaAccuracy.textContent =+ status.simpleqa_accuracy ? status.simpleqa_accuracy.toFixed(1) + '%' : '--%';+ if (browsecompAccuracy) browsecompAccuracy.textContent =+ status.browsecomp_accuracy ? status.browsecomp_accuracy.toFixed(1) + '%' : '--%';+}++function cancelBenchmark() {+ if (!currentBenchmarkId) return;++ fetch(`/benchmark/api/cancel/${currentBenchmarkId}`, {+ method: 'POST'+ })+ .then(response => response.json())+ .then(data => {+ if (data.success) {+ showAlert('Benchmark cancelled successfully.', 'info');+ clearInterval(progressInterval);+ progressInterval = null;+ resetForm();+ } else {+ showAlert('Error cancelling benchmark: ' + data.error, 'error');+ }+ })+ .catch(error => {+ console.error('Cancel error:', error);+ showAlert('Error cancelling benchmark: ' + error.message, 'error');+ });+}++function resetForm() {+ document.getElementById('benchmark-form').style.display = 'block';+ document.getElementById('benchmark-progress').style.display = 'none';+ document.getElementById('performance-charts-section').style.display = 'none';+ currentBenchmarkId = null;++ // Reset chart data+ chartData = {+ examples: [],+ accuracies: [],+ processingTimes: [],+ timestamps: [],+ searchResultCounts: []+ };++ // Reset search quality monitoring+ recentSearchCounts = [];+ searchQualityAlert = false;++ // Destroy existing charts+ if (accuracyChart) {+ accuracyChart.destroy();+ accuracyChart = null;+ }+ if (timingChart) {+ timingChart.destroy();+ timingChart = null;+ }+ if (searchResultsChart) {+ searchResultsChart.destroy();+ searchResultsChart = null;+ }++ if (progressInterval) {+ clearInterval(progressInterval);+ progressInterval = null;+ }+}++function showAlert(message, type) {+ const alertContainer = document.getElementById('benchmark-alert');+ alertContainer.innerHTML = `+ <div class="settings-alert alert-${type}">+ <span>${message}</span>+ <button type="button" class="close-alert" onclick="this.parentElement.parentElement.style.display='none'">+ <i class="fas fa-times"></i>+ </button>+ </div>+ `;+ alertContainer.style.display = 'block';++ // Auto-hide success messages+ if (type === 'success') {+ setTimeout(() => {+ alertContainer.style.display = 'none';+ }, 5000);+ }+}++function checkForRunningBenchmark() {+ // Check if there's a running benchmark when page loads+ fetch('/benchmark/api/running')+ .then(response => response.json())+ .then(data => {+ if (data.success && data.benchmark_run_id) {+ currentBenchmarkId = data.benchmark_run_id;+ showAlert(`Reconnected to running benchmark #${currentBenchmarkId}`, 'info');++ // Show progress panel and hide form+ document.getElementById('benchmark-form').style.display = 'none';+ document.getElementById('benchmark-progress').style.display = 'block';++ // Start tracking progress+ startProgressTracking();+ }+ })+ .catch(error => {+ console.log('No running benchmark found (this is normal)');+ });+}++// Load current settings from database and display them+async function loadCurrentSettings() {+ try {+ // Load all settings individually+ const [llmResponse, searchToolResponse, iterationsResponse, questionsResponse, strategyResponse] = await Promise.all([+ fetch('/research/settings/api/llm'),+ fetch('/research/settings/api/search.tool'),+ fetch('/research/settings/api/search.iterations'),+ fetch('/research/settings/api/search.questions_per_iteration'),+ fetch('/research/settings/api/search.search_strategy')+ ]);++ const llmData = await llmResponse.json();+ const searchToolData = await searchToolResponse.json();+ const iterationsData = await iterationsResponse.json();+ const questionsData = await questionsResponse.json();+ const strategyData = await strategyResponse.json();++ console.log('Loaded settings:', { llmData, searchToolData, iterationsData, questionsData, strategyData });++ // Display LLM settings+ if (llmData && llmData.settings && llmData.settings.value) {+ const settings = llmData.settings.value;++ document.getElementById('current-provider').textContent =+ settings.provider ? settings.provider.toUpperCase() : 'Not set';+ document.getElementById('current-model').textContent =+ settings.model || 'Not set';+ }++ // Display search tool and check for warnings+ if (searchToolData && searchToolData.settings && searchToolData.settings.value) {+ const searchTool = searchToolData.settings.value || 'Not set';+ document.getElementById('current-search-tool').textContent = searchTool;++ // Check for search engine warnings+ checkSearchEngineWarnings(searchTool);+ }++ // Display search iterations+ if (iterationsData && iterationsData.settings && iterationsData.settings.value) {+ document.getElementById('current-iterations').textContent =+ iterationsData.settings.value || '8';+ } else {+ document.getElementById('current-iterations').textContent = '8'; // default+ }++ // Display questions per iteration+ if (questionsData && questionsData.settings && questionsData.settings.value) {+ document.getElementById('current-questions').textContent =+ questionsData.settings.value || '5';+ } else {+ document.getElementById('current-questions').textContent = '5'; // default+ }++ // Display search strategy+ if (strategyData && strategyData.settings && strategyData.settings.value) {+ document.getElementById('current-strategy').textContent =+ strategyData.settings.value || 'focused_iteration';+ } else {+ document.getElementById('current-strategy').textContent = 'focused_iteration'; // default+ }++ } catch (error) {+ console.error('Error loading current settings:', error);+ document.querySelectorAll('#current-settings-display .metric-value').forEach(el => {+ el.textContent = 'Error loading';+ });+ showAlert('Could not load current settings. Using defaults.', 'warning');+ }+}++function updateCurrentQuestion(status) {+ const currentQuestionText = document.getElementById('current-question-text');+ const currentDataset = document.getElementById('current-dataset');+ const currentExampleId = document.getElementById('current-example-id');+ const currentProcessingStatus = document.getElementById('current-processing-status');++ if (status.status === 'in_progress') {+ currentProcessingStatus.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';+ currentProcessingStatus.className = 'processing-status processing';++ // Show progress info+ const progressText = `Processing example ${status.completed_examples + 1} of ${status.total_examples}`;+ currentQuestionText.textContent = progressText;+ currentDataset.textContent = 'Active';+ currentExampleId.textContent = `Example ${status.completed_examples + 1}`;+ } else if (status.status === 'completed') {+ currentProcessingStatus.innerHTML = '<i class="fas fa-check-circle"></i> Benchmark completed!';+ currentProcessingStatus.className = 'processing-status completed';+ currentQuestionText.textContent = 'All questions processed successfully.';+ currentDataset.textContent = 'Completed';+ currentExampleId.textContent = `${status.completed_examples}/${status.total_examples}`;+ } else {+ currentProcessingStatus.innerHTML = '<i class="fas fa-clock"></i> Waiting...';+ currentProcessingStatus.className = 'processing-status';+ currentQuestionText.textContent = 'No question being processed...';+ currentDataset.textContent = '--';+ currentExampleId.textContent = '--';+ }+}++function updateRecentResults() {+ if (!currentBenchmarkId) return;++ fetch(`/benchmark/api/results/${currentBenchmarkId}?limit=100`)+ .then(response => response.json())+ .then(data => {+ if (data.success && data.results) {+ displayRecentResults(data.results);+ }+ })+ .catch(error => {+ console.error('Error fetching all results:', error);+ });+}++function getSearchCountClass(count) {+ if (count <= 1) return 'critical';+ if (count <= 4) return 'warning';+ return 'good';+}++function displayRecentResults(results) {+ const container = document.getElementById('recent-results-container');++ if (!results || results.length === 0) {+ container.innerHTML = '<div class="no-results">No results yet...</div>';+ return;+ }++ const resultsHtml = results.map((result, index) => {+ const statusClass = result.is_correct ? 'correct' : 'incorrect';+ const statusIcon = result.is_correct ? '<i class="fas fa-check-circle"></i>' : '<i class="fas fa-times-circle"></i>';+ const statusText = result.is_correct ? 'Correct' : 'Incorrect';++ // Function to create expandable text+ const createExpandableText = (text, id, maxLength = 200) => {+ if (!text) return 'No answer provided';++ if (text.length <= maxLength) return text;++ const truncated = text.substring(0, maxLength) + '...';+ return `+ <span id="truncated-${id}">${truncated}</span>+ <span id="full-${id}" style="display: none;">${text}</span>+ <a href="#" onclick="toggleText('${id}'); return false;" id="toggle-${id}" style="color: #2196f3; font-size: 0.85rem; margin-left: 5px; text-decoration: underline;">Show more</a>+ `;+ };++ return `+ <div class="result-card ${statusClass}">+ <div class="result-header">+ <div>+ <span class="dataset-badge">${result.dataset_type}</span>+ <span class="example-id">${result.example_id}</span>+ ${result.search_result_count !== undefined ?+ `<span class="search-count-badge ${getSearchCountClass(result.search_result_count)}" title="Search results found">${result.search_result_count} results</span>` :+ ''}+ </div>+ <span class="result-status ${statusClass}">+ ${statusIcon} ${statusText}+ </span>+ </div>+ <div class="question-text" style="margin-bottom: 10px; font-size: 0.9rem;">+ ${result.question || 'No question provided'}+ </div>+ <div class="answer-comparison">+ <div class="answer-box model-answer">+ <div class="answer-label">Model Answer</div>+ <div>${createExpandableText(result.model_answer || 'No answer provided', `model-${index}`)}</div>+ </div>+ <div class="answer-box correct-answer">+ <div class="answer-label">Correct Answer</div>+ <div>${createExpandableText(result.correct_answer || 'No correct answer available', `correct-${index}`)}</div>+ </div>+ </div>+ </div>+ `;+ }).join('');++ container.innerHTML = resultsHtml;+}++// Toggle function for expandable text+function toggleText(id) {+ const truncated = document.getElementById(`truncated-${id}`);+ const full = document.getElementById(`full-${id}`);+ const toggle = document.getElementById(`toggle-${id}`);++ if (truncated.style.display === 'none') {+ truncated.style.display = 'inline';+ full.style.display = 'none';+ toggle.textContent = 'Show more';+ } else {+ truncated.style.display = 'none';+ full.style.display = 'inline';+ toggle.textContent = 'Show less';+ }+}++// Chart initialization and management+function initializeCharts() {+ const chartOptions = {+ responsive: true,+ maintainAspectRatio: false,+ plugins: {+ legend: {+ labels: {+ color: '#e0e0e0'+ }+ }+ },+ scales: {+ x: {+ ticks: {+ color: '#a0a0a0'+ },+ grid: {+ color: '#333'+ }+ },+ y: {+ ticks: {+ color: '#a0a0a0'+ },+ grid: {+ color: '#333'+ }+ }+ }+ };++ // Accuracy Chart+ const accuracyCtx = document.getElementById('accuracy-chart').getContext('2d');+ accuracyChart = new Chart(accuracyCtx, {+ type: 'line',+ data: {+ labels: [],+ datasets: [{+ label: 'Overall Accuracy',+ data: [],+ borderColor: '#4caf50',+ backgroundColor: 'rgba(76, 175, 80, 0.1)',+ tension: 0.4,+ fill: true+ }, {+ label: 'SimpleQA Accuracy',+ data: [],+ borderColor: '#2196f3',+ backgroundColor: 'rgba(33, 150, 243, 0.1)',+ tension: 0.4,+ fill: false+ }, {+ label: 'BrowseComp Accuracy',+ data: [],+ borderColor: '#ff9800',+ backgroundColor: 'rgba(255, 152, 0, 0.1)',+ tension: 0.4,+ fill: false+ }]+ },+ options: {+ ...chartOptions,+ scales: {+ ...chartOptions.scales,+ y: {+ ...chartOptions.scales.y,+ min: 0,+ max: 100,+ ticks: {+ ...chartOptions.scales.y.ticks,+ callback: function(value) {+ return value + '%';+ }+ }+ }+ }+ }+ });++ // Timing Chart+ const timingCtx = document.getElementById('timing-chart').getContext('2d');+ timingChart = new Chart(timingCtx, {+ type: 'line',+ data: {+ labels: [],+ datasets: [{+ label: 'Processing Time (seconds)',+ data: [],+ borderColor: '#e91e63',+ backgroundColor: 'rgba(233, 30, 99, 0.1)',+ tension: 0.4,+ fill: true+ }]+ },+ options: {+ ...chartOptions,+ scales: {+ ...chartOptions.scales,+ y: {+ ...chartOptions.scales.y,+ min: 0,+ ticks: {+ ...chartOptions.scales.y.ticks,+ callback: function(value) {+ return value + 's';+ }+ }+ }+ }+ }+ });++ // Search Results Chart+ const searchResultsCtx = document.getElementById('search-results-chart').getContext('2d');+ searchResultsChart = new Chart(searchResultsCtx, {+ type: 'line',+ data: {+ labels: [],+ datasets: [{+ label: 'Search Results Count',+ data: [],+ borderColor: '#9c27b0',+ backgroundColor: 'rgba(156, 39, 176, 0.1)',+ tension: 0.4,+ fill: true+ }]+ },+ options: {+ ...chartOptions,+ scales: {+ ...chartOptions.scales,+ y: {+ ...chartOptions.scales.y,+ min: 0,+ ticks: {+ ...chartOptions.scales.y.ticks,+ callback: function(value) {+ return Math.round(value) + ' results';+ }+ }+ }+ }+ }+ });+}++function updateCharts(status) {+ if (!accuracyChart || !timingChart || !searchResultsChart || !status) return;++ const currentExample = status.completed_examples;+ if (currentExample <= 0) return;++ // Update accuracy chart+ if (status.overall_accuracy !== undefined) {+ // Add new data point+ const labels = accuracyChart.data.labels;+ if (!labels.includes(currentExample)) {+ labels.push(currentExample);+ accuracyChart.data.datasets[0].data.push(status.overall_accuracy || 0);+ accuracyChart.data.datasets[1].data.push(status.simpleqa_accuracy || 0);+ accuracyChart.data.datasets[2].data.push(status.browsecomp_accuracy || 0);+ } else {+ // Update existing data point+ const index = labels.indexOf(currentExample);+ if (index >= 0) {+ accuracyChart.data.datasets[0].data[index] = status.overall_accuracy || 0;+ accuracyChart.data.datasets[1].data[index] = status.simpleqa_accuracy || 0;+ accuracyChart.data.datasets[2].data[index] = status.browsecomp_accuracy || 0;+ }+ }++ // Keep only last 50 data points+ if (labels.length > 50) {+ labels.shift();+ accuracyChart.data.datasets.forEach(dataset => dataset.data.shift());+ }++ accuracyChart.update('none');+ }++ // Update timing chart+ if (status.avg_time_per_example !== undefined) {+ const timingLabels = timingChart.data.labels;+ if (!timingLabels.includes(currentExample)) {+ timingLabels.push(currentExample);+ timingChart.data.datasets[0].data.push(status.avg_time_per_example || 0);+ } else {+ // Update existing data point+ const index = timingLabels.indexOf(currentExample);+ if (index >= 0) {+ timingChart.data.datasets[0].data[index] = status.avg_time_per_example || 0;+ }+ }++ // Keep only last 50 data points+ if (timingLabels.length > 50) {+ timingLabels.shift();+ timingChart.data.datasets[0].data.shift();+ }++ timingChart.update('none');+ }+}++// Load historical chart data when reconnecting to running benchmark+async function loadHistoricalChartData() {+ if (!currentBenchmarkId || !accuracyChart || !timingChart) return;++ try {+ // Get benchmark status to populate initial chart data+ const response = await fetch(`/benchmark/api/status/${currentBenchmarkId}`);+ const data = await response.json();++ if (data.success && data.status.completed_examples > 0) {+ // Create simulated historical data points for a smooth chart+ // In a real implementation, you'd store this data in the database+ const status = data.status;+ const totalCompleted = status.completed_examples;++ // Generate some sample points for the chart+ for (let i = 1; i <= totalCompleted; i += Math.max(1, Math.floor(totalCompleted / 20))) {+ accuracyChart.data.labels.push(i);+ // Use current accuracy as approximation (in real implementation, store historical values)+ accuracyChart.data.datasets[0].data.push(status.overall_accuracy || 0);+ accuracyChart.data.datasets[1].data.push(status.simpleqa_accuracy || 0);+ accuracyChart.data.datasets[2].data.push(status.browsecomp_accuracy || 0);++ timingChart.data.labels.push(i);+ timingChart.data.datasets[0].data.push(status.avg_time_per_example || 0);+ }++ accuracyChart.update();+ timingChart.update();+ }+ } catch (error) {+ console.error('Error loading historical chart data:', error);+ }+}++// Search quality monitoring functions+async function updateSearchQualityMonitoring() {+ if (!currentBenchmarkId) return;++ try {+ // Fetch recent results to get search counts+ const response = await fetch(`/benchmark/api/results/${currentBenchmarkId}?limit=5`);+ const data = await response.json();++ if (data.success && data.results && data.results.length > 0) {+ // Process search result counts (already calculated by backend)+ const recentResults = data.results;+ let totalSearchResults = 0;+ let validResults = 0;++ recentResults.forEach(result => {+ if (result.search_result_count !== undefined && result.search_result_count !== null) {+ totalSearchResults += result.search_result_count;+ validResults++;+ }+ });++ if (validResults > 0) {+ const avgSearchResults = totalSearchResults / validResults;+ updateSearchResultsChart(avgSearchResults);+ updateSearchQualityAlert(avgSearchResults);+ }+ }+ } catch (error) {+ console.error('Error updating search quality monitoring:', error);+ }+}++function updateSearchResultsChart(avgSearchResults) {+ if (!searchResultsChart || !currentBenchmarkId) return;++ // Get current timestamp or progress for x-axis+ const now = new Date().toLocaleTimeString();+ const labels = searchResultsChart.data.labels;++ // Always add new data point with timestamp+ labels.push(now);+ searchResultsChart.data.datasets[0].data.push(avgSearchResults);++ // Keep only last 20 data points for readability+ if (labels.length > 20) {+ labels.shift();+ searchResultsChart.data.datasets[0].data.shift();+ }++ // Store for alert monitoring+ recentSearchCounts.push(avgSearchResults);+ if (recentSearchCounts.length > 10) {+ recentSearchCounts.shift();+ }++ searchResultsChart.update('none');+}++function updateSearchQualityAlert(avgSearchResults) {+ const statusIcon = document.getElementById('search-status-icon');+ const statusText = document.getElementById('search-status-text');+ const statusDetails = document.getElementById('search-status-details');++ if (!statusIcon || !statusText || !statusDetails) return;++ // Determine alert level based on search result count+ let alertLevel = 'good';+ let alertMessage = '';+ let alertDetails = '';+ let alertIcon = 'fas fa-check-circle';+ let alertColor = '#4caf50';++ if (avgSearchResults < 2) {+ alertLevel = 'critical';+ alertMessage = 'CRITICAL: Very few search results';+ alertDetails = `Only ${avgSearchResults.toFixed(1)} results per query. Accuracy likely severely degraded.`;+ alertIcon = 'fas fa-exclamation-triangle';+ alertColor = '#f44336';++ // Show rate limit warning+ document.getElementById('rate-limit-warning').style.display = 'block';++ } else if (avgSearchResults < 5) {+ alertLevel = 'warning';+ alertMessage = 'WARNING: Low search results';+ alertDetails = `${avgSearchResults.toFixed(1)} results per query. Consider restarting SearXNG.`;+ alertIcon = 'fas fa-exclamation-circle';+ alertColor = '#ff9800';++ } else if (avgSearchResults < 10) {+ alertLevel = 'caution';+ alertMessage = 'CAUTION: Moderate search results';+ alertDetails = `${avgSearchResults.toFixed(1)} results per query. Performance may be affected.`;+ alertIcon = 'fas fa-info-circle';+ alertColor = '#2196f3';++ } else {+ alertLevel = 'good';+ alertMessage = 'GOOD: Healthy search results';+ alertDetails = `${avgSearchResults.toFixed(1)} results per query. Search engines working well.`;+ alertIcon = 'fas fa-check-circle';+ alertColor = '#4caf50';++ // Hide rate limit warning if it was shown+ document.getElementById('rate-limit-warning').style.display = 'none';+ }++ // Update UI+ statusIcon.innerHTML = `<i class="${alertIcon}"></i>`;+ statusIcon.style.color = alertColor;+ statusText.textContent = alertMessage;+ statusText.style.color = alertColor;+ statusDetails.textContent = alertDetails;++ // Trigger alert if we detect degradation+ if (alertLevel === 'critical' && !searchQualityAlert) {+ searchQualityAlert = true;+ showAlert('Search engine performance critically degraded! Consider restarting SearXNG.', 'error');+ } else if (alertLevel === 'warning' && !searchQualityAlert) {+ searchQualityAlert = true;+ showAlert('Search engine performance is declining. Monitor closely.', 'warning');+ } else if (alertLevel === 'good') {+ searchQualityAlert = false; // Reset alert flag when performance improves+ }+}++// Rate limiting status monitoring (simplified)+async function updateRateLimitingStatus() {+ try {+ const response = await fetch('/benchmark/api/search-quality');+ const data = await response.json();++ if (data.success && data.search_quality && data.search_quality.length > 0) {+ // Find SearXNG engine specifically (most critical for benchmarks)+ const searxngStats = data.search_quality.find(stat =>+ stat.engine_type.toLowerCase().includes('searxng')+ );++ if (searxngStats && searxngStats.recent_avg_results < 2) {+ // Show warning when search results are critically low+ console.warn('Low search results detected:', searxngStats);++ const statusDetails = document.getElementById('search-status-details');+ if (statusDetails && !statusDetails.textContent.includes('Very low results')) {+ statusDetails.textContent += ` Very low results: ${searxngStats.recent_avg_results.toFixed(1)} avg.`;+ }+ }+ }+ } catch (error) {+ console.error('Error fetching rate limiting status:', error);+ }+}++// Check for search engine warnings and display appropriate messages+function checkSearchEngineWarnings(searchTool) {+ const warningContainer = document.getElementById('search-engine-warning');+ const warningText = document.getElementById('search-warning-text');++ let showWarning = false;+ let message = '';++ switch (searchTool?.toLowerCase()) {+ case 'searxng':+ showWarning = true;+ message = 'SearXNG is a shared resource. Please use reasonable example counts to avoid affecting other users. Consider shorter benchmarks for testing.';+ break;+ case 'arxiv':+ showWarning = true;+ message = 'ArXiv is a shared resource containing only academic papers - benchmarking with SimpleQA is useless as it will find zero relevant results for general knowledge questions. Should not be used for this test. Use Tavily instead.';+ break;+ case 'pubmed':+ showWarning = true;+ message = 'PubMed is a shared resource containing only medical literature - benchmarking with SimpleQA is absolutely useless as general knowledge questions will find zero relevant results. Should not be used for this test. Use Tavily instead.';+ break;+ case 'semanticscholar':+ showWarning = true;+ message = 'Semantic Scholar is a shared resource specialized for academic research - not suitable for general SimpleQA questions and should not be used for this test. Use Tavily instead.';+ break;+ case 'wikipedia':+ showWarning = true;+ message = 'Wikipedia is a shared resource with limited coverage - benchmarking with it is useless for comprehensive testing and should not be used for this test. Use Tavily instead.';+ break;+ default:+ showWarning = false;+ }++ if (showWarning) {+ warningText.textContent = message;+ warningContainer.style.display = 'block';+ } else {+ warningContainer.style.display = 'none';+ }+}+</script>+{% endblock %}++{% block page_scripts %}+<!-- Load required services for progress tracking -->+<script src="{{ url_for('research.serve_static', path='js/services/audio.js') }}"></script>+<script src="{{ url_for('research.serve_static', path='js/services/ui.js') }}"></script>+<script src="{{ url_for('research.serve_static', path='js/services/formatting.js') }}"></script>+<script src="{{ url_for('research.serve_static', path='js/services/api.js') }}"></script>+<script src="{{ url_for('research.serve_static', path='js/services/socket.js') }}"></script>+{% endblock %}diff --git a/src/local_deep_research/web/templates/pages/benchmark_results.html b/src/local_deep_research/web/templates/pages/benchmark_results.htmlnew file mode 100644index 0000000000..9715467527--- /dev/null+++ b/src/local_deep_research/web/templates/pages/benchmark_results.html@@ -0,0 +1,1136 @@+{% extends "base.html" %}++{% set active_page = 'benchmark-results' %}++{% block title %}Benchmark Results History - Deep Research System{% endblock %}++{% block extra_head %}+<meta name="csrf-token" content="{{ csrf_token() }}">+<style>+.benchmark-results-card {+ width: 100%;+ margin: 0;+ padding: 0;+ background: transparent;+ border: none;+ box-shadow: none;+}++.card-content {+ padding: 0;+}++.run-card {+ background: #1a1a1a;+ border: 1px solid #333;+ border-radius: 8px;+ padding: 20px;+ margin-bottom: 20px;+ cursor: pointer;+ transition: border-color 0.2s, background-color 0.2s;+}++.run-card:hover {+ border-color: var(--primary-color);+ background: #1e1e1e;+}++.run-card.expanded {+ border-color: var(--primary-color);+}++.run-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: 10px;+}++.run-title {+ font-size: 1.2rem;+ font-weight: bold;+ color: #e0e0e0;+}++.run-date {+ color: #a0a0a0;+ font-size: 0.9rem;+}++.run-summary {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));+ gap: 12px;+ margin-bottom: 15px;+}++/* Responsive grid adjustments for more columns on wider screens */+@media (min-width: 768px) {+ .run-summary {+ grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));+ gap: 15px;+ }+}++@media (min-width: 1200px) {+ .run-summary {+ grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));+ gap: 16px;+ }+}++@media (min-width: 1600px) {+ .run-summary {+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));+ gap: 18px;+ }+}++@media (min-width: 1920px) {+ .run-summary {+ grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));+ gap: 20px;+ }+}++.summary-item {+ text-align: center;+ padding: 10px;+ background: #2a2a2a;+ border-radius: 6px;+}++.summary-value {+ font-size: 1.4rem;+ font-weight: bold;+ color: var(--primary-color);+}++.summary-label {+ font-size: 0.85rem;+ color: #a0a0a0;+ margin-top: 5px;+}++.accuracy-indicator {+ display: inline-block;+ padding: 4px 8px;+ border-radius: 12px;+ font-size: 0.85rem;+ font-weight: bold;+}++.accuracy-high {+ background: #1e3a1e;+ color: #4caf50;+}++.accuracy-medium {+ background: #3a2a1e;+ color: #ff9800;+}++.accuracy-low {+ background: #3a1e1e;+ color: #f44336;+}++.status-indicator {+ display: inline-block;+ padding: 4px 8px;+ border-radius: 12px;+ font-size: 0.85rem;+ font-weight: bold;+}++.status-completed {+ background: #1e3a1e;+ color: #4caf50;+}++.status-in-progress {+ background: #1e2a3a;+ color: #2196f3;+}++.status-failed {+ background: #3a1e1e;+ color: #f44336;+}++.status-cancelled {+ background: #2a2a2a;+ color: #999;+}++.run-config {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));+ gap: 10px;+ margin-bottom: 15px;+ padding: 15px;+ background: #242424;+ border-radius: 6px;+}++.config-item {+ display: flex;+ justify-content: space-between;+ padding: 5px 0;+ border-bottom: 1px solid #333;+}++.config-label {+ color: #a0a0a0;+ font-size: 0.9rem;+}++.config-value {+ color: #e0e0e0;+ font-weight: 500;+}++.results-section {+ margin-top: 20px;+ display: none;+}++.results-section.visible {+ display: block;+}++.examples-grid {+ display: grid;+ gap: 15px;+ margin-top: 15px;+}++.example-card {+ background: #1a1a1a;+ border: 1px solid #333;+ border-radius: 6px;+ padding: 15px;+}++.example-card.correct {+ border-left: 4px solid #4caf50;+}++.example-card.incorrect {+ border-left: 4px solid #f44336;+}++.example-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: 10px;+}++.example-status {+ display: flex;+ align-items: center;+ gap: 5px;+ font-weight: 600;+}++.example-status.correct {+ color: #4caf50;+}++.example-status.incorrect {+ color: #f44336;+}++.example-question {+ background: #2a2a2a;+ padding: 12px;+ border-radius: 4px;+ border-left: 4px solid var(--primary-color);+ margin-bottom: 12px;+ color: #e0e0e0;+}++.example-answers {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 12px;+}++.answer-section {+ padding: 10px;+ border-radius: 4px;+ font-size: 0.9rem;+ line-height: 1.4;+}++.model-answer-section {+ background: #1e2a3a;+ border-left: 3px solid #2196f3;+}++.correct-answer-section {+ background: #1e3a1e;+ border-left: 3px solid #4caf50;+}++.answer-label {+ font-size: 0.75rem;+ font-weight: 600;+ color: #a0a0a0;+ text-transform: uppercase;+ margin-bottom: 6px;+}++.answer-text {+ color: #e0e0e0;+}++.no-results {+ text-align: center;+ color: #a0a0a0;+ padding: 40px;+ font-style: italic;+}++.expand-indicator {+ color: #a0a0a0;+ font-size: 0.9rem;+ margin-top: 10px;+ text-align: center;+}++.dataset-breakdown {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));+ gap: 10px;+ margin-top: 10px;+}++.dataset-item {+ text-align: center;+ padding: 8px;+ background: #2a2a2a;+ border-radius: 4px;+}++.dataset-name {+ font-size: 0.8rem;+ color: #a0a0a0;+ margin-bottom: 4px;+}++.dataset-accuracy {+ font-weight: bold;+ color: var(--primary-color);+}++.loading {+ text-align: center;+ padding: 40px;+ color: #a0a0a0;+}++.pagination {+ display: flex;+ justify-content: center;+ align-items: center;+ gap: 10px;+ margin-top: 30px;+}++.pagination button {+ padding: 8px 12px;+ background: #2a2a2a;+ border: 1px solid #333;+ border-radius: 4px;+ color: #e0e0e0;+ cursor: pointer;+}++.pagination button:hover {+ background: var(--primary-color);+}++.pagination button:disabled {+ opacity: 0.5;+ cursor: not-allowed;+}++.delete-btn {+ background: #3a1e1e !important;+ border-color: #f44336 !important;+ color: #f44336 !important;+ font-size: 0.8rem;+ padding: 4px 8px;+ transition: all 0.2s;+}++.delete-btn:hover:not(:disabled) {+ background: #f44336 !important;+ color: white !important;+}++.delete-btn:disabled {+ background: #2a2a2a !important;+ border-color: #555 !important;+ color: #888 !important;+ cursor: not-allowed;+}++.filters {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));+ gap: 15px;+ margin-bottom: 20px;+}++/* Responsive filter adjustments for full-width layout */+@media (max-width: 767px) {+ .filters {+ grid-template-columns: 1fr 1fr;+ gap: 12px;+ }+}++@media (min-width: 768px) {+ .filters {+ grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));+ gap: 16px;+ }+}++@media (min-width: 1200px) {+ .filters {+ grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));+ gap: 18px;+ }+}++@media (min-width: 1600px) {+ .filters {+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));+ gap: 20px;+ }+}++.processing-time {+ background: #2a3f2a;+ color: #90ee90;+ padding: 2px 6px;+ border-radius: 3px;+ font-size: 0.8rem;+ font-weight: 500;+ white-space: nowrap;+}++.filter-group {+ display: flex;+ flex-direction: column;+ gap: 5px;+}++.filter-group label {+ font-size: 0.85rem;+ color: #a0a0a0;+}++.filter-group select,+.filter-group input {+ padding: 6px 10px;+ background: #2a2a2a;+ border: 1px solid #333;+ border-radius: 4px;+ color: #e0e0e0;+}++.search-stats-section {+ margin-bottom: 20px;+ padding: 15px;+ background: #1e1e1e;+ border: 1px solid #333;+ border-radius: 6px;+}++.section-title {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-bottom: 15px;+ color: #e0e0e0;+ font-size: 1.1rem;+ font-weight: 600;+}++.search-stats-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));+ gap: 15px;+}++.stat-item {+ text-align: center;+ padding: 12px;+ background: #2a2a2a;+ border-radius: 6px;+}++.stat-value {+ font-size: 1.4rem;+ font-weight: bold;+ color: var(--primary-color);+ margin-bottom: 5px;+}++.stat-label {+ font-size: 0.85rem;+ color: #a0a0a0;+}++.results-divider {+ height: 1px;+ background: #333;+ margin: 20px 0;+}++.examples-section {+ margin-top: 15px;+}++.example-metrics {+ display: flex;+ gap: 10px;+ align-items: center;+}++.search-results-count {+ background: #2a3a3a;+ color: #81c784;+ padding: 2px 6px;+ border-radius: 3px;+ font-size: 0.8rem;+ font-weight: 500;+ white-space: nowrap;+}+</style>+{% endblock %}++{% block content %}+<div class="page active" id="benchmark-results">+ <div class="page-header">+ <h1>Benchmark Results History</h1>+ <p class="page-subtitle">Compare accuracy across different models, search engines, and strategies</p>+ </div>++ <div class="card benchmark-results-card">+ <div class="card-content">+ <!-- Filters -->+ <div class="filters">+ <div class="filter-group">+ <label for="accuracy-filter">Accuracy Range</label>+ <select id="accuracy-filter">+ <option value="">All</option>+ <option value="high">90%+ (High)</option>+ <option value="medium">70-90% (Medium)</option>+ <option value="low"><70% (Low)</option>+ </select>+ </div>+ <div class="filter-group">+ <label for="model-filter">Model</label>+ <select id="model-filter">+ <option value="">All Models</option>+ </select>+ </div>+ <div class="filter-group">+ <label for="strategy-filter">Strategy</label>+ <select id="strategy-filter">+ <option value="">All Strategies</option>+ </select>+ </div>+ <div class="filter-group">+ <label for="status-filter">Status</label>+ <select id="status-filter">+ <option value="">All Statuses</option>+ <option value="completed">Completed</option>+ <option value="in_progress">In Progress</option>+ <option value="failed">Failed</option>+ <option value="cancelled">Cancelled</option>+ </select>+ </div>+ <div class="filter-group">+ <label for="date-filter">Date Range</label>+ <input type="date" id="date-from">+ <input type="date" id="date-to">+ </div>+ </div>++ <!-- Results List -->+ <div id="results-container">+ <div class="loading">+ <i class="fas fa-spinner fa-spin"></i> Loading benchmark results...+ </div>+ </div>++ <!-- Pagination -->+ <div class="pagination" id="pagination" style="display: none;">+ <button id="prev-page">← Previous</button>+ <span id="page-info">Page 1 of 1</span>+ <button id="next-page">Next →</button>+ </div>+ </div>+ </div>+</div>++<script>+let benchmarkRuns = [];+let filteredRuns = [];+let currentPage = 1;+const itemsPerPage = 20;++document.addEventListener('DOMContentLoaded', function() {+ loadBenchmarkHistory();+ setupFilters();+});++async function loadBenchmarkHistory() {+ try {+ const response = await fetch('/benchmark/api/history');+ const data = await response.json();++ if (data.success) {+ benchmarkRuns = data.runs;+ filteredRuns = [...benchmarkRuns];+ populateFilters();+ displayResults();+ } else {+ document.getElementById('results-container').innerHTML =+ '<div class="no-results">Error loading benchmark results</div>';+ }+ } catch (error) {+ console.error('Error loading benchmark history:', error);+ document.getElementById('results-container').innerHTML =+ '<div class="no-results">Error loading benchmark results</div>';+ }+}++function populateFilters() {+ // Populate model filter+ const models = [...new Set(benchmarkRuns.map(run =>+ run.search_config?.model_name).filter(Boolean))];+ const modelFilter = document.getElementById('model-filter');+ models.forEach(model => {+ const option = document.createElement('option');+ option.value = model;+ option.textContent = model;+ modelFilter.appendChild(option);+ });++ // Populate strategy filter+ const strategies = [...new Set(benchmarkRuns.map(run =>+ run.search_config?.search_strategy).filter(Boolean))];+ const strategyFilter = document.getElementById('strategy-filter');+ strategies.forEach(strategy => {+ const option = document.createElement('option');+ option.value = strategy;+ option.textContent = strategy.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());+ strategyFilter.appendChild(option);+ });+}++function setupFilters() {+ document.getElementById('accuracy-filter').addEventListener('change', applyFilters);+ document.getElementById('model-filter').addEventListener('change', applyFilters);+ document.getElementById('strategy-filter').addEventListener('change', applyFilters);+ document.getElementById('status-filter').addEventListener('change', applyFilters);+ document.getElementById('date-from').addEventListener('change', applyFilters);+ document.getElementById('date-to').addEventListener('change', applyFilters);+}++function applyFilters() {+ const accuracyFilter = document.getElementById('accuracy-filter').value;+ const modelFilter = document.getElementById('model-filter').value;+ const strategyFilter = document.getElementById('strategy-filter').value;+ const statusFilter = document.getElementById('status-filter').value;+ const dateFrom = document.getElementById('date-from').value;+ const dateTo = document.getElementById('date-to').value;++ filteredRuns = benchmarkRuns.filter(run => {+ // Accuracy filter+ if (accuracyFilter) {+ const accuracy = run.overall_accuracy || 0;+ if (accuracyFilter === 'high' && accuracy < 90) return false;+ if (accuracyFilter === 'medium' && (accuracy < 70 || accuracy >= 90)) return false;+ if (accuracyFilter === 'low' && accuracy >= 70) return false;+ }++ // Model filter+ if (modelFilter && run.search_config?.model_name !== modelFilter) return false;++ // Strategy filter+ if (strategyFilter && run.search_config?.search_strategy !== strategyFilter) return false;++ // Status filter+ if (statusFilter && run.status !== statusFilter) return false;++ // Date filters+ const runDate = new Date(run.created_at).toISOString().split('T')[0];+ if (dateFrom && runDate < dateFrom) return false;+ if (dateTo && runDate > dateTo) return false;++ return true;+ });++ currentPage = 1;+ displayResults();+}++function displayResults() {+ const container = document.getElementById('results-container');++ if (filteredRuns.length === 0) {+ container.innerHTML = '<div class="no-results">No benchmark results found</div>';+ document.getElementById('pagination').style.display = 'none';+ return;+ }++ const startIndex = (currentPage - 1) * itemsPerPage;+ const endIndex = Math.min(startIndex + itemsPerPage, filteredRuns.length);+ const pageRuns = filteredRuns.slice(startIndex, endIndex);++ const html = pageRuns.map(run => createRunCard(run)).join('');+ container.innerHTML = html;++ // Setup pagination+ setupPagination();+}++function createRunCard(run) {+ const accuracy = run.overall_accuracy || 0;+ const accuracyClass = accuracy >= 90 ? 'accuracy-high' :+ accuracy >= 70 ? 'accuracy-medium' : 'accuracy-low';++ // Status handling+ const status = run.status || 'unknown';+ const statusClass = `status-${status.replace('_', '-')}`;+ const statusText = status.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase());++ const date = new Date(run.created_at).toLocaleDateString();+ const time = new Date(run.created_at).toLocaleTimeString();++ // Progress calculation+ const progress = run.total_examples > 0 ?+ ((run.completed_examples / run.total_examples) * 100).toFixed(1) : 0;++ // Format status text with proper capitalization+ const formattedStatus = status.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());++ return `+ <div class="run-card" onclick="toggleRunDetails(${run.id})">+ <div class="run-header">+ <div class="run-title">${run.run_name}</div>+ <div class="run-date">${date} ${time}</div>+ </div>++ <div class="run-summary">+ <div class="summary-item">+ <div class="summary-value ${statusClass} status-indicator">${formattedStatus}</div>+ <div class="summary-label">Status</div>+ </div>+ <div class="summary-item">+ <div class="summary-value">${run.completed_examples}/${run.total_examples}</div>+ <div class="summary-label">Progress (${progress}%)</div>+ </div>+ <div class="summary-item">+ <div class="summary-value ${status === 'completed' && accuracy > 0 ? accuracyClass + ' accuracy-indicator' : ''}">${status === 'completed' && accuracy > 0 ? accuracy.toFixed(1) + '%' : 'N/A'}</div>+ <div class="summary-label">Accuracy</div>+ </div>+ <div class="summary-item">+ <div class="summary-value">${run.search_config?.model_name || 'Unknown'}</div>+ <div class="summary-label">Model</div>+ </div>+ <div class="summary-item">+ <div class="summary-value">${(run.search_config?.search_strategy || 'unknown').replace(/_/g, ' ')}</div>+ <div class="summary-label">Strategy</div>+ </div>+ <div class="summary-item">+ <div class="summary-value">${run.search_config?.search_tool || 'Unknown'}</div>+ <div class="summary-label">Search Engine</div>+ </div>+ <div class="summary-item">+ <div class="summary-value">${formatAvgSearchResults(run)}</div>+ <div class="summary-label">Avg Search Results</div>+ </div>+ <div class="summary-item">+ <div class="summary-value">${formatAvgSearchRequests(run)}</div>+ <div class="summary-label">Avg Search Requests</div>+ </div>+ <div class="summary-item">+ <div class="summary-value">${formatAvgProcessingTime(run)}</div>+ <div class="summary-label">Avg Time/Question</div>+ </div>+ <div class="summary-item">+ ${status === 'in_progress' ?+ `<button class="btn btn-outline btn-sm delete-btn" onclick="event.stopPropagation(); cancelAndDeleteBenchmarkRun(${run.id})" style="background: #3a1e1e !important; border-color: #f44336 !important; color: #f44336 !important;">+ <i class="fas fa-stop"></i> Cancel & Delete+ </button>` :+ `<button class="btn btn-outline btn-sm delete-btn" onclick="event.stopPropagation(); deleteBenchmarkRun(${run.id})">+ <i class="fas fa-trash"></i> Delete+ </button>`+ }+ <div class="summary-label">Actions</div>+ </div>+ </div>++ <div class="expand-indicator">+ <i class="fas fa-chevron-down"></i> Click to view detailed results and examples+ </div>++ <div class="results-section" id="results-${run.id}">+ <div class="run-config">+ <div class="config-item">+ <span class="config-label">Iterations:</span>+ <span class="config-value">${run.search_config?.iterations || 'N/A'}</span>+ </div>+ <div class="config-item">+ <span class="config-label">Questions/Iteration:</span>+ <span class="config-value">${run.search_config?.questions_per_iteration || 'N/A'}</span>+ </div>+ <div class="config-item">+ <span class="config-label">Temperature:</span>+ <span class="config-value">${run.search_config?.temperature || 'N/A'}</span>+ </div>+ <div class="config-item">+ <span class="config-label">Provider:</span>+ <span class="config-value">${run.search_config?.provider || 'N/A'}</span>+ </div>+ </div>++ <div id="examples-${run.id}">+ <div class="loading">Loading detailed results...</div>+ </div>+ </div>+ </div>+ `;+}++async function toggleRunDetails(runId) {+ const resultsSection = document.getElementById(`results-${runId}`);+ const runCard = resultsSection.closest('.run-card');++ if (resultsSection.classList.contains('visible')) {+ resultsSection.classList.remove('visible');+ runCard.classList.remove('expanded');+ return;+ }++ resultsSection.classList.add('visible');+ runCard.classList.add('expanded');++ // Load examples if not already loaded+ const examplesContainer = document.getElementById(`examples-${runId}`);+ if (examplesContainer.innerHTML.includes('Loading detailed results...')) {+ await loadExamples(runId);+ }+}++async function loadExamples(runId) {+ try {+ const response = await fetch(`/benchmark/api/results/${runId}?limit=50`);+ const data = await response.json();++ const examplesContainer = document.getElementById(`examples-${runId}`);++ if (data.success && data.results.length > 0) {+ // Calculate search result statistics+ const searchResultCounts = data.results.map(r => r.search_result_count || 0);+ const avgSearchResults = searchResultCounts.length > 0+ ? (searchResultCounts.reduce((sum, count) => sum + count, 0) / searchResultCounts.length).toFixed(1)+ : 'N/A';+ const minSearchResults = searchResultCounts.length > 0 ? Math.min(...searchResultCounts) : 'N/A';+ const maxSearchResults = searchResultCounts.length > 0 ? Math.max(...searchResultCounts) : 'N/A';++ // Create search results statistics section+ const statsHtml = `+ <div class="search-stats-section">+ <h4 class="section-title">+ <i class="fas fa-search"></i> Search Results Statistics+ </h4>+ <div class="search-stats-grid">+ <div class="stat-item">+ <div class="stat-value">${avgSearchResults}</div>+ <div class="stat-label">Avg Search Results</div>+ </div>+ <div class="stat-item">+ <div class="stat-value">${minSearchResults}</div>+ <div class="stat-label">Min Results</div>+ </div>+ <div class="stat-item">+ <div class="stat-value">${maxSearchResults}</div>+ <div class="stat-label">Max Results</div>+ </div>+ <div class="stat-item">+ <div class="stat-value">${data.results.length}</div>+ <div class="stat-label">Total Queries</div>+ </div>+ </div>+ </div>+ `;++ // Create examples grid+ const examplesHtml = data.results.map(result => createExampleCard(result)).join('');++ examplesContainer.innerHTML = `+ ${statsHtml}+ <div class="results-divider"></div>+ <div class="examples-section">+ <h4 class="section-title">+ <i class="fas fa-list"></i> Individual Query Results (${data.results.length} shown)+ </h4>+ <div class="examples-grid">${examplesHtml}</div>+ </div>+ `;+ } else {+ examplesContainer.innerHTML = '<div class="no-results">No detailed results available</div>';+ }+ } catch (error) {+ console.error('Error loading examples:', error);+ document.getElementById(`examples-${runId}`).innerHTML =+ '<div class="no-results">Error loading examples</div>';+ }+}++function formatAvgSearchResults(run) {+ if (!run.avg_search_results || run.avg_search_results <= 0) {+ return 'N/A';+ }++ return Math.round(run.avg_search_results).toString();+}++function formatAvgSearchRequests(run) {+ if (!run.total_search_requests || run.total_search_requests <= 0) {+ return 'N/A';+ }++ return Math.round(run.total_search_requests).toString();+}++function formatAvgProcessingTime(run) {+ // Calculate average processing time from completed examples+ if (!run.avg_processing_time && (!run.results || run.results.length === 0)) {+ return 'N/A';+ }++ // Use avg_processing_time if available, otherwise calculate from results+ let avgTime = run.avg_processing_time;+ if (!avgTime && run.results) {+ const timesWithValues = run.results+ .filter(r => r.processing_time && r.processing_time > 0)+ .map(r => r.processing_time);++ if (timesWithValues.length === 0) return 'N/A';+ avgTime = timesWithValues.reduce((sum, time) => sum + time, 0) / timesWithValues.length;+ }++ if (!avgTime || avgTime <= 0) return 'N/A';++ // Format time nicely+ if (avgTime < 60) {+ return `${avgTime.toFixed(1)}s`;+ } else if (avgTime < 3600) {+ const minutes = Math.floor(avgTime / 60);+ const seconds = Math.round(avgTime % 60);+ return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`;+ } else {+ const hours = Math.floor(avgTime / 3600);+ const minutes = Math.round((avgTime % 3600) / 60);+ return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;+ }+}++function createExampleCard(result) {+ const statusClass = result.is_correct ? 'correct' : 'incorrect';+ const statusIcon = result.is_correct ? '<i class="fas fa-check-circle"></i>' : '<i class="fas fa-times-circle"></i>';+ const statusText = result.is_correct ? 'Correct' : 'Incorrect';++ // Format processing time for individual result+ const processingTime = result.processing_time && result.processing_time > 0+ ? (result.processing_time < 60+ ? `${result.processing_time.toFixed(1)}s`+ : `${Math.floor(result.processing_time / 60)}m ${Math.round(result.processing_time % 60)}s`)+ : 'N/A';++ // Format search results count+ const searchResultCount = result.search_result_count || 0;++ return `+ <div class="example-card ${statusClass}">+ <div class="example-header">+ <span class="dataset-badge">${result.dataset_type}</span>+ <span class="example-status ${statusClass}">+ ${statusIcon} ${statusText}+ </span>+ <div class="example-metrics">+ <span class="processing-time">⏱️ ${processingTime}</span>+ <span class="search-results-count">🔍 ${searchResultCount} results</span>+ </div>+ </div>++ <div class="example-question">+ <strong>Question:</strong> ${result.question}+ </div>++ <div class="example-answers">+ <div class="answer-section model-answer-section">+ <div class="answer-label">Model Answer</div>+ <div class="answer-text">${result.model_answer || 'No answer provided'}</div>+ </div>+ <div class="answer-section correct-answer-section">+ <div class="answer-label">Expected Answer</div>+ <div class="answer-text">${result.correct_answer || 'No expected answer'}</div>+ </div>+ </div>+ </div>+ `;+}++function setupPagination() {+ const totalPages = Math.ceil(filteredRuns.length / itemsPerPage);+ const paginationDiv = document.getElementById('pagination');++ if (totalPages <= 1) {+ paginationDiv.style.display = 'none';+ return;+ }++ paginationDiv.style.display = 'flex';++ const prevBtn = document.getElementById('prev-page');+ const nextBtn = document.getElementById('next-page');+ const pageInfo = document.getElementById('page-info');++ prevBtn.disabled = currentPage === 1;+ nextBtn.disabled = currentPage === totalPages;+ pageInfo.textContent = `Page ${currentPage} of ${totalPages}`;++ prevBtn.onclick = () => {+ if (currentPage > 1) {+ currentPage--;+ displayResults();+ }+ };++ nextBtn.onclick = () => {+ if (currentPage < totalPages) {+ currentPage++;+ displayResults();+ }+ };+}++async function cancelAndDeleteBenchmarkRun(runId) {+ if (!confirm('Are you sure you want to cancel and delete this running benchmark? This action cannot be undone.')) {+ return;+ }++ try {+ // First cancel the benchmark+ const cancelResponse = await fetch(`/benchmark/api/cancel/${runId}`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ }+ });++ const cancelData = await cancelResponse.json();++ if (cancelData.success) {+ showAlert('Benchmark cancelled successfully. Deleting...', 'info');++ // Wait a moment for cancellation to process+ await new Promise(resolve => setTimeout(resolve, 1000));++ // Then delete it+ await deleteBenchmarkRun(runId);+ } else {+ showAlert('Error cancelling benchmark: ' + cancelData.error, 'error');+ }+ } catch (error) {+ console.error('Error cancelling benchmark:', error);+ showAlert('Error cancelling benchmark: ' + error.message, 'error');+ }+}++async function deleteBenchmarkRun(runId) {+ try {+ const response = await fetch(`/benchmark/api/delete/${runId}`, {+ method: 'DELETE',+ headers: {+ 'Content-Type': 'application/json',+ }+ });++ const data = await response.json();++ if (data.success) {+ // Show success message+ showAlert('Benchmark run deleted successfully!', 'success');++ // Remove the run from our local data+ benchmarkRuns = benchmarkRuns.filter(run => run.id !== runId);++ // Reapply filters and redisplay+ applyFilters();+ } else {+ showAlert('Error deleting benchmark run: ' + data.error, 'error');+ }+ } catch (error) {+ console.error('Error deleting benchmark run:', error);+ showAlert('Error deleting benchmark run: ' + error.message, 'error');+ }+}++function showAlert(message, type) {+ // Create alert element+ const alertDiv = document.createElement('div');+ alertDiv.className = `alert alert-${type}`;+ alertDiv.style.cssText = `+ position: fixed;+ top: 20px;+ right: 20px;+ z-index: 1000;+ max-width: 400px;+ padding: 15px;+ border-radius: 6px;+ color: white;+ font-weight: 500;+ box-shadow: 0 4px 12px rgba(0,0,0,0.3);+ `;++ // Set background color based on type+ const colors = {+ success: '#4caf50',+ error: '#f44336',+ warning: '#ff9800',+ info: '#2196f3'+ };+ alertDiv.style.backgroundColor = colors[type] || colors.info;++ alertDiv.innerHTML = `+ <div style="display: flex; align-items: center; justify-content: space-between;">+ <span>${message}</span>+ <button onclick="this.parentElement.parentElement.remove()" style="background: none; border: none; color: white; font-size: 1.2rem; cursor: pointer; margin-left: 10px;">×</button>+ </div>+ `;++ document.body.appendChild(alertDiv);++ // Auto-remove after 5 seconds+ setTimeout(() => {+ if (alertDiv.parentElement) {+ alertDiv.remove();+ }+ }, 5000);+}+</script>+{% endblock %}diff --git a/src/local_deep_research/web/templates/pages/benchmark_simple.html b/src/local_deep_research/web/templates/pages/benchmark_simple.htmlnew file mode 100644index 0000000000..a7e7a2ed72--- /dev/null+++ b/src/local_deep_research/web/templates/pages/benchmark_simple.html@@ -0,0 +1,453 @@+{% extends "base.html" %}++{% set active_page = 'benchmark' %}++{% block title %}Benchmark - Deep Research System{% endblock %}++{% block extra_head %}+<meta name="csrf-token" content="{{ csrf_token() }}">+<style>+.benchmark-card {+ max-width: 700px;+ margin: 0 auto;+}++.current-config {+ background: var(--bg-color);+ border: 1px solid var(--border-color);+ border-radius: 8px;+ padding: 20px;+ margin-bottom: 20px;+}++.config-item {+ display: flex;+ justify-content: space-between;+ padding: 8px 0;+ border-bottom: 1px solid var(--border-color);+}++.config-item:last-child {+ border-bottom: none;+}++.config-label {+ font-weight: 500;+ color: var(--text-muted);+}++.config-value {+ font-weight: 600;+ color: var(--primary-color);+}++.dataset-selection {+ margin: 20px 0;+}++.dataset-option {+ display: flex;+ align-items: center;+ padding: 15px;+ margin: 10px 0;+ background: var(--card-bg);+ border: 2px solid var(--border-color);+ border-radius: 8px;+ cursor: pointer;+ transition: all 0.2s;+}++.dataset-option:hover {+ border-color: var(--primary-color);+}++.dataset-option.selected {+ border-color: var(--primary-color);+ background: var(--primary-light);+}++.dataset-option input[type="number"] {+ width: 80px;+ margin-left: auto;+}++.start-button {+ width: 100%;+ padding: 15px;+ font-size: 1.1rem;+}++.progress-section {+ display: none;+ margin-top: 30px;+}++.progress-bar {+ width: 100%;+ height: 30px;+ background: var(--bg-color);+ border-radius: 15px;+ overflow: hidden;+ margin: 20px 0;+}++.progress-fill {+ height: 100%;+ background: linear-gradient(90deg, var(--primary-color), var(--accent-color));+ width: 0%;+ transition: width 0.3s ease;+}++.stats-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));+ gap: 15px;+ margin-top: 20px;+}++.stat-card {+ padding: 15px;+ background: var(--bg-color);+ border-radius: 8px;+ text-align: center;+}++.stat-value {+ font-size: 1.8rem;+ font-weight: bold;+ color: var(--primary-color);+}++.stat-label {+ font-size: 0.9rem;+ color: var(--text-muted);+ margin-top: 5px;+}+</style>+{% endblock %}++{% block content %}+<div class="page active" id="benchmark">+ <div class="page-header">+ <h1>Benchmark Your Configuration</h1>+ <p class="page-subtitle">Test your current settings against standard datasets</p>+ </div>++ <div id="benchmark-alert" class="settings-alert-container" style="display:none"></div>++ <div class="card benchmark-card">+ <div class="card-content">+ <!-- Current Configuration Display -->+ <div class="current-config">+ <h3>Current Configuration</h3>+ <div id="config-display">+ <div class="config-item">+ <span class="config-label">Loading...</span>+ <span class="config-value"></span>+ </div>+ </div>+ </div>++ <!-- Dataset Selection -->+ <div class="dataset-selection">+ <h3>Select Datasets to Test</h3>++ <div class="dataset-option selected" data-dataset="simpleqa">+ <div>+ <h4>SimpleQA</h4>+ <p>Fact-based questions with clear answers</p>+ </div>+ <input type="number" id="simpleqa_count" value="20" min="1" max="500">+ </div>++ <div class="dataset-option selected" data-dataset="browsecomp">+ <div>+ <h4>BrowseComp</h4>+ <p>Complex browsing and comparison tasks</p>+ </div>+ <input type="number" id="browsecomp_count" value="10" min="1" max="200">+ </div>+ </div>++ <!-- Start Button -->+ <button type="button" id="start-benchmark" class="btn btn-primary start-button">+ <i class="fas fa-play"></i> Start Benchmark+ </button>++ <!-- Progress Section -->+ <div class="progress-section" id="progress-section">+ <h3>Benchmark Progress</h3>++ <div class="progress-bar">+ <div class="progress-fill" id="progress-fill"></div>+ </div>++ <div class="stats-grid">+ <div class="stat-card">+ <div class="stat-value" id="stat-accuracy">--%</div>+ <div class="stat-label">Accuracy</div>+ </div>+ <div class="stat-card">+ <div class="stat-value" id="stat-completed">0</div>+ <div class="stat-label">Completed</div>+ </div>+ <div class="stat-card">+ <div class="stat-value" id="stat-rate">--</div>+ <div class="stat-label">Per Minute</div>+ </div>+ <div class="stat-card">+ <div class="stat-value" id="stat-remaining">--</div>+ <div class="stat-label">Time Left</div>+ </div>+ </div>++ <div style="margin-top: 20px; text-align: center;">+ <button type="button" id="cancel-benchmark" class="btn btn-secondary">+ <i class="fas fa-stop"></i> Cancel+ </button>+ </div>+ </div>+ </div>+ </div>+</div>++<script>+let currentBenchmarkId = null;+let progressInterval = null;++document.addEventListener('DOMContentLoaded', function() {+ loadCurrentConfig();+ setupEventListeners();+});++async function loadCurrentConfig() {+ try {+ // Get current settings from the database+ const response = await fetch('/research/settings/api');+ const data = await response.json();++ if (data.settings) {+ const config = {+ provider: data.settings['llm.provider']?.value || 'Not configured',+ model: data.settings['llm.model']?.value || 'Not configured',+ search_tool: data.settings['search.tool']?.value || 'searxng',+ iterations: data.settings['search.iterations']?.value || '8',+ questions_per_iteration: data.settings['search.questions_per_iteration']?.value || '5',+ search_strategy: data.settings['search.search_strategy']?.value || 'focused_iteration'+ };+ displayConfig(config);+ }+ } catch (error) {+ console.error('Error loading config:', error);+ // Use fallback display+ displayConfig({+ provider: 'Loading...',+ model: 'Loading...',+ search_tool: 'Loading...',+ iterations: '-'+ });+ }+}++function displayConfig(config) {+ const configDisplay = document.getElementById('config-display');+ configDisplay.innerHTML = `+ <div class="config-item">+ <span class="config-label">LLM Provider</span>+ <span class="config-value">${config.provider || 'Not set'}</span>+ </div>+ <div class="config-item">+ <span class="config-label">Model</span>+ <span class="config-value">${config.model || 'Not set'}</span>+ </div>+ <div class="config-item">+ <span class="config-label">Search Engine</span>+ <span class="config-value">${config.search_tool || 'searxng'}</span>+ </div>+ <div class="config-item">+ <span class="config-label">Search Iterations</span>+ <span class="config-value">${config.iterations || '8'}</span>+ </div>+ `;+}++function setupEventListeners() {+ // Dataset selection+ document.querySelectorAll('.dataset-option').forEach(option => {+ option.addEventListener('click', function(e) {+ if (!e.target.matches('input')) {+ this.classList.toggle('selected');+ }+ });+ });++ // Start benchmark+ document.getElementById('start-benchmark').addEventListener('click', startBenchmark);++ // Cancel benchmark+ document.getElementById('cancel-benchmark').addEventListener('click', cancelBenchmark);+}++async function startBenchmark() {+ // Get dataset configuration+ const datasets = {};+ document.querySelectorAll('.dataset-option.selected').forEach(option => {+ const dataset = option.getAttribute('data-dataset');+ const count = parseInt(option.querySelector('input').value) || 0;+ if (count > 0) {+ datasets[dataset] = { count: count };+ }+ });++ if (Object.keys(datasets).length === 0) {+ showAlert('Please select at least one dataset', 'error');+ return;+ }++ // Disable start button+ document.getElementById('start-benchmark').disabled = true;++ try {+ // Get CSRF token+ const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');++ const response = await fetch('/benchmark/api/start-simple', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': csrfToken+ },+ body: JSON.stringify({ datasets_config: datasets })+ });++ const data = await response.json();++ if (data.success) {+ currentBenchmarkId = data.benchmark_run_id;+ showProgress();+ startProgressTracking();+ showAlert('Benchmark started!', 'success');+ } else {+ showAlert('Error: ' + data.error, 'error');+ document.getElementById('start-benchmark').disabled = false;+ }+ } catch (error) {+ console.error('Error starting benchmark:', error);+ showAlert('Failed to start benchmark', 'error');+ document.getElementById('start-benchmark').disabled = false;+ }+}++function showProgress() {+ document.querySelector('.dataset-selection').style.display = 'none';+ document.getElementById('start-benchmark').style.display = 'none';+ document.getElementById('progress-section').style.display = 'block';+}++function hideProgress() {+ document.querySelector('.dataset-selection').style.display = 'block';+ document.getElementById('start-benchmark').style.display = 'block';+ document.getElementById('progress-section').style.display = 'none';+ document.getElementById('start-benchmark').disabled = false;+}++function startProgressTracking() {+ updateProgress(); // Initial update+ progressInterval = setInterval(updateProgress, 2000);+}++async function updateProgress() {+ if (!currentBenchmarkId) return;++ try {+ const response = await fetch(`/benchmark/api/status/${currentBenchmarkId}`);+ const data = await response.json();++ if (data.success) {+ const status = data.status;++ // Update progress bar+ const percentage = status.total_examples > 0 ?+ (status.completed_examples / status.total_examples * 100) : 0;+ document.getElementById('progress-fill').style.width = percentage + '%';++ // Update stats+ document.getElementById('stat-accuracy').textContent =+ status.overall_accuracy ? status.overall_accuracy.toFixed(1) + '%' : '--%';+ document.getElementById('stat-completed').textContent =+ `${status.completed_examples}/${status.total_examples}`;+ document.getElementById('stat-rate').textContent =+ status.processing_rate ? status.processing_rate.toFixed(1) : '--';++ // Estimate remaining time+ if (status.processing_rate > 0 && status.completed_examples < status.total_examples) {+ const remaining = status.total_examples - status.completed_examples;+ const minutes = Math.ceil(remaining / status.processing_rate);+ document.getElementById('stat-remaining').textContent = `${minutes}m`;+ } else {+ document.getElementById('stat-remaining').textContent = '--';+ }++ // Check if completed+ if (status.status === 'completed' || status.status === 'failed' || status.status === 'cancelled') {+ clearInterval(progressInterval);+ progressInterval = null;++ if (status.status === 'completed') {+ showAlert(`Benchmark completed! Final accuracy: ${status.overall_accuracy.toFixed(1)}%`, 'success');+ } else {+ showAlert(`Benchmark ${status.status}`, 'error');+ }++ setTimeout(() => {+ hideProgress();+ currentBenchmarkId = null;+ }, 3000);+ }+ }+ } catch (error) {+ console.error('Error updating progress:', error);+ }+}++async function cancelBenchmark() {+ if (!currentBenchmarkId) return;++ try {+ const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');+ const response = await fetch(`/benchmark/api/cancel/${currentBenchmarkId}`, {+ method: 'POST',+ headers: {+ 'X-CSRFToken': csrfToken+ }+ });++ const data = await response.json();+ if (data.success) {+ showAlert('Benchmark cancelled', 'info');+ }+ } catch (error) {+ console.error('Error cancelling benchmark:', error);+ }+}++function showAlert(message, type) {+ const alertContainer = document.getElementById('benchmark-alert');+ alertContainer.innerHTML = `+ <div class="settings-alert alert-${type}">+ <span>${message}</span>+ <button type="button" class="close-alert" onclick="this.parentElement.parentElement.style.display='none'">+ <i class="fas fa-times"></i>+ </button>+ </div>+ `;+ alertContainer.style.display = 'block';++ if (type === 'success') {+ setTimeout(() => {+ alertContainer.style.display = 'none';+ }, 5000);+ }+}+</script>+{% endblock %}diff --git a/src/local_deep_research/web/templates/pages/metrics.html b/src/local_deep_research/web/templates/pages/metrics.htmlindex f3ef3005a7..21a4421ab9 100644--- a/src/local_deep_research/web/templates/pages/metrics.html+++ b/src/local_deep_research/web/templates/pages/metrics.html@@ -682,6 +682,77 @@</div></div>+ <!-- Rate Limiting Analytics -->+ <div class="card" style="margin-top: 2rem;">+ <div class="card-header">+ <h2><i class="fas fa-clock"></i> Rate Limiting Analytics</h2>+ </div>+ <div class="card-content">+ <!-- Rate Limiting Overview Cards -->+ <div class="metrics-grid" style="margin-bottom: 2rem;">+ <div class="metric-card">+ <div class="metric-icon">+ <i class="fas fa-stopwatch"></i>+ </div>+ <div class="metric-label tooltip" data-tooltip="Percentage of retry attempts that succeeded after rate limiting">+ Rate Limit Success Rate+ <i class="fas fa-info-circle info-icon"></i>+ </div>+ <div class="metric-value" id="rate-limit-success-rate">0%</div>+ </div>++ <div class="metric-card">+ <div class="metric-icon">+ <i class="fas fa-exclamation-triangle"></i>+ </div>+ <div class="metric-label tooltip" data-tooltip="Number of times search engines were rate limited">+ Rate Limit Events+ <i class="fas fa-info-circle info-icon"></i>+ </div>+ <div class="metric-value" id="rate-limit-events">0</div>+ </div>++ <div class="metric-card">+ <div class="metric-icon">+ <i class="fas fa-hourglass-half"></i>+ </div>+ <div class="metric-label tooltip" data-tooltip="Average time waited before retrying after rate limits">+ Avg Wait Time+ <i class="fas fa-info-circle info-icon"></i>+ </div>+ <div class="metric-value" id="avg-wait-time">0s</div>+ </div>++ <div class="metric-card">+ <div class="metric-icon">+ <i class="fas fa-server"></i>+ </div>+ <div class="metric-label tooltip" data-tooltip="Number of search engines being tracked for rate limiting">+ Engines Tracked+ <i class="fas fa-info-circle info-icon"></i>+ </div>+ <div class="metric-value" id="engines-tracked">0</div>+ </div>+ </div>++ <!-- Engine Status Grid -->+ <div style="margin-bottom: 2rem;">+ <h3><i class="fas fa-tachometer-alt"></i> Search Engine Status</h3>+ <div id="engine-status-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 1rem; margin-top: 1rem;">+ <!-- Populated dynamically -->+ </div>+ </div>++ <!-- Rate Limiting Chart -->+ <div style="margin-top: 2rem;">+ <h3><i class="fas fa-chart-line"></i> Rate Limiting Activity Over Time</h3>+ <div class="chart-container" style="height: 300px;">+ <canvas id="rate-limiting-chart"></canvas>+ </div>+ </div>+ </div>+ </div>+<!-- Developer Insights --><div class="card" style="margin-top: 2rem;"><div class="card-header">@@ -817,7 +888,6 @@<script>// Metrics Dashboard JavaScript(function() {- console.log("=== METRICS SCRIPT STARTED ===");let metricsData = null;let tokenChart = null;@@ -871,40 +941,30 @@// Load metrics data for current time periodasync function loadMetrics(period = currentPeriod) {- console.log('=== STARTING LOADMETRICS ===');- console.log('Period:', period, 'Mode:', currentMode);try {// Show loading state- console.log('Setting loading state...');document.getElementById('loading').style.display = 'block';document.getElementById('metrics-content').style.display = 'none';document.getElementById('error').style.display = 'none';- console.log('Making basic API call...');const basicResponse = await fetch(`/metrics/api/metrics?period=${period}&mode=${currentMode}`);- console.log('Basic response status:', basicResponse.status);if (!basicResponse.ok) {throw new Error(`Basic API failed: ${basicResponse.status}`);}const basicData = await basicResponse.json();- console.log('Basic data received:', basicData);- console.log('Making enhanced API call...');const enhancedResponse = await fetch(`/metrics/api/metrics/enhanced?period=${period}&mode=${currentMode}`);- console.log('Enhanced response status:', enhancedResponse.status);if (!enhancedResponse.ok) {throw new Error(`Enhanced API failed: ${enhancedResponse.status}`);}const enhancedData = await enhancedResponse.json();- console.log('Enhanced data received:', enhancedData);if (basicData.status === 'success') {- console.log('Basic data success, setting metricsData');metricsData = basicData.metrics;// Check if we have any data at all@@ -913,15 +973,12 @@(metricsData.by_model && metricsData.by_model.length > 0) ||(metricsData.recent_researches && metricsData.recent_researches.length > 0);- console.log('Has data check:', hasData, 'tokens:', metricsData.total_tokens, 'researches:', metricsData.total_researches);if (hasData) {- console.log('Displaying metrics...');// We have data, display normallydisplayMetrics();if (enhancedData.status === 'success') {- console.log('Displaying enhanced metrics...');displayEnhancedMetrics(enhancedData.metrics);createTimeSeriesChart(enhancedData.metrics.time_series_data);createSearchActivityChart(enhancedData.metrics.search_time_series);@@ -932,40 +989,35 @@// Load cost analyticsloadCostAnalytics(period);+ // Load rate limiting analytics+ loadRateLimitingAnalytics(period);+document.getElementById('loading').style.display = 'none';document.getElementById('metrics-content').style.display = 'block';- console.log('Metrics display completed');- } else {- console.log('No data, showing empty state');+ } else {// No data yet, show empty state with helpful messagesshowEmptyState();// Still try to display enhanced metrics in case there's some enhanced dataif (enhancedData.status === 'success') {- console.log('Displaying enhanced metrics in empty state...');displayEnhancedMetrics(enhancedData.metrics);// Re-setup tooltips for any new contentsetTimeout(setupTooltipPositioning, 100);}}} else {- console.log('Basic data failed, showing error');showError();}} catch (error) {- console.error('Error loading metrics:', error);showError();}}// Display metrics on the pagefunction displayMetrics() {- console.log('displayMetrics called with metricsData:', metricsData);// Update summary cards- console.log('Updating total tokens:', metricsData.total_tokens);document.getElementById('total-tokens').textContent = formatNumber(metricsData.total_tokens);- console.log('Updating total researches:', metricsData.total_researches);document.getElementById('total-researches').textContent = formatNumber(metricsData.total_researches);// Update token breakdown details@@ -984,15 +1036,12 @@document.getElementById('success-rate').textContent = '0%';// Update user satisfaction rating- console.log('User satisfaction data:', metricsData.user_satisfaction);if (metricsData.user_satisfaction && metricsData.user_satisfaction.avg_rating !== null) {const rating = metricsData.user_satisfaction.avg_rating;const stars = '⭐'.repeat(Math.floor(rating));const displayText = `${rating} ${stars}`;- console.log('Setting user rating to:', displayText);document.getElementById('avg-user-rating').textContent = displayText;} else {- console.log('No user satisfaction data available');document.getElementById('avg-user-rating').textContent = '-';}@@ -1194,8 +1243,6 @@// Get strategy data from metricsData (added by our API)const strategyData = metricsData.strategy_analytics;- // Log strategy data for debugging- console.log('Strategy data received:', strategyData);if (strategyData && strategyData.strategy_usage && strategyData.strategy_usage.length > 0) {strategyData.strategy_usage.forEach(strategy => {@@ -1651,26 +1698,20 @@// Load cost analytics dataasync function loadCostAnalytics(period = currentPeriod) {try {- console.log('Loading cost analytics for period:', period);-const response = await fetch(`/metrics/api/cost-analytics?period=${period}`);if (!response.ok) {- console.warn('Cost analytics API failed:', response.status);displayCostData(null);return;}const data = await response.json();- console.log('Cost analytics data received:', data);if (data.status === 'success') {displayCostData(data);} else {- console.warn('Cost analytics returned error:', data.message);displayCostData(null);}} catch (error) {- console.error('Error loading cost analytics:', error);displayCostData(null);}}@@ -1700,7 +1741,133 @@document.getElementById('total-output-cost').textContent = formatCurrency(overview.completion_cost);document.getElementById('total-cost-breakdown').textContent = formatCurrency(overview.total_cost);- console.log('Cost data displayed successfully');+ }++ // Load rate limiting analytics+ async function loadRateLimitingAnalytics(period = currentPeriod) {+ try {+ const response = await fetch(`/metrics/api/rate-limiting?period=${period}`);+ if (!response.ok) {+ displayRateLimitingData(null);+ return;+ }++ const data = await response.json();++ if (data.status === 'success') {+ displayRateLimitingData(data.data);+ } else {+ displayRateLimitingData(null);+ }+ } catch (error) {+ displayRateLimitingData(null);+ }+ }++ // Display rate limiting data in the dashboard+ function displayRateLimitingData(rateLimitData) {+ if (!rateLimitData || !rateLimitData.rate_limiting_analytics) {+ // No rate limiting data available, show zeros+ document.getElementById('rate-limit-success-rate').textContent = '0%';+ document.getElementById('rate-limit-events').textContent = '0';+ document.getElementById('avg-wait-time').textContent = '0s';+ document.getElementById('engines-tracked').textContent = '0';++ // Clear engine status grid+ const statusGrid = document.getElementById('engine-status-grid');+ statusGrid.innerHTML = '<div style="grid-column: 1 / -1; text-align: center; padding: 2rem; color: var(--text-secondary);"><i class="fas fa-clock fa-2x" style="margin-bottom: 1rem;"></i><p>No rate limiting data yet</p><p style="font-size: 0.875rem;">Rate limiting will appear after search engines are used</p></div>';+ return;+ }++ const analytics = rateLimitData.rate_limiting_analytics;++ // Update overview cards+ document.getElementById('rate-limit-success-rate').textContent = `${analytics.success_rate}%`;+ document.getElementById('rate-limit-events').textContent = formatNumber(analytics.rate_limit_events);+ document.getElementById('avg-wait-time').textContent = `${analytics.avg_wait_time}s`;+ document.getElementById('engines-tracked').textContent = formatNumber(analytics.total_engines_tracked);++ // Update engine status grid+ const statusGrid = document.getElementById('engine-status-grid');+ statusGrid.innerHTML = '';++ if (Object.keys(analytics.engine_stats).length === 0) {+ statusGrid.innerHTML = '<div style="grid-column: 1 / -1; text-align: center; padding: 2rem; color: var(--text-secondary);"><i class="fas fa-clock fa-2x" style="margin-bottom: 1rem;"></i><p>No engine data yet</p><p style="font-size: 0.875rem;">Search engine metrics will appear after rate limiting occurs</p></div>';+ } else {+ Object.entries(analytics.engine_stats).forEach(([engineType, stats]) => {+ const statusCard = document.createElement('div');+ statusCard.className = 'metric-card';+ statusCard.style.borderLeft = `4px solid ${getStatusColor(stats.status)}`;++ statusCard.innerHTML = `+ <div class="metric-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">+ <h4 style="margin: 0; color: var(--text-primary);">${engineType.replace('SearchEngine', '')}</h4>+ <span class="status-badge" style="+ background: ${getStatusColor(stats.status)};+ color: white;+ padding: 2px 8px;+ border-radius: 12px;+ font-size: 0.75rem;+ font-weight: 600;+ text-transform: uppercase;+ ">${stats.status}</span>+ </div>+ <div class="engine-stats-grid" style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem; font-size: 0.875rem;">+ <div>+ <div style="color: var(--text-secondary);">Base Wait:</div>+ <div style="font-weight: 600;">${stats.base_wait_seconds}s</div>+ </div>+ <div>+ <div style="color: var(--text-secondary);">Success Rate:</div>+ <div style="font-weight: 600; color: ${stats.success_rate > 80 ? '#4CAF50' : stats.success_rate > 50 ? '#FF9800' : '#F44336'};">${stats.success_rate}%</div>+ </div>+ <div>+ <div style="color: var(--text-secondary);">Total Attempts:</div>+ <div style="font-weight: 600;">${formatNumber(stats.total_attempts)}</div>+ </div>+ <div>+ <div style="color: var(--text-secondary);">Last Updated:</div>+ <div style="font-weight: 600;">${formatTime(stats.last_updated)}</div>+ </div>+ </div>+ <div style="margin-top: 0.75rem; font-size: 0.75rem; color: var(--text-secondary);">+ Range: ${stats.min_wait_seconds}s - ${stats.max_wait_seconds}s+ </div>+ `;++ statusGrid.appendChild(statusCard);+ });+ }++ }++ // Get status color based on engine health+ function getStatusColor(status) {+ switch (status) {+ case 'healthy': return '#4CAF50';+ case 'degraded': return '#FF9800';+ case 'poor': return '#F44336';+ default: return '#9E9E9E';+ }+ }++ // Format time for display+ function formatTime(timeString) {+ try {+ const date = new Date(timeString);+ const now = new Date();+ const diffHours = (now - date) / (1000 * 60 * 60);++ if (diffHours < 1) {+ return 'Just now';+ } else if (diffHours < 24) {+ return `${Math.floor(diffHours)}h ago`;+ } else {+ return `${Math.floor(diffHours / 24)}d ago`;+ }+ } catch {+ return timeString;+ }}// Show error message@@ -1736,6 +1903,12 @@document.getElementById('total-output-cost').textContent = '-';document.getElementById('total-cost-breakdown').textContent = '-';+ // Reset rate limiting metrics+ document.getElementById('rate-limit-success-rate').textContent = '0%';+ document.getElementById('rate-limit-events').textContent = '0';+ document.getElementById('avg-wait-time').textContent = '0s';+ document.getElementById('engines-tracked').textContent = '0';+// Show helpful message in chartsshowEmptyChartsAndTables();}diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.pyindex 7dd798f9ac..bae2d20a5a 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py@@ -9,6 +9,7 @@ from ...advanced_search_system.filters.journal_reputation_filter import ()from ...config import search_configfrom ..search_engine_base import BaseSearchEngine+from ..rate_limiting import RateLimitErrorclass ArXivSearchEngine(BaseSearchEngine):@@ -155,8 +156,20 @@ class ArXivSearchEngine(BaseSearchEngine):return previews- except Exception:+ except Exception as e:+ error_msg = str(e)logger.exception("Error getting arXiv previews")++ # Check for rate limiting patterns+ if (+ "429" in error_msg+ or "too many requests" in error_msg.lower()+ or "rate limit" in error_msg.lower()+ or "service unavailable" in error_msg.lower()+ or "503" in error_msg+ ):+ raise RateLimitError(f"arXiv rate limit hit: {error_msg}")+return []def _get_full_content(diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_brave.py b/src/local_deep_research/web_search_engines/engines/search_engine_brave.pyindex 829347ea72..745c183885 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_brave.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_brave.py@@ -7,6 +7,7 @@ from langchain_core.language_models import BaseLLMfrom ...config import search_configfrom ..search_engine_base import BaseSearchEngine+from ..rate_limiting import RateLimitErrorlogger = logging.getLogger(__name__)@@ -174,7 +175,20 @@ class BraveSearchEngine(BaseSearchEngine):return previewsexcept Exception as e:- logger.error(f"Error getting Brave Search results: {e}")+ error_msg = str(e)+ logger.error(f"Error getting Brave Search results: {error_msg}")++ # Check for rate limit patterns+ if (+ "429" in error_msg+ or "too many requests" in error_msg.lower()+ or "rate limit" in error_msg.lower()+ or "quota" in error_msg.lower()+ ):+ raise RateLimitError(+ f"Brave Search rate limit hit: {error_msg}"+ )+return []def _get_full_content(diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py b/src/local_deep_research/web_search_engines/engines/search_engine_ddg.pyindex 01508a2df0..69d34d9227 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py@@ -5,6 +5,7 @@ from langchain_community.utilities import DuckDuckGoSearchAPIWrapperfrom langchain_core.language_models import BaseLLMfrom ..search_engine_base import BaseSearchEngine+from ..rate_limiting import RateLimitErrorfrom .full_search import FullSearchResults # Import the FullSearchResults classlogger = logging.getLogger(__name__)@@ -114,7 +115,25 @@ class DuckDuckGoSearchEngine(BaseSearchEngine):return previewsexcept Exception as e:- logger.error(f"Error getting DuckDuckGo previews: {e}")+ error_msg = str(e)+ logger.error(f"Error getting DuckDuckGo previews: {error_msg}")++ # Check for known rate limit patterns+ if "202 Ratelimit" in error_msg or "ratelimit" in error_msg.lower():+ raise RateLimitError(f"DuckDuckGo rate limit hit: {error_msg}")+ elif "403" in error_msg or "forbidden" in error_msg.lower():+ raise RateLimitError(+ f"DuckDuckGo access forbidden (possible rate limit): {error_msg}"+ )+ elif (+ "timeout" in error_msg.lower()+ or "timed out" in error_msg.lower()+ ):+ # Timeouts can sometimes indicate rate limiting+ raise RateLimitError(+ f"DuckDuckGo timeout (possible rate limit): {error_msg}"+ )+return []def _get_full_content(diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py b/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.pyindex ea95e39248..d05b209dfb 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py@@ -8,6 +8,7 @@ from langchain_core.language_models import BaseLLMfrom requests.exceptions import RequestExceptionfrom ..search_engine_base import BaseSearchEngine+from ..rate_limiting import RateLimitError# Set up logginglogging.basicConfig(level=logging.INFO)@@ -220,20 +221,43 @@ class GooglePSESearchEngine(BaseSearchEngine):return response.json()except RequestException as e:+ error_msg = str(e)logger.warning("Request error on attempt %s / %s: %s",attempt + 1,self.max_retries,- str(e),+ error_msg,)++ # Check for rate limiting patterns+ if (+ "quota" in error_msg.lower()+ or "quotaExceeded" in error_msg+ or "dailyLimitExceeded" in error_msg+ or "rateLimitExceeded" in error_msg+ or "429" in error_msg+ or "403" in error_msg+ ):+ raise RateLimitError(+ f"Google PSE rate limit/quota exceeded: {error_msg}"+ )+last_exception = eexcept Exception as e:+ error_msg = str(e)logger.warning("Error on attempt %s / %s: %s",attempt + 1,self.max_retries,- str(e),+ error_msg,)++ # Check for rate limiting patterns in general errors+ if "quota" in error_msg.lower() or "limit" in error_msg.lower():+ raise RateLimitError(+ f"Google PSE error (possible rate limit): {error_msg}"+ )+last_exception = eattempt += 1diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.pyindex 24ec313b07..ad9c2b8175 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py@@ -9,6 +9,7 @@ from langchain_core.language_models import BaseLLMfrom ...config import search_configfrom ..search_engine_base import BaseSearchEngine+from ..rate_limiting import RateLimitError# Setup logginglogging.basicConfig(level=logging.INFO)@@ -639,7 +640,20 @@ The default assumption should be that medical and scientific queries want RECENTreturn summariesexcept Exception as e:- logger.error(f"Error getting article summaries: {e}")+ error_msg = str(e)+ logger.error(f"Error getting article summaries: {error_msg}")++ # Check for rate limiting patterns+ if (+ "429" in error_msg+ or "too many requests" in error_msg.lower()+ or "rate limit" in error_msg.lower()+ or "service unavailable" in error_msg.lower()+ or "503" in error_msg+ or "403" in error_msg+ ):+ raise RateLimitError(f"PubMed rate limit hit: {error_msg}")+return []def _get_article_abstracts(self, id_list: List[str]) -> Dict[str, str]:diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py b/src/local_deep_research/web_search_engines/engines/search_engine_tavily.pynew file mode 100644index 0000000000..8075198498--- /dev/null+++ b/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py@@ -0,0 +1,307 @@+import logging+import os+from typing import Any, Dict, List, Optional++import requests+from langchain_core.language_models import BaseLLM++from ...config import search_config+from ..search_engine_base import BaseSearchEngine+from ..rate_limiting import RateLimitError++logger = logging.getLogger(__name__)+++class TavilySearchEngine(BaseSearchEngine):+ """Tavily search engine implementation with two-phase approach"""++ def __init__(+ self,+ max_results: int = 10,+ region: str = "US",+ time_period: str = "y",+ safe_search: bool = True,+ search_language: str = "English",+ api_key: Optional[str] = None,+ llm: Optional[BaseLLM] = None,+ include_full_content: bool = True,+ max_filtered_results: Optional[int] = None,+ search_depth: str = "basic",+ include_domains: Optional[List[str]] = None,+ exclude_domains: Optional[List[str]] = None,+ **kwargs,+ ):+ """+ Initialize the Tavily search engine.++ Args:+ max_results: Maximum number of search results+ region: Region code for search results (not used by Tavily currently)+ time_period: Time period for search results (not used by Tavily currently)+ safe_search: Whether to enable safe search (not used by Tavily currently)+ search_language: Language for search results (not used by Tavily currently)+ api_key: Tavily API key (can also be set in TAVILY_API_KEY env)+ llm: Language model for relevance filtering+ include_full_content: Whether to include full webpage content in results+ max_filtered_results: Maximum number of results to keep after filtering+ search_depth: "basic" or "advanced" - controls search quality vs speed+ include_domains: List of domains to include in search+ exclude_domains: List of domains to exclude from search+ **kwargs: Additional parameters (ignored but accepted for compatibility)+ """+ # Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results+ super().__init__(+ llm=llm,+ max_filtered_results=max_filtered_results,+ max_results=max_results,+ )+ self.include_full_content = include_full_content+ self.search_depth = search_depth+ self.include_domains = include_domains or []+ self.exclude_domains = exclude_domains or []++ # Get API key - check params, database, or env vars+ from ...utilities.db_utils import get_db_setting++ tavily_api_key = api_key+ if not tavily_api_key:+ tavily_api_key = get_db_setting("search.engine.web.tavily.api_key")++ if not tavily_api_key:+ tavily_api_key = os.environ.get("TAVILY_API_KEY")++ if not tavily_api_key:+ raise ValueError(+ "Tavily API key not found. Please provide api_key parameter, "+ "set it in the UI settings, or set TAVILY_API_KEY environment variable."+ )++ self.api_key = tavily_api_key+ self.base_url = "https://api.tavily.com"++ # If full content is requested, initialize FullSearchResults+ if include_full_content:+ # Import FullSearchResults only if needed+ try:+ from .full_search import FullSearchResults++ # Create a simple wrapper for Tavily API calls+ class TavilyWrapper:+ def __init__(self, parent):+ self.parent = parent++ def run(self, query):+ return self.parent._get_previews(query)++ self.full_search = FullSearchResults(+ llm=llm,+ web_search=TavilyWrapper(self),+ language=search_language,+ max_results=max_results,+ region=region,+ time=time_period,+ safesearch="moderate" if safe_search else "off",+ )+ except ImportError:+ logger.warning(+ "Warning: FullSearchResults not available. Full content retrieval disabled."+ )+ self.include_full_content = False++ def _get_previews(self, query: str) -> List[Dict[str, Any]]:+ """+ Get preview information from Tavily Search.++ Args:+ query: The search query++ Returns:+ List of preview dictionaries+ """+ logger.info("Getting search results from Tavily")++ try:+ # Prepare the request payload+ payload = {+ "api_key": self.api_key,+ "query": query[:400], # Limit query length+ "search_depth": self.search_depth,+ "max_results": min(+ 20, self.max_results+ ), # Tavily has a max limit+ "include_answer": False, # We don't need the AI answer+ "include_images": False, # We don't need images+ "include_raw_content": self.include_full_content, # Get content if requested+ }++ # Add domain filters if specified+ if self.include_domains:+ payload["include_domains"] = self.include_domains+ if self.exclude_domains:+ payload["exclude_domains"] = self.exclude_domains++ # Make the API request+ response = requests.post(+ f"{self.base_url}/search",+ json=payload,+ headers={"Content-Type": "application/json"},+ timeout=30,+ )++ # Check for errors+ if response.status_code == 429:+ raise RateLimitError(+ f"Tavily rate limit hit: {response.status_code} - {response.text}"+ )++ response.raise_for_status()++ # Parse the response+ data = response.json()+ results = data.get("results", [])++ # Format results as previews+ previews = []+ for i, result in enumerate(results):+ preview = {+ "id": result.get("url", str(i)), # Use URL as ID+ "title": result.get("title", ""),+ "link": result.get("url", ""),+ "snippet": result.get(+ "content", ""+ ), # Tavily calls it "content"+ "displayed_link": result.get("url", ""),+ "position": i,+ }++ # Store full Tavily result for later+ preview["_full_result"] = result++ previews.append(preview)++ # Store the previews for potential full content retrieval+ self._search_results = previews++ return previews++ except RateLimitError:+ raise # Re-raise rate limit errors+ except requests.exceptions.RequestException as e:+ error_msg = str(e)+ logger.error(f"Error getting Tavily results: {error_msg}")++ # Check for rate limit patterns in error message+ if any(+ pattern in error_msg.lower()+ for pattern in [+ "429",+ "rate limit",+ "quota",+ "too many requests",+ ]+ ):+ raise RateLimitError(f"Tavily rate limit hit: {error_msg}")++ return []+ except Exception as e:+ logger.error(f"Unexpected error getting Tavily results: {e}")+ return []++ def _get_full_content(+ self, relevant_items: List[Dict[str, Any]]+ ) -> List[Dict[str, Any]]:+ """+ Get full content for the relevant search results.+ If include_full_content is True and raw content was retrieved,+ includes it in the results.++ Args:+ relevant_items: List of relevant preview dictionaries++ Returns:+ List of result dictionaries with full content if available+ """+ # Check if we should get full content+ if (+ hasattr(search_config, "SEARCH_SNIPPETS_ONLY")+ and search_config.SEARCH_SNIPPETS_ONLY+ ):+ logger.info("Snippet-only mode, skipping full content retrieval")++ # Return the relevant items with their full Tavily information+ results = []+ for item in relevant_items:+ # Use the full result if available, otherwise use the preview+ if "_full_result" in item:+ result = item["_full_result"]+ # Remove temporary field+ if "_full_result" in result:+ del result["_full_result"]+ else:+ result = item++ results.append(result)++ return results++ # If full content retrieval is enabled+ if self.include_full_content and hasattr(self, "full_search"):+ logger.info("Retrieving full webpage content")++ try:+ # Use FullSearchResults to get full content+ results_with_content = self.full_search._get_full_content(+ relevant_items+ )++ return results_with_content++ except Exception as e:+ logger.error(f"Error retrieving full content: {e}")+ # Fall back to returning the items without full content++ # Return items with their full Tavily information+ results = []+ for item in relevant_items:+ # Use the full result if available, otherwise use the preview+ if "_full_result" in item:+ result = item["_full_result"].copy()++ # If Tavily provided raw_content, include it+ if "raw_content" in result and self.include_full_content:+ result["content"] = result.get(+ "raw_content", result.get("content", "")+ )++ # Remove temporary field+ if "_full_result" in result:+ del result["_full_result"]+ else:+ result = item.copy()+ if "_full_result" in result:+ del result["_full_result"]++ results.append(result)++ return results++ def run(self, query: str) -> List[Dict[str, Any]]:+ """+ Execute a search using Tavily with the two-phase approach.++ Args:+ query: The search query++ Returns:+ List of search results+ """+ logger.info("---Execute a search using Tavily---")++ # Use the implementation from the parent class which handles all phases+ results = super().run(query)++ # Clean up+ if hasattr(self, "_search_results"):+ del self._search_results++ return resultsdiff --git a/src/local_deep_research/web_search_engines/rate_limiting/__init__.py b/src/local_deep_research/web_search_engines/rate_limiting/__init__.pynew file mode 100644index 0000000000..0e6c8b76ce--- /dev/null+++ b/src/local_deep_research/web_search_engines/rate_limiting/__init__.py@@ -0,0 +1,14 @@+"""+Adaptive rate limiting module for search engines.+"""++from .exceptions import RateLimitError, AdaptiveRetryError, RateLimitConfigError+from .tracker import AdaptiveRateLimitTracker, get_tracker++__all__ = [+ "RateLimitError",+ "AdaptiveRetryError",+ "RateLimitConfigError",+ "AdaptiveRateLimitTracker",+ "get_tracker",+]diff --git a/src/local_deep_research/web_search_engines/rate_limiting/__main__.py b/src/local_deep_research/web_search_engines/rate_limiting/__main__.pynew file mode 100644index 0000000000..7555e358be--- /dev/null+++ b/src/local_deep_research/web_search_engines/rate_limiting/__main__.py@@ -0,0 +1,9 @@+"""+Entry point for rate limiting CLI module.+Allows running: python -m local_deep_research.web_search_engines.rate_limiting+"""++from .cli import main++if __name__ == "__main__":+ main()diff --git a/src/local_deep_research/web_search_engines/rate_limiting/cli.py b/src/local_deep_research/web_search_engines/rate_limiting/cli.pynew file mode 100644index 0000000000..109c4c0d0c--- /dev/null+++ b/src/local_deep_research/web_search_engines/rate_limiting/cli.py@@ -0,0 +1,209 @@+"""+Command-line interface for rate limiting monitoring and management.+"""++import argparse+import sys+from datetime import datetime++from .tracker import get_tracker+++def format_stats_table(stats: list) -> str:+ """Format rate limit statistics as a table."""+ if not stats:+ return "No rate limit data available."++ # Header+ lines = []+ lines.append("Rate Limit Statistics:")+ lines.append("-" * 80)+ lines.append(+ f"{'Engine':<20} {'Base Wait':<12} {'Range':<20} {'Success':<10} {'Attempts':<10} {'Updated':<15}"+ )+ lines.append("-" * 80)++ # Data rows+ for row in stats:+ (+ engine_type,+ base_wait,+ min_wait,+ max_wait,+ last_updated,+ attempts,+ success_rate,+ ) = row++ # Format time+ updated_time = datetime.fromtimestamp(last_updated).strftime(+ "%m-%d %H:%M"+ )++ # Format range+ range_str = f"{min_wait:.1f}s - {max_wait:.1f}s"++ lines.append(+ f"{engine_type:<20} {base_wait:<12.2f} {range_str:<20} "+ f"{success_rate:<10.1%} {attempts:<10} {updated_time:<15}"+ )++ return "\n".join(lines)+++def cmd_status(args):+ """Show current rate limit status."""+ tracker = get_tracker()++ if args.engine:+ stats = tracker.get_stats(args.engine)+ if not stats:+ print(f"No rate limit data found for engine: {args.engine}")+ return+ else:+ stats = tracker.get_stats()++ print(format_stats_table(stats))+++def cmd_reset(args):+ """Reset rate limit data for an engine."""+ tracker = get_tracker()++ if args.engine:+ tracker.reset_engine(args.engine)+ print(f"Reset rate limit data for {args.engine}")+ else:+ print("Error: --engine parameter is required for reset command")+ sys.exit(1)+++def cmd_cleanup(args):+ """Clean up old rate limit data."""+ tracker = get_tracker()+ tracker.cleanup_old_data(days=args.days)+ print(f"Cleaned up rate limit data older than {args.days} days")+++def cmd_export(args):+ """Export rate limit data."""+ tracker = get_tracker()++ # Get all stats+ stats = tracker.get_stats()++ if args.format == "csv":+ print(+ "engine_type,base_wait_seconds,min_wait_seconds,max_wait_seconds,last_updated,total_attempts,success_rate"+ )+ for row in stats:+ print(",".join(map(str, row)))+ elif args.format == "json":+ import json++ data = []+ for row in stats:+ (+ engine_type,+ base_wait,+ min_wait,+ max_wait,+ last_updated,+ attempts,+ success_rate,+ ) = row+ data.append(+ {+ "engine_type": engine_type,+ "base_wait_seconds": base_wait,+ "min_wait_seconds": min_wait,+ "max_wait_seconds": max_wait,+ "last_updated": last_updated,+ "total_attempts": attempts,+ "success_rate": success_rate,+ }+ )+ print(json.dumps(data, indent=2))+ else:+ print(format_stats_table(stats))+++def main():+ """Main CLI entry point."""+ parser = argparse.ArgumentParser(+ description="Rate limiting monitoring and management",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""+Examples:+ # Show all engine statistics+ python -m local_deep_research.web_search_engines.rate_limiting.cli status++ # Show specific engine statistics+ python -m local_deep_research.web_search_engines.rate_limiting.cli status --engine DuckDuckGoSearchEngine++ # Reset rate limit data for an engine+ python -m local_deep_research.web_search_engines.rate_limiting.cli reset --engine SearXNGSearchEngine++ # Export data as CSV+ python -m local_deep_research.web_search_engines.rate_limiting.cli export --format csv++ # Clean up old data+ python -m local_deep_research.web_search_engines.rate_limiting.cli cleanup --days 30+""",+ )++ subparsers = parser.add_subparsers(+ dest="command", help="Available commands"+ )++ # Status command+ status_parser = subparsers.add_parser(+ "status", help="Show rate limit statistics"+ )+ status_parser.add_argument(+ "--engine", help="Show stats for specific engine"+ )+ status_parser.set_defaults(func=cmd_status)++ # Reset command+ reset_parser = subparsers.add_parser("reset", help="Reset rate limit data")+ reset_parser.add_argument("--engine", required=True, help="Engine to reset")+ reset_parser.set_defaults(func=cmd_reset)++ # Export command+ export_parser = subparsers.add_parser(+ "export", help="Export rate limit data"+ )+ export_parser.add_argument(+ "--format",+ choices=["table", "csv", "json"],+ default="table",+ help="Output format",+ )+ export_parser.set_defaults(func=cmd_export)++ # Cleanup command+ cleanup_parser = subparsers.add_parser("cleanup", help="Clean up old data")+ cleanup_parser.add_argument(+ "--days",+ type=int,+ default=30,+ help="Remove data older than this many days",+ )+ cleanup_parser.set_defaults(func=cmd_cleanup)++ args = parser.parse_args()++ if not args.command:+ parser.print_help()+ sys.exit(1)++ try:+ args.func(args)+ except Exception as e:+ print(f"Error: {e}")+ sys.exit(1)+++if __name__ == "__main__":+ main()diff --git a/src/local_deep_research/web_search_engines/rate_limiting/exceptions.py b/src/local_deep_research/web_search_engines/rate_limiting/exceptions.pynew file mode 100644index 0000000000..f65069cd3e--- /dev/null+++ b/src/local_deep_research/web_search_engines/rate_limiting/exceptions.py@@ -0,0 +1,21 @@+"""+Rate limiting specific exceptions for search engines.+"""+++class RateLimitError(Exception):+ """Raised when a search engine hits rate limits."""++ pass+++class AdaptiveRetryError(Exception):+ """Raised when adaptive retry fails after all attempts."""++ pass+++class RateLimitConfigError(Exception):+ """Raised when there's an issue with rate limit configuration."""++ passdiff --git a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py b/src/local_deep_research/web_search_engines/rate_limiting/tracker.pynew file mode 100644index 0000000000..593d8e4cd5--- /dev/null+++ b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py@@ -0,0 +1,497 @@+"""+Adaptive rate limit tracker that learns optimal retry wait times for each search engine.+"""++import time+import random+import logging+from collections import deque+from typing import Dict, Optional, Tuple, List+++from ...utilities.db_utils import get_db_session+from ...web.database.models import RateLimitAttempt, RateLimitEstimate++logger = logging.getLogger(__name__)+++class AdaptiveRateLimitTracker:+ """+ Tracks and learns optimal retry wait times for each search engine.+ Persists learned patterns to the main application database using SQLAlchemy.+ """++ def __init__(self):+ # Load configuration from database settings+ from ...utilities.db_utils import get_db_setting++ self.memory_window = int(+ get_db_setting("rate_limiting.memory_window", 100)+ )+ self.exploration_rate = float(+ get_db_setting("rate_limiting.exploration_rate", 0.1)+ )+ self.learning_rate = float(+ get_db_setting("rate_limiting.learning_rate", 0.3)+ )+ self.decay_per_day = 0.95 # Keep this internal for now+ self.enabled = bool(get_db_setting("rate_limiting.enabled", True))++ # Apply rate limiting profile+ self._apply_profile(get_db_setting("rate_limiting.profile", "balanced"))++ # In-memory cache for fast access+ self.recent_attempts: Dict[str, deque] = {}+ self.current_estimates: Dict[str, Dict[str, float]] = {}++ # Load estimates from database+ self._load_estimates()++ logger.info(+ f"AdaptiveRateLimitTracker initialized: enabled={self.enabled}, profile={get_db_setting('rate_limiting.profile', 'balanced')}"+ )++ def _apply_profile(self, profile: str) -> None:+ """Apply rate limiting profile settings."""+ if profile == "conservative":+ # More conservative: lower exploration, slower learning+ self.exploration_rate = min(+ self.exploration_rate * 0.5, 0.05+ ) # 5% max exploration+ self.learning_rate = min(+ self.learning_rate * 0.7, 0.2+ ) # Slower learning+ logger.info("Applied conservative rate limiting profile")+ elif profile == "aggressive":+ # More aggressive: higher exploration, faster learning+ self.exploration_rate = min(+ self.exploration_rate * 1.5, 0.2+ ) # Up to 20% exploration+ self.learning_rate = min(+ self.learning_rate * 1.3, 0.5+ ) # Faster learning+ logger.info("Applied aggressive rate limiting profile")+ else: # balanced+ # Use settings as-is+ logger.info("Applied balanced rate limiting profile")++ def _load_estimates(self) -> None:+ """Load estimates from database into memory."""+ try:+ session = get_db_session()+ estimates = session.query(RateLimitEstimate).all()++ for estimate in estimates:+ # Apply decay for old estimates+ age_hours = (time.time() - estimate.last_updated) / 3600+ decay = self.decay_per_day ** (age_hours / 24)++ self.current_estimates[estimate.engine_type] = {+ "base": estimate.base_wait_seconds,+ "min": estimate.min_wait_seconds,+ "max": estimate.max_wait_seconds,+ "confidence": decay,+ }++ logger.debug(+ f"Loaded estimate for {estimate.engine_type}: base={estimate.base_wait_seconds:.2f}s, confidence={decay:.2f}"+ )++ except Exception as e:+ logger.warning(f"Could not load rate limit estimates: {e}")+ # Continue with empty estimates - they'll be learned++ def get_wait_time(self, engine_type: str) -> float:+ """+ Get adaptive wait time for a search engine.+ Includes exploration to discover better rates.++ Args:+ engine_type: Name of the search engine++ Returns:+ Wait time in seconds+ """+ # If rate limiting is disabled, return minimal wait time+ if not self.enabled:+ return 0.1++ if engine_type not in self.current_estimates:+ # First time seeing this engine - start optimistic and learn from real responses+ # Use engine-specific optimistic defaults only for what we know for sure+ optimistic_defaults = {+ "LocalSearchEngine": 0.0, # No network calls+ "SearXNGSearchEngine": 0.1, # Self-hosted default engine+ }++ wait_time = optimistic_defaults.get(+ engine_type, 0.5+ ) # Default optimistic for others+ logger.info(+ f"No rate limit data for {engine_type}, starting optimistic with {wait_time}s"+ )+ return wait_time++ estimate = self.current_estimates[engine_type]+ base_wait = estimate["base"]++ # Exploration vs exploitation+ if random.random() < self.exploration_rate:+ # Explore: try a faster rate to see if API limits have relaxed+ wait_time = base_wait * random.uniform(0.5, 0.9)+ logger.debug(+ f"Exploring faster rate for {engine_type}: {wait_time:.2f}s"+ )+ else:+ # Exploit: use learned estimate with jitter+ wait_time = base_wait * random.uniform(0.9, 1.1)++ # Enforce bounds+ wait_time = max(estimate["min"], min(wait_time, estimate["max"]))+ return wait_time++ def record_outcome(+ self,+ engine_type: str,+ wait_time: float,+ success: bool,+ retry_count: int,+ error_type: Optional[str] = None,+ search_result_count: Optional[int] = None,+ ) -> None:+ """+ Record the outcome of a retry attempt.++ Args:+ engine_type: Name of the search engine+ wait_time: How long we waited before this attempt+ success: Whether the attempt succeeded+ retry_count: Which retry attempt this was (1, 2, 3, etc.)+ error_type: Type of error if failed+ search_result_count: Number of search results returned (for quality monitoring)+ """+ # If rate limiting is disabled, don't record outcomes+ if not self.enabled:+ return+ timestamp = time.time()++ try:+ # Save to database+ session = get_db_session()+ attempt = RateLimitAttempt(+ engine_type=engine_type,+ timestamp=timestamp,+ wait_time=wait_time,+ retry_count=retry_count,+ success=success,+ error_type=error_type,+ )+ session.add(attempt)+ session.commit()+ except Exception as e:+ logger.error(f"Failed to record rate limit outcome: {e}")++ # Update in-memory tracking+ if engine_type not in self.recent_attempts:+ # Get current memory window setting+ from ...utilities.db_utils import get_db_setting++ current_memory_window = int(+ get_db_setting(+ "rate_limiting.memory_window", self.memory_window+ )+ )+ self.recent_attempts[engine_type] = deque(+ maxlen=current_memory_window+ )++ self.recent_attempts[engine_type].append(+ {+ "wait_time": wait_time,+ "success": success,+ "timestamp": timestamp,+ "retry_count": retry_count,+ "search_result_count": search_result_count,+ }+ )++ # Update estimates+ self._update_estimate(engine_type)++ def _update_estimate(self, engine_type: str) -> None:+ """Update wait time estimate based on recent attempts."""+ if (+ engine_type not in self.recent_attempts+ or len(self.recent_attempts[engine_type]) < 3+ ):+ return++ attempts = list(self.recent_attempts[engine_type])++ # Calculate success rate and optimal wait time+ successful_waits = [a["wait_time"] for a in attempts if a["success"]]+ failed_waits = [a["wait_time"] for a in attempts if not a["success"]]++ if not successful_waits:+ # All attempts failed - increase wait time with a cap+ new_base = max(failed_waits) * 1.5 if failed_waits else 10.0+ # Cap the base wait time to prevent runaway growth+ new_base = min(new_base, 10.0) # Max 10 seconds base when all fail+ else:+ # Use 75th percentile of successful waits+ successful_waits.sort()+ percentile_75 = successful_waits[int(len(successful_waits) * 0.75)]+ new_base = percentile_75++ # Update estimate with learning rate (exponential moving average)+ if engine_type in self.current_estimates:+ old_base = self.current_estimates[engine_type]["base"]+ # Get current learning rate from settings+ from ...utilities.db_utils import get_db_setting++ current_learning_rate = float(+ get_db_setting(+ "rate_limiting.learning_rate", self.learning_rate+ )+ )+ new_base = (+ 1 - current_learning_rate+ ) * old_base + current_learning_rate * new_base++ # Apply absolute cap to prevent extreme wait times+ new_base = min(new_base, 10.0) # Cap base at 10 seconds++ # Calculate bounds with more reasonable limits+ min_wait = max(0.5, new_base * 0.5)+ max_wait = min(10.0, new_base * 3.0) # Max 10 seconds absolute cap++ # Update in memory+ self.current_estimates[engine_type] = {+ "base": new_base,+ "min": min_wait,+ "max": max_wait,+ "confidence": min(len(attempts) / 20.0, 1.0),+ }++ # Persist to database+ success_rate = len(successful_waits) / len(attempts) if attempts else 0++ try:+ session = get_db_session()++ # Check if estimate exists+ estimate = (+ session.query(RateLimitEstimate)+ .filter_by(engine_type=engine_type)+ .first()+ )++ if estimate:+ # Update existing estimate+ estimate.base_wait_seconds = new_base+ estimate.min_wait_seconds = min_wait+ estimate.max_wait_seconds = max_wait+ estimate.last_updated = time.time()+ estimate.total_attempts = len(attempts)+ estimate.success_rate = success_rate+ else:+ # Create new estimate+ estimate = RateLimitEstimate(+ engine_type=engine_type,+ base_wait_seconds=new_base,+ min_wait_seconds=min_wait,+ max_wait_seconds=max_wait,+ last_updated=time.time(),+ total_attempts=len(attempts),+ success_rate=success_rate,+ )+ session.add(estimate)++ session.commit()++ except Exception as e:+ logger.error(f"Failed to persist rate limit estimate: {e}")++ logger.info(+ f"Updated rate limit for {engine_type}: {new_base:.2f}s "+ f"(success rate: {success_rate:.1%})"+ )++ def get_stats(+ self, engine_type: Optional[str] = None+ ) -> List[Tuple[str, float, float, float, float, int, float]]:+ """+ Get statistics for monitoring.++ Args:+ engine_type: Specific engine to get stats for, or None for all++ Returns:+ List of tuples with engine statistics+ """+ try:+ session = get_db_session()++ if engine_type:+ estimates = (+ session.query(RateLimitEstimate)+ .filter_by(engine_type=engine_type)+ .all()+ )+ else:+ estimates = (+ session.query(RateLimitEstimate)+ .order_by(RateLimitEstimate.engine_type)+ .all()+ )++ return [+ (+ est.engine_type,+ est.base_wait_seconds,+ est.min_wait_seconds,+ est.max_wait_seconds,+ est.last_updated,+ est.total_attempts,+ est.success_rate,+ )+ for est in estimates+ ]+ except Exception as e:+ logger.error(f"Failed to get rate limit stats: {e}")+ return []++ def reset_engine(self, engine_type: str) -> None:+ """+ Reset learned values for a specific engine.++ Args:+ engine_type: Engine to reset+ """+ try:+ session = get_db_session()++ # Delete historical attempts+ session.query(RateLimitAttempt).filter_by(+ engine_type=engine_type+ ).delete()++ # Delete estimates+ session.query(RateLimitEstimate).filter_by(+ engine_type=engine_type+ ).delete()++ session.commit()++ # Clear from memory+ if engine_type in self.recent_attempts:+ del self.recent_attempts[engine_type]+ if engine_type in self.current_estimates:+ del self.current_estimates[engine_type]++ logger.info(f"Reset rate limit data for {engine_type}")++ except Exception as e:+ logger.error(+ f"Failed to reset rate limit data for {engine_type}: {e}"+ )++ def get_search_quality_stats(+ self, engine_type: Optional[str] = None+ ) -> List[Dict]:+ """+ Get basic search quality statistics for monitoring.++ Args:+ engine_type: Specific engine to get stats for, or None for all++ Returns:+ List of dictionaries with search quality metrics+ """+ stats = []++ engines_to_check = (+ [engine_type] if engine_type else list(self.recent_attempts.keys())+ )++ for engine in engines_to_check:+ if engine not in self.recent_attempts:+ continue++ recent = list(self.recent_attempts[engine])+ search_counts = [+ attempt.get("search_result_count", 0)+ for attempt in recent+ if attempt.get("search_result_count") is not None+ ]++ if not search_counts:+ continue++ recent_avg = sum(search_counts) / len(search_counts)++ stats.append(+ {+ "engine_type": engine,+ "recent_avg_results": recent_avg,+ "min_recent_results": min(search_counts),+ "max_recent_results": max(search_counts),+ "sample_size": len(search_counts),+ "total_attempts": len(recent),+ "status": self._get_quality_status(recent_avg),+ }+ )++ return stats++ def _get_quality_status(self, recent_avg: float) -> str:+ """Get quality status string based on average results."""+ if recent_avg < 1:+ return "CRITICAL"+ elif recent_avg < 3:+ return "WARNING"+ elif recent_avg < 5:+ return "CAUTION"+ elif recent_avg >= 10:+ return "EXCELLENT"+ else:+ return "GOOD"++ def cleanup_old_data(self, days: int = 30) -> None:+ """+ Remove old retry attempt data to prevent database bloat.++ Args:+ days: Remove data older than this many days+ """+ cutoff_time = time.time() - (days * 24 * 3600)++ try:+ session = get_db_session()++ # Count and delete old attempts+ old_attempts = session.query(RateLimitAttempt).filter(+ RateLimitAttempt.timestamp < cutoff_time+ )+ deleted_count = old_attempts.count()+ old_attempts.delete()++ session.commit()++ if deleted_count > 0:+ logger.info(f"Cleaned up {deleted_count} old retry attempts")++ except Exception as e:+ logger.error(f"Failed to cleanup old rate limit data: {e}")+++# Create a singleton instance+_tracker_instance: Optional[AdaptiveRateLimitTracker] = None+++def get_tracker() -> AdaptiveRateLimitTracker:+ """Get the global rate limit tracker instance."""+ global _tracker_instance+ if _tracker_instance is None:+ _tracker_instance = AdaptiveRateLimitTracker()+ return _tracker_instancediff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.pyindex deadb259e5..16dd70ec36 100644--- a/src/local_deep_research/web_search_engines/search_engine_base.py+++ b/src/local_deep_research/web_search_engines/search_engine_base.py@@ -6,10 +6,28 @@ from typing import Any, Dict, List, Optionalfrom langchain_core.language_models import BaseLLMfrom loguru import logger+from tenacity import (+ retry,+ stop_after_attempt,+ retry_if_exception_type,+ RetryError,+)+from tenacity.wait import wait_basefrom ..advanced_search_system.filters.base_filter import BaseFilterfrom ..metrics.search_tracker import get_search_trackerfrom ..utilities.db_utils import get_db_setting+from .rate_limiting import RateLimitError, get_tracker+++class AdaptiveWait(wait_base):+ """Custom wait strategy that uses adaptive rate limiting."""++ def __init__(self, get_wait_func):+ self.get_wait_func = get_wait_func++ def __call__(self, retry_state):+ return self.get_wait_func()class BaseSearchEngine(ABC):@@ -59,6 +77,12 @@ class BaseSearchEngine(ABC):1, int(max_results)) # Ensure it's a positive integer+ # Rate limiting attributes+ self.engine_type = self.__class__.__name__+ self.rate_tracker = get_tracker()+ self._last_wait_time = None+ self._last_results_count = 0+@propertydef max_filtered_results(self) -> int:"""Get the maximum number of filtered results."""@@ -84,6 +108,29 @@ class BaseSearchEngine(ABC):value = 10self._max_results = max(1, int(value))+ def _get_adaptive_wait(self) -> float:+ """Get adaptive wait time from tracker."""+ wait_time = self.rate_tracker.get_wait_time(self.engine_type)+ self._last_wait_time = wait_time+ logger.debug(+ f"{self.engine_type} waiting {wait_time:.2f}s before retry"+ )+ return wait_time++ def _record_retry_outcome(self, retry_state) -> None:+ """Record outcome after retry completes."""+ success = (+ not retry_state.outcome.failed if retry_state.outcome else False+ )+ self.rate_tracker.record_outcome(+ self.engine_type,+ self._last_wait_time or 0,+ success,+ retry_state.attempt_number,+ error_type="RateLimitError" if not success else None,+ search_result_count=self._last_results_count if success else 0,+ )+def run(self, query: str) -> List[Dict[str, Any]]:"""Run the search engine with a given query, retrieving and filtering results.@@ -109,58 +156,112 @@ class BaseSearchEngine(ABC):error_message = Noneresults_count = 0- try:- # Step 1: Get preview information for items- previews = self._get_previews(query)- if not previews:- logger.info(- f"Search engine {self.__class__.__name__} returned no preview results for query: {query}"- )- results_count = 0- return []+ # Define the core search function with retry logic+ if self.rate_tracker.enabled:+ # Rate limiting enabled - use retry with adaptive wait+ @retry(+ stop=stop_after_attempt(3),+ wait=AdaptiveWait(lambda: self._get_adaptive_wait()),+ retry=retry_if_exception_type((RateLimitError,)),+ after=self._record_retry_outcome,+ reraise=True,+ )+ def _run_with_retry():+ nonlocal success, error_message, results_count+ return _execute_search()+ else:+ # Rate limiting disabled - run without retry+ def _run_with_retry():+ nonlocal success, error_message, results_count+ return _execute_search()++ def _execute_search():+ nonlocal success, error_message, results_count++ try:+ # Step 1: Get preview information for items+ previews = self._get_previews(query)+ if not previews:+ logger.info(+ f"Search engine {self.__class__.__name__} returned no preview results for query: {query}"+ )+ results_count = 0+ return []- for preview_filter in self._preview_filters:- previews = preview_filter.filter_results(previews, query)+ for preview_filter in self._preview_filters:+ previews = preview_filter.filter_results(previews, query)- # Step 2: Filter previews for relevance with LLM- # TEMPORARILY DISABLED: Skip LLM relevance filtering- filtered_items = previews- logger.info(- f"LLM relevance filtering disabled - returning all {len(previews)} previews"- )+ # Step 2: Filter previews for relevance with LLM+ # TEMPORARILY DISABLED: Skip LLM relevance filtering+ filtered_items = previews+ logger.info(+ f"LLM relevance filtering disabled - returning all {len(previews)} previews"+ )- # # Original filtering code (disabled):- # filtered_items = self._filter_for_relevance(previews, query)- # if not filtered_items:- # logger.info(- # f"All preview results were filtered out as irrelevant for query: {query}"- # )- # # Do not fall back to previews, return empty list instead- # results_count = 0- # return []-- # Step 3: Get full content for filtered items- # Import config inside the method to avoid circular import-- if get_db_setting("search.snippets_only", True):- logger.info("Returning snippet-only results as per config")- results = filtered_items- else:- results = self._get_full_content(filtered_items)+ # Step 3: Get full content for filtered items+ if get_db_setting("search.snippets_only", True):+ logger.info("Returning snippet-only results as per config")+ results = filtered_items+ else:+ results = self._get_full_content(filtered_items)++ for content_filter in self._content_filters:+ results = content_filter.filter_results(results, query)++ results_count = len(results)+ self._last_results_count = results_count++ # Record success if we get here and rate limiting is enabled+ if (+ self.rate_tracker.enabled+ and self._last_wait_time is not None+ ):+ self.rate_tracker.record_outcome(+ self.engine_type,+ self._last_wait_time,+ success=True,+ retry_count=1, # First attempt succeeded+ search_result_count=results_count,+ )- for content_filter in self._content_filters:- results = content_filter.filter_results(results, query)+ return results- results_count = len(results)- return results+ except RateLimitError:+ # Only re-raise if rate limiting is enabled+ if self.rate_tracker.enabled:+ raise+ else:+ # If rate limiting is disabled, treat as regular error+ success = False+ error_message = "Rate limit hit but rate limiting disabled"+ logger.warning(+ f"Rate limit hit on {self.__class__.__name__} but rate limiting is disabled"+ )+ results_count = 0+ return []+ except Exception as e:+ # Other errors - don't retry+ success = False+ error_message = str(e)+ logger.error(+ f"Search engine {self.__class__.__name__} failed: {e}"+ )+ results_count = 0+ return []+ try:+ return _run_with_retry()+ except RetryError as e:+ # All retries exhausted+ success = False+ error_message = f"Rate limited after all retries: {e}"+ logger.error(f"{self.__class__.__name__} failed after all retries")+ return []except Exception as e:success = Falseerror_message = str(e)- logger.error(f"Search engine {self.__class__.__name__} failed: {e}")- results_count = 0+ logger.error(f"Search engine {self.__class__.__name__} error: {e}")return []-finally:# Record search metricsresponse_time_ms = int((time.time() - start_time) * 1000)diff --git a/src/local_deep_research/web_search_engines/search_engine_factory.py b/src/local_deep_research/web_search_engines/search_engine_factory.pyindex f5c8a3acd3..0c11612c7f 100644--- a/src/local_deep_research/web_search_engines/search_engine_factory.py+++ b/src/local_deep_research/web_search_engines/search_engine_factory.py@@ -313,6 +313,26 @@ def get_search(logger.info(f"Creating search engine for tool: {search_tool} with params: {params.keys()}")++ # Special handling for SearXNG - test basic connectivity+ if search_tool == "searxng":+ try:+ # Test SearXNG basic availability+ import requests++ response = requests.get("http://localhost:8080/", timeout=5)+ if response.status_code == 200:+ logger.info("SearXNG is available and responding")+ else:+ logger.warning(+ f"SearXNG returned status {response.status_code} - may have connectivity issues"+ )+ except Exception as e:+ logger.warning(+ f"SearXNG not accessible ({str(e)}) - service may not be running"+ )+ logger.warning("SearXNG engine will handle fallbacks internally")+engine = create_search_engine(search_tool, **params)# Add debugging to check if engine is Nonediff --git a/tests/run_all_tests.py b/tests/run_all_tests.pyindex c0b33744f0..0b94ca3050 100755--- a/tests/run_all_tests.py+++ b/tests/run_all_tests.py@@ -330,6 +330,7 @@ class TestRunner:"tests/test_search_engines_enhanced.py","tests/test_utils.py","tests/test_research_strategy_orm.py",+ "tests/rate_limiting/", # Rate limiting test suite"tests/feature_tests/","tests/fix_tests/","--cov=src",diff --git a/tests/test_orm_changes.py b/tests/test_orm_changes.pynew file mode 100644index 0000000000..2deb52da14--- /dev/null+++ b/tests/test_orm_changes.py@@ -0,0 +1,80 @@+#!/usr/bin/env python3+"""Test script to verify ORM changes work correctly."""++import os+import sys++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from src.local_deep_research.utilities.db_utils import get_db_session+from src.local_deep_research.web.database.models import (+ Base,+ Research,+ ResearchMode,+ ResearchStatus,+)+from src.local_deep_research.web.services.research_service import (+ get_research_strategy,+ save_research_strategy,+)+from sqlalchemy import create_engine+++def test_orm_changes():+ """Test that the ORM changes work correctly."""+ print("Testing ORM changes...")++ # Create a test database+ test_db_path = "test_orm.db"+ engine = create_engine(f"sqlite:///{test_db_path}")++ # Create all tables+ Base.metadata.create_all(engine)+ print("✓ Tables created successfully")++ # Test save_research_strategy and get_research_strategy+ # First create a test research+ session = get_db_session()+ try:+ test_research = Research(+ query="Test query",+ status=ResearchStatus.COMPLETED,+ mode=ResearchMode.QUICK,+ )+ session.add(test_research)+ session.commit()+ research_id = test_research.id+ print(f"✓ Created test research with ID: {research_id}")+ finally:+ session.close()++ # Test saving a strategy+ test_strategy = "source-based"+ save_research_strategy(research_id, test_strategy)+ print(f"✓ Saved strategy '{test_strategy}' for research {research_id}")++ # Test retrieving the strategy+ retrieved_strategy = get_research_strategy(research_id)+ assert retrieved_strategy == test_strategy, (+ f"Expected '{test_strategy}', got '{retrieved_strategy}'"+ )+ print(f"✓ Retrieved strategy correctly: '{retrieved_strategy}'")++ # Test updating a strategy+ new_strategy = "iterative"+ save_research_strategy(research_id, new_strategy)+ print(f"✓ Updated strategy to '{new_strategy}'")++ retrieved_strategy = get_research_strategy(research_id)+ assert retrieved_strategy == new_strategy, (+ f"Expected '{new_strategy}', got '{retrieved_strategy}'"+ )+ print(f"✓ Retrieved updated strategy correctly: '{retrieved_strategy}'")++ # Cleanup+ os.remove(test_db_path)+ print("\n✅ All ORM tests passed!")+++if __name__ == "__main__":+ test_orm_changes()diff --git a/tests/test_rate_limiting.py b/tests/test_rate_limiting.pynew file mode 100644index 0000000000..32d9e61107--- /dev/null+++ b/tests/test_rate_limiting.py@@ -0,0 +1,254 @@+"""+Tests for the adaptive rate limiting system.+"""++import unittest+from unittest.mock import patch++from src.local_deep_research.web_search_engines.rate_limiting import (+ AdaptiveRateLimitTracker,+ RateLimitError,+)+++class TestAdaptiveRateLimitTracker(unittest.TestCase):+ """Test the AdaptiveRateLimitTracker class."""++ def setUp(self):+ """Set up test fixtures."""+ # Note: Using the main database - in a real test environment+ # you'd want to mock the database session+ self.tracker = AdaptiveRateLimitTracker()++ def tearDown(self):+ """Clean up test fixtures."""+ # Clean up any test data+ try:+ self.tracker.reset_engine("TestEngine")+ except:+ pass++ def test_get_wait_time_new_engine(self):+ """Test getting wait time for a new engine."""+ # Reset any existing data for test engines+ try:+ self.tracker.reset_engine("TestEngine")+ self.tracker.reset_engine("SearXNGSearchEngine")+ self.tracker.reset_engine("LocalSearchEngine")+ except:+ pass++ # Test default engine (unknown)+ wait_time = self.tracker.get_wait_time("TestEngine")+ self.assertEqual(wait_time, 0.5) # Default optimistic++ # Test SearXNG (self-hosted default)+ # Clear from current estimates to force default+ if "SearXNGSearchEngine" in self.tracker.current_estimates:+ del self.tracker.current_estimates["SearXNGSearchEngine"]+ searxng_wait = self.tracker.get_wait_time("SearXNGSearchEngine")+ self.assertEqual(searxng_wait, 0.1) # Very optimistic for self-hosted++ # Test Local search (no network)+ # Clear from current estimates to force default+ if "LocalSearchEngine" in self.tracker.current_estimates:+ del self.tracker.current_estimates["LocalSearchEngine"]+ local_wait = self.tracker.get_wait_time("LocalSearchEngine")+ self.assertEqual(local_wait, 0.0) # No wait for local search++ def test_record_outcome_and_learning(self):+ """Test recording outcomes and learning from them."""+ engine_type = "TestEngine"++ # Record several successful attempts with different wait times+ successful_waits = [2.0, 2.5, 3.0, 2.2, 2.8]+ for i, wait_time in enumerate(successful_waits):+ self.tracker.record_outcome(+ engine_type=engine_type,+ wait_time=wait_time,+ success=True,+ retry_count=1,+ )++ # The tracker should have learned from these attempts+ self.assertIn(engine_type, self.tracker.current_estimates)++ # Get new wait time - should be influenced by successful attempts+ new_wait_time = self.tracker.get_wait_time(engine_type)+ self.assertGreater(new_wait_time, 0)++ def test_record_failure_increases_wait_time(self):+ """Test that failures increase the wait time when all attempts fail."""+ engine_type = "TestEngine"++ # Record some initial successful attempts (need at least 3 for estimate creation)+ for wait_time in [2.0, 2.5, 3.0]:+ self.tracker.record_outcome(+ engine_type=engine_type,+ wait_time=wait_time,+ success=True,+ retry_count=1,+ )++ initial_estimate = self.tracker.current_estimates[engine_type]["base"]++ # Reset and record only failures to test failure handling+ self.tracker.recent_attempts[engine_type] = (+ self.tracker.recent_attempts[engine_type].__class__(+ maxlen=self.tracker.memory_window+ )+ )++ # Record only failures (this should increase wait time)+ for wait_time in [2.0, 2.5, 3.0]:+ self.tracker.record_outcome(+ engine_type=engine_type,+ wait_time=wait_time,+ success=False,+ retry_count=2,+ error_type="RateLimitError",+ )++ # Base wait time should increase after all failures+ new_estimate = self.tracker.current_estimates[engine_type]["base"]+ self.assertGreater(new_estimate, initial_estimate)++ def test_persistence(self):+ """Test that estimates are persisted across instances."""+ engine_type = "TestEngine2" # Use different name to avoid conflicts++ # Record enough data to create an estimate (need at least 3 attempts)+ for wait_time in [4.0, 5.0, 6.0]:+ self.tracker.record_outcome(+ engine_type=engine_type,+ wait_time=wait_time,+ success=True,+ retry_count=1,+ )++ original_base = self.tracker.current_estimates[engine_type]["base"]++ # Create a new tracker instance (uses same database)+ new_tracker = AdaptiveRateLimitTracker()++ # Should load the previous estimate+ self.assertIn(engine_type, new_tracker.current_estimates)+ loaded_base = new_tracker.current_estimates[engine_type]["base"]++ # Should be close to the original (allowing for decay)+ self.assertAlmostEqual(loaded_base, original_base, delta=1.0)++ # Clean up+ new_tracker.reset_engine(engine_type)++ def test_get_stats(self):+ """Test getting statistics."""+ engine_type = "TestEngine"++ # Record enough data to create an estimate (need at least 3 attempts)+ for wait_time in [3.0, 3.5, 4.0]:+ self.tracker.record_outcome(+ engine_type=engine_type,+ wait_time=wait_time,+ success=True,+ retry_count=1,+ )++ # Get stats for specific engine+ stats = self.tracker.get_stats(engine_type)+ self.assertEqual(len(stats), 1)+ self.assertEqual(+ stats[0][0], engine_type+ ) # engine_type is first column++ # Get stats for all engines+ all_stats = self.tracker.get_stats()+ self.assertGreaterEqual(len(all_stats), 1)++ def test_reset_engine(self):+ """Test resetting an engine's data."""+ engine_type = "TestEngine"++ # Record enough data to create an estimate (need at least 3 attempts)+ for wait_time in [3.0, 3.5, 4.0]:+ self.tracker.record_outcome(+ engine_type=engine_type,+ wait_time=wait_time,+ success=True,+ retry_count=1,+ )++ # Verify data exists+ self.assertIn(engine_type, self.tracker.current_estimates)++ # Reset the engine+ self.tracker.reset_engine(engine_type)++ # Data should be gone+ self.assertNotIn(engine_type, self.tracker.current_estimates)+ stats = self.tracker.get_stats(engine_type)+ self.assertEqual(len(stats), 0)++ def test_exploration_vs_exploitation(self):+ """Test that exploration sometimes returns different wait times."""+ engine_type = "TestEngine"++ # Set up a known estimate+ self.tracker.current_estimates[engine_type] = {+ "base": 10.0,+ "min": 5.0,+ "max": 20.0,+ "confidence": 0.8,+ }++ # Get multiple wait times+ wait_times = [+ self.tracker.get_wait_time(engine_type) for _ in range(50)+ ]++ # Should have some variation due to exploration and jitter+ unique_times = set(wait_times)+ self.assertGreater(len(unique_times), 5) # Should have some variation++ # All should be within bounds+ for wait_time in wait_times:+ self.assertGreaterEqual(wait_time, 5.0)+ self.assertLessEqual(wait_time, 20.0)+++class TestRateLimitIntegration(unittest.TestCase):+ """Test rate limiting integration with search engines."""++ def test_rate_limit_error_exception(self):+ """Test that RateLimitError can be raised and caught."""+ with self.assertRaises(RateLimitError):+ raise RateLimitError("Test rate limit")++ @patch(+ "src.local_deep_research.web_search_engines.rate_limiting.tracker.AdaptiveRateLimitTracker"+ )+ def test_base_search_engine_integration(self, mock_tracker_class):+ """Test integration with BaseSearchEngine."""+ # This would require more complex mocking of the search engine+ # For now, just verify the import works+ from src.local_deep_research.web_search_engines.search_engine_base import (+ BaseSearchEngine,+ )++ # Create a mock engine to verify rate_tracker is set during init+ # We need to provide required abstract methods+ class MockSearchEngine(BaseSearchEngine):+ def _get_previews(self, query):+ return []++ def _get_full_content(self, relevant_items):+ return []++ # Create instance and verify rate_tracker is set+ mock_engine = MockSearchEngine()+ self.assertTrue(hasattr(mock_engine, "rate_tracker"))+ self.assertIsNotNone(mock_engine.rate_tracker)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/ui_tests/run_all_tests.js b/tests/ui_tests/run_all_tests.jsindex 7f26e11da0..26e1c20f08 100644--- a/tests/ui_tests/run_all_tests.js+++ b/tests/ui_tests/run_all_tests.js@@ -47,6 +47,11 @@ const tests = [name: 'Star Reviews Test',file: 'test_star_reviews.js',description: 'Tests star reviews analytics page and visualizations'+ },+ {+ name: 'Rate Limiting Settings Test',+ file: 'test_rate_limiting_settings.js',+ description: 'Tests rate limiting settings panel functionality and API integration'}];diff --git a/tests/ui_tests/test_rate_limiting_settings.js b/tests/ui_tests/test_rate_limiting_settings.jsnew file mode 100644index 0000000000..c45326c160--- /dev/null+++ b/tests/ui_tests/test_rate_limiting_settings.js@@ -0,0 +1,291 @@+/**+ * Rate Limiting Settings UI Test+ *+ * Comprehensive test of the rate limiting settings panel in the web UI.+ * Tests all form elements, API interactions, and visual feedback.+ *+ * Prerequisites: Web server running on http://127.0.0.1:5000+ *+ * Usage: node tests/ui_tests/test_rate_limiting_settings.js+ */++const puppeteer = require('puppeteer');++async function testRateLimitingSettings() {+ const browser = await puppeteer.launch({+ headless: process.env.CI ? true : false,+ args: ['--no-sandbox', '--disable-setuid-sandbox']+ });+ const page = await browser.newPage();++ // Set viewport for consistent testing+ await page.setViewport({ width: 1280, height: 720 });++ // Monitor network requests for API calls+ const apiRequests = [];+ await page.setRequestInterception(true);+ page.on('request', request => {+ if (request.url().includes('/api/v1/settings')) {+ apiRequests.push({+ method: request.method(),+ url: request.url(),+ postData: request.postData()+ });+ console.log('API REQUEST:', request.method(), request.url());+ }+ request.continue();+ });++ page.on('response', response => {+ if (response.url().includes('/api/v1/settings')) {+ console.log('API RESPONSE:', response.status(), response.url());+ }+ });++ try {+ console.log('🚀 Starting rate limiting settings UI test...');++ // Navigate to settings page+ console.log('📍 Navigating to settings page...');+ await page.goto('http://127.0.0.1:5000/research/settings', {+ waitUntil: 'networkidle2',+ timeout: 30000+ });++ // Wait for settings to load+ console.log('⏳ Waiting for settings to load...');+ await page.waitForTimeout(3000);++ // Test 1: Check if rate limiting section exists+ console.log('🔍 Test 1: Checking for rate limiting section...');+ const rateLimitingSection = await page.$('[data-category="rate_limiting"], .rate-limiting-section, #rate-limiting');+ if (rateLimitingSection) {+ console.log('✅ Rate limiting section found');+ } else {+ console.log('❌ Rate limiting section not found');+ // Try to find any settings related to rate limiting+ const rateLimitingSettings = await page.$$eval('*', els =>+ els.filter(el => el.textContent && el.textContent.toLowerCase().includes('rate limit')).length+ );+ console.log(`Found ${rateLimitingSettings} elements mentioning rate limiting`);+ }++ // Test 2: Check for rate limiting enabled checkbox+ console.log('🔍 Test 2: Checking for rate limiting enabled checkbox...');+ const enabledCheckbox = await page.$('input[type="checkbox"][name*="rate_limiting"], input[type="checkbox"][id*="rate_limiting"]');+ if (enabledCheckbox) {+ console.log('✅ Rate limiting enabled checkbox found');++ // Test toggling the checkbox+ const isChecked = await page.evaluate(el => el.checked, enabledCheckbox);+ console.log(`📊 Initial state: ${isChecked ? 'enabled' : 'disabled'}`);++ // Toggle the checkbox+ await enabledCheckbox.click();+ await page.waitForTimeout(1000); // Wait for potential API call++ const newState = await page.evaluate(el => el.checked, enabledCheckbox);+ console.log(`📊 After toggle: ${newState ? 'enabled' : 'disabled'}`);++ if (newState !== isChecked) {+ console.log('✅ Checkbox toggle works correctly');+ } else {+ console.log('❌ Checkbox toggle failed');+ }+ } else {+ console.log('❌ Rate limiting enabled checkbox not found');+ }++ // Test 3: Check for rate limiting profile selector+ console.log('🔍 Test 3: Checking for rate limiting profile selector...');+ const profileSelector = await page.$('select[name*="profile"], select[id*="profile"], .profile-selector select');+ if (profileSelector) {+ console.log('✅ Rate limiting profile selector found');++ // Get available options+ const options = await page.evaluate(select =>+ Array.from(select.options).map(option => option.value), profileSelector+ );+ console.log('📊 Available profiles:', options);++ // Test selecting different profiles+ if (options.includes('conservative')) {+ await page.select(profileSelector, 'conservative');+ console.log('✅ Selected conservative profile');+ await page.waitForTimeout(500);+ }++ if (options.includes('balanced')) {+ await page.select(profileSelector, 'balanced');+ console.log('✅ Selected balanced profile');+ await page.waitForTimeout(500);+ }++ if (options.includes('aggressive')) {+ await page.select(profileSelector, 'aggressive');+ console.log('✅ Selected aggressive profile');+ await page.waitForTimeout(500);+ }+ } else {+ console.log('❌ Rate limiting profile selector not found');+ }++ // Test 4: Check for numeric input fields (learning rate, exploration rate, etc.)+ console.log('🔍 Test 4: Checking for numeric input fields...');+ const numericInputs = await page.$$('input[type="number"], input[step]');+ console.log(`📊 Found ${numericInputs.length} numeric input fields`);++ for (let i = 0; i < Math.min(numericInputs.length, 3); i++) {+ const input = numericInputs[i];+ const name = await page.evaluate(el => el.name || el.id, input);+ const value = await page.evaluate(el => el.value, input);+ console.log(`📊 Numeric input ${i + 1}: ${name} = ${value}`);++ // Test changing the value+ await input.click({ clickCount: 3 }); // Select all text+ await input.type('0.5');+ await page.waitForTimeout(300);+ console.log(`✅ Updated numeric input ${i + 1}`);+ }++ // Test 5: Check for rate limiting statistics/status display+ console.log('🔍 Test 5: Checking for rate limiting statistics...');+ const statisticsElements = await page.$$('.statistics, .status, .rate-limit-stats, [class*="stat"]');+ if (statisticsElements.length > 0) {+ console.log(`✅ Found ${statisticsElements.length} statistics elements`);++ // Try to read some statistics values+ for (let i = 0; i < Math.min(statisticsElements.length, 3); i++) {+ const text = await page.evaluate(el => el.textContent, statisticsElements[i]);+ if (text && text.trim()) {+ console.log(`📊 Statistics ${i + 1}: ${text.trim().substring(0, 50)}...`);+ }+ }+ } else {+ console.log('❌ No rate limiting statistics found');+ }++ // Test 6: Test save/submit functionality+ console.log('🔍 Test 6: Testing save functionality...');+ const saveButton = await page.$('button[type="submit"], .save-button, button:contains("Save")');+ if (saveButton) {+ console.log('✅ Save button found');++ const initialRequestCount = apiRequests.length;+ await saveButton.click();+ await page.waitForTimeout(2000); // Wait for API calls++ const newRequestCount = apiRequests.length;+ if (newRequestCount > initialRequestCount) {+ console.log('✅ Save triggered API requests');+ console.log(`📊 API requests: ${newRequestCount - initialRequestCount} new requests`);+ } else {+ console.log('❌ Save did not trigger API requests');+ }+ } else {+ console.log('❌ Save button not found');+ }++ // Test 7: Check for validation feedback+ console.log('🔍 Test 7: Testing validation feedback...');+ const errorElements = await page.$$('.error, .validation-error, .invalid-feedback, [class*="error"]');+ console.log(`📊 Found ${errorElements.length} potential error elements`);++ // Test 8: Check for help text or tooltips+ console.log('🔍 Test 8: Checking for help text...');+ const helpElements = await page.$$('.help-text, .tooltip, .description, [title]');+ console.log(`📊 Found ${helpElements.length} help/tooltip elements`);++ // Test 9: Responsive design test+ console.log('🔍 Test 9: Testing responsive design...');+ await page.setViewport({ width: 768, height: 1024 }); // Tablet view+ await page.waitForTimeout(500);++ const visibleElements = await page.evaluate(() => {+ const elements = document.querySelectorAll('input, select, button');+ return Array.from(elements).filter(el => {+ const style = window.getComputedStyle(el);+ return style.display !== 'none' && style.visibility !== 'hidden';+ }).length;+ });++ console.log(`📊 Visible form elements in tablet view: ${visibleElements}`);++ await page.setViewport({ width: 375, height: 667 }); // Mobile view+ await page.waitForTimeout(500);++ const mobileVisibleElements = await page.evaluate(() => {+ const elements = document.querySelectorAll('input, select, button');+ return Array.from(elements).filter(el => {+ const style = window.getComputedStyle(el);+ return style.display !== 'none' && style.visibility !== 'hidden';+ }).length;+ });++ console.log(`📊 Visible form elements in mobile view: ${mobileVisibleElements}`);++ // Test 10: Performance test+ console.log('🔍 Test 10: Performance test...');+ const navigationTiming = await page.evaluate(() => {+ const timing = performance.getEntriesByType('navigation')[0];+ return {+ domContentLoaded: timing.domContentLoadedEventEnd - timing.domContentLoadedEventStart,+ loadComplete: timing.loadEventEnd - timing.loadEventStart,+ total: timing.loadEventEnd - timing.fetchStart+ };+ });++ console.log('📊 Page load performance:');+ console.log(` DOM Content Loaded: ${navigationTiming.domContentLoaded.toFixed(2)}ms`);+ console.log(` Load Complete: ${navigationTiming.loadComplete.toFixed(2)}ms`);+ console.log(` Total Load Time: ${navigationTiming.total.toFixed(2)}ms`);++ // Summary+ console.log('📊 Test Summary:');+ console.log(` Total API requests: ${apiRequests.length}`);+ console.log(` Form elements tested: Multiple categories`);+ console.log(` Responsive views tested: Desktop, Tablet, Mobile`);++ // Take screenshot for debugging+ await page.screenshot({+ path: 'rate_limiting_settings_test.png',+ fullPage: true+ });+ console.log('📸 Screenshot saved as rate_limiting_settings_test.png');++ console.log('🎉 Rate limiting settings UI test completed successfully');++ } catch (error) {+ console.error('❌ Error during rate limiting settings test:', error);++ // Take error screenshot+ try {+ await page.screenshot({+ path: 'rate_limiting_settings_error.png',+ fullPage: true+ });+ console.log('📸 Error screenshot saved as rate_limiting_settings_error.png');+ } catch (screenshotError) {+ console.error('Failed to take error screenshot:', screenshotError);+ }++ throw error;+ } finally {+ await browser.close();+ }+}++// Run the test+if (require.main === module) {+ testRateLimitingSettings()+ .then(() => {+ console.log('✅ All rate limiting UI tests completed');+ process.exit(0);+ })+ .catch(error => {+ console.error('❌ Rate limiting UI tests failed:', error);+ process.exit(1);+ });+}++module.exports = { testRateLimitingSettings };