~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
added parallel and rapid search and some minor optimizations
LearningCircuit14289e940dc5
diff --git a/src/local_deep_research/advanced_search_system/questions/decomposition_question.py b/src/local_deep_research/advanced_search_system/questions/decomposition_question.pyindex 0d22a2be83..237fd1789c 100644--- a/src/local_deep_research/advanced_search_system/questions/decomposition_question.py+++ b/src/local_deep_research/advanced_search_system/questions/decomposition_question.py@@ -49,16 +49,23 @@ Main Query: {query}Context (Initial Search Results):{context}-Sub-queries (one per line):+Format your response with each sub-query on a new line starting with Q:, for example:+Q: First sub-query+Q: Second sub-query+Q: Third sub-query"""logger.info(f"Generating sub-questions for query: '{query}'. Context length: {len(context)}")response = self.model.invoke(prompt)- # Assume response is a string with each question on a new line++ # Use the same question extraction method as standard strategysub_queries = [- q.strip() for q in response.content.strip().split("\n") if q.strip()- ]+ q.replace("Q:", "").strip()+ for q in response.content.split("\n")+ if q.strip().startswith("Q:")+ ][: self.max_subqueries]+logger.info(f"Generated {len(sub_queries)} sub-questions.")- return sub_queries[: self.max_subqueries] # Limit to max_subqueries+ return sub_queriesdiff --git a/src/local_deep_research/advanced_search_system/questions/standard_question.py b/src/local_deep_research/advanced_search_system/questions/standard_question.pyindex 2449ad7a75..fa1760d755 100644--- a/src/local_deep_research/advanced_search_system/questions/standard_question.py+++ b/src/local_deep_research/advanced_search_system/questions/standard_question.py@@ -6,7 +6,6 @@ import loggingfrom datetime import datetimefrom typing import List-from ...utilties.search_utilities import remove_think_tagsfrom .base_question import BaseQuestionGeneratorlogger = logging.getLogger(__name__)@@ -43,7 +42,7 @@ class StandardQuestionGenerator(BaseQuestionGenerator):response = self.model.invoke(prompt)questions = [q.replace("Q:", "").strip()- for q in remove_think_tags(response.content).split("\n")+ for q in response.content.split("\n")if q.strip().startswith("Q:")][:questions_per_iteration]@@ -84,7 +83,7 @@ Only provide the numbered sub-questions, nothing else."""try:response = self.model.invoke(prompt)- content = remove_think_tags(response.content)+ content = response.content# Parse sub-questions from the responsesub_questions = []diff --git a/src/local_deep_research/advanced_search_system/strategies/parallel_search_strategy.py b/src/local_deep_research/advanced_search_system/strategies/parallel_search_strategy.pynew file mode 100644index 0000000000..abb5da26ed--- /dev/null+++ b/src/local_deep_research/advanced_search_system/strategies/parallel_search_strategy.py@@ -0,0 +1,216 @@+"""+Parallel search strategy implementation for maximum search speed.+"""++import concurrent.futures+import logging+from typing import Dict++from ...citation_handler import CitationHandler+from ...config.llm_config import get_llm+from ...config.search_config import get_search+from ...utilties.search_utilities import extract_links_from_search_results+from ..findings.repository import FindingsRepository+from ..questions.standard_question import StandardQuestionGenerator+from .base_strategy import BaseSearchStrategy++logger = logging.getLogger(__name__)+++class ParallelSearchStrategy(BaseSearchStrategy):+ """+ Parallel search strategy that generates questions and runs all searches+ simultaneously for maximum speed.+ """++ def __init__(self, search=None, model=None, citation_handler=None):+ """Initialize with optional dependency injection for testing."""+ super().__init__()+ self.search = search or get_search()+ self.model = model or get_llm()+ self.progress_callback = None+ self.all_links_of_system = list()+ self.questions_by_iteration = {}++ # Use provided citation_handler or create one+ self.citation_handler = citation_handler or CitationHandler(self.model)++ # Initialize components+ self.question_generator = StandardQuestionGenerator(self.model)+ self.findings_repository = FindingsRepository(self.model)++ def analyze_topic(self, query: str) -> Dict:+ """+ Parallel implementation that generates questions and searches all at once.+ """+ logger.info(f"Starting parallel research on topic: {query}")++ findings = []+ all_search_results = []++ self._update_progress(+ "Initializing parallel research",+ 5,+ {"phase": "init", "strategy": "parallel"},+ )++ # Check search engine+ if not self._validate_search_engine():+ return {+ "findings": [],+ "iterations": 0,+ "questions": {},+ "formatted_findings": "Error: Unable to conduct research without a search engine.",+ "current_knowledge": "",+ "error": "No search engine available",+ }++ # Force snippet-only mode+ original_snippet_mode = None+ if hasattr(self.search, "include_full_content"):+ original_snippet_mode = self.search.include_full_content+ self.search.include_full_content = False++ try:+ # Step 1: Generate questions first+ self._update_progress(+ "Generating search questions", 10, {"phase": "question_generation"}+ )++ # Generate 3 additional questions (plus the main query = 4 total)+ questions = self.question_generator.generate_questions(+ current_knowledge="", # No knowledge accumulation+ query=query,+ questions_per_iteration=3, # 3 additional questions+ questions_by_iteration={},+ )++ # Add the original query as the first question+ all_questions = [query] + questions++ # Store in questions_by_iteration+ self.questions_by_iteration[0] = questions+ logger.info(f"Generated questions: {questions}")++ # Step 2: Run all searches in parallel+ self._update_progress(+ "Running parallel searches for all questions",+ 20,+ {"phase": "parallel_search"},+ )++ # Function for thread pool+ def search_question(q):+ try:+ result = self.search.run(q)+ return {"question": q, "results": result or []}+ except Exception as e:+ logger.error(f"Error searching for '{q}': {str(e)}")+ return {"question": q, "results": [], "error": str(e)}++ # Run searches in parallel+ with concurrent.futures.ThreadPoolExecutor(+ max_workers=len(all_questions)+ ) as executor:+ futures = [executor.submit(search_question, q) for q in all_questions]+ all_search_dict = {}++ # Process results as they complete+ for i, future in enumerate(concurrent.futures.as_completed(futures)):+ result_dict = future.result()+ question = result_dict["question"]+ search_results = result_dict["results"]+ all_search_dict[question] = search_results++ self._update_progress(+ f"Completed search {i + 1} of {len(all_questions)}: {question[:30]}...",+ 20 + ((i + 1) / len(all_questions) * 40),+ {+ "phase": "search_complete",+ "result_count": len(search_results),+ "question": question,+ },+ )++ # Extract and save links+ links = extract_links_from_search_results(search_results)+ self.all_links_of_system.extend(links)+ all_search_results.extend(search_results)++ # Step 3: Single analysis of all collected search results+ self._update_progress(+ "Analyzing all collected search results",+ 70,+ {"phase": "final_analysis"},+ )++ # Use citation handler for analysis of all results together+ result = self.citation_handler.analyze_initial(query, all_search_results)++ if result:+ synthesized_content = result["content"]+ finding = {+ "phase": "Final synthesis",+ "content": synthesized_content,+ "question": query,+ "search_results": all_search_results,+ "documents": result.get("documents", []),+ }+ findings.append(finding)++ # Transfer questions to repository+ self.findings_repository.set_questions_by_iteration(+ self.questions_by_iteration+ )++ # Format findings+ formatted_findings = self.findings_repository.format_findings_to_text(+ findings, synthesized_content+ )++ # Add documents to repository+ if "documents" in result:+ self.findings_repository.add_documents(result["documents"])+ else:+ synthesized_content = "No relevant results found."+ formatted_findings = synthesized_content+ finding = {+ "phase": "Error",+ "content": "No relevant results found.",+ "question": query,+ "search_results": all_search_results,+ "documents": [],+ }+ findings.append(finding)++ except Exception as e:+ error_msg = f"Error in research process: {str(e)}"+ logger.error(error_msg)+ synthesized_content = f"Error: {str(e)}"+ formatted_findings = f"Error: {str(e)}"+ finding = {+ "phase": "Error",+ "content": synthesized_content,+ "question": query,+ "search_results": [],+ "documents": [],+ }+ findings.append(finding)++ finally:+ # Restore original settings+ if (+ hasattr(self.search, "include_full_content")+ and original_snippet_mode is not None+ ):+ self.search.include_full_content = original_snippet_mode++ self._update_progress("Research complete", 100, {"phase": "complete"})++ return {+ "findings": findings,+ "iterations": 1,+ "questions": self.questions_by_iteration,+ "formatted_findings": formatted_findings,+ "current_knowledge": synthesized_content,+ }diff --git a/src/local_deep_research/advanced_search_system/strategies/rapid_search_strategy.py b/src/local_deep_research/advanced_search_system/strategies/rapid_search_strategy.pynew file mode 100644index 0000000000..ac2f84091f--- /dev/null+++ b/src/local_deep_research/advanced_search_system/strategies/rapid_search_strategy.py@@ -0,0 +1,270 @@+"""+RapidSearch strategy implementation.+"""++import logging+from typing import Dict++from ...citation_handler import CitationHandler+from ...config.llm_config import get_llm+from ...config.search_config import get_search+from ...utilties.search_utilities import extract_links_from_search_results+from ..findings.repository import FindingsRepository+from ..knowledge.standard_knowledge import StandardKnowledge+from ..questions.standard_question import StandardQuestionGenerator+from .base_strategy import BaseSearchStrategy++logger = logging.getLogger(__name__)+++class RapidSearchStrategy(BaseSearchStrategy):+ """+ Rapid search strategy that only analyzes snippets and performs+ a single synthesis step at the end, optimized for speed.+ """++ def __init__(self, search=None, model=None, citation_handler=None):+ """Initialize with optional dependency injection for testing."""+ super().__init__()+ self.search = search or get_search()+ self.model = model or get_llm()+ self.progress_callback = None+ self.all_links_of_system = list()+ self.questions_by_iteration = {}++ # Use provided citation_handler or create one+ self.citation_handler = citation_handler or CitationHandler(self.model)++ # Initialize components+ self.question_generator = StandardQuestionGenerator(self.model)+ self.knowledge_generator = StandardKnowledge(self.model)+ self.findings_repository = FindingsRepository(self.model)++ def analyze_topic(self, query: str) -> Dict:+ """+ RapidSearch implementation that collects snippets, avoids intermediate+ synthesis, and only performs a final synthesis at the end.+ """+ logger.info(f"Starting rapid research on topic: {query}")++ findings = []+ all_search_results = []+ collected_snippets = []+ section_links = list()++ self._update_progress(+ "Initializing rapid research system",+ 5,+ {"phase": "init", "strategy": "rapid"},+ )++ # Check if search engine is available+ if not self._validate_search_engine():+ return {+ "findings": [],+ "iterations": 0,+ "questions": {},+ "formatted_findings": "Error: Unable to conduct research without a search engine.",+ "current_knowledge": "",+ "error": "No search engine available",+ }++ # Step 1: Initial search for the main query+ self._update_progress(+ "Performing initial search for main query",+ 10,+ {"phase": "search", "iteration": 1},+ )++ try:+ initial_results = self.search.run(query)++ if not initial_results:+ self._update_progress(+ "No initial results found",+ 15,+ {"phase": "search_complete", "result_count": 0},+ )+ initial_results = []+ else:+ self._update_progress(+ f"Found {len(initial_results)} initial results",+ 15,+ {"phase": "search_complete", "result_count": len(initial_results)},+ )++ # Extract snippets and links+ for result in initial_results:+ if "snippet" in result:+ collected_snippets.append(+ {+ "text": result["snippet"],+ "source": result.get("title", "Unknown Source"),+ "link": result.get("link", ""),+ "query": query,+ }+ )++ # Extract and save links+ initial_links = extract_links_from_search_results(initial_results)+ self.all_links_of_system.extend(initial_links)+ section_links.extend(initial_links)+ all_search_results.extend(initial_results)++ # No findings added here - just collecting data++ except Exception as e:+ error_msg = f"Error during initial search: {str(e)}"+ logger.error(f"SEARCH ERROR: {error_msg}")+ self._update_progress(+ error_msg, 15, {"phase": "search_error", "error": str(e)}+ )+ initial_results = []++ # Step 2: Generate a few follow-up questions (optional, can be skipped for ultimate speed)+ self._update_progress(+ "Generating follow-up questions", 25, {"phase": "question_generation"}+ )++ questions = self.question_generator.generate_questions(+ current_knowledge="", # No knowledge accumulation in rapid mode+ query=query,+ questions_per_iteration=3, # Fewer questions for speed+ questions_by_iteration={},+ )++ self.questions_by_iteration[0] = questions+ logger.info(f"Generated questions: {questions}")++ # Step 3: Process follow-up questions+ question_count = len(questions)+ for q_idx, question in enumerate(questions):+ question_progress = 30 + ((q_idx + 1) / question_count * 40)++ self._update_progress(+ f"Searching for: {question}",+ int(question_progress),+ {"phase": "search", "question_index": q_idx + 1},+ )++ try:+ search_results = self.search.run(question)++ if not search_results:+ self._update_progress(+ f"No results found for question: {question}",+ int(question_progress + 2),+ {"phase": "search_complete", "result_count": 0},+ )+ continue++ self._update_progress(+ f"Found {len(search_results)} results for question: {question}",+ int(question_progress + 5),+ {"phase": "search_complete", "result_count": len(search_results)},+ )++ # Extract snippets only+ for result in search_results:+ if "snippet" in result:+ collected_snippets.append(+ {+ "text": result["snippet"],+ "source": result.get("title", "Unknown Source"),+ "link": result.get("link", ""),+ "query": question,+ }+ )++ # Extract and save links+ links = extract_links_from_search_results(search_results)+ self.all_links_of_system.extend(links)+ section_links.extend(links)+ all_search_results.extend(search_results)++ # No findings added here - just collecting data++ except Exception as e:+ error_msg = f"Error during search: {str(e)}"+ logger.error(f"SEARCH ERROR: {error_msg}")+ self._update_progress(+ error_msg,+ int(question_progress + 2),+ {"phase": "search_error", "error": str(e)},+ )++ # Step 4: Perform a single final synthesis with all collected snippets using the citation handler+ self._update_progress(+ "Synthesizing all collected information", 80, {"phase": "final_synthesis"}+ )++ try:+ # Use citation handler for the final analysis+ # First, we need a stub of current knowledge++ # Use the citation handler to analyze the results+ result = self.citation_handler.analyze_initial(query, all_search_results)++ if result:+ synthesized_content = result["content"]++ # Create a synthesis finding+ finding = {+ "phase": "Final synthesis",+ "content": synthesized_content,+ "question": query,+ "search_results": all_search_results,+ "documents": result.get("documents", []),+ }+ findings.append(finding)++ # Transfer questions to the repository+ self.findings_repository.set_questions_by_iteration(+ self.questions_by_iteration+ )++ # Format the findings with search questions and sources+ formatted_findings = self.findings_repository.format_findings_to_text(+ findings, synthesized_content+ )++ # Also add to the repository+ self.findings_repository.add_documents(result.get("documents", []))+ else:+ # Fallback if citation handler fails+ synthesized_content = (+ "Error: Failed to synthesize results with citation handler."+ )+ formatted_findings = synthesized_content+ finding = {+ "phase": "Error",+ "content": synthesized_content,+ "question": query,+ "search_results": all_search_results,+ "documents": [],+ }+ findings.append(finding)++ except Exception as e:+ error_msg = f"Error synthesizing final answer: {str(e)}"+ logger.error(error_msg)+ synthesized_content = f"Error generating synthesis: {str(e)}"+ formatted_findings = f"Error: {str(e)}"+ finding = {+ "phase": "Error",+ "content": synthesized_content,+ "question": query,+ "search_results": all_search_results,+ "documents": [],+ }+ findings.append(finding)++ self._update_progress("Research complete", 100, {"phase": "complete"})++ return {+ "findings": findings,+ "iterations": 1, # Always 1 iteration in rapid mode+ "questions": self.questions_by_iteration,+ "formatted_findings": formatted_findings,+ "current_knowledge": synthesized_content,+ }diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.pyindex fa1964fb7b..59814a0b0c 100644--- a/src/local_deep_research/search_system.py+++ b/src/local_deep_research/search_system.py@@ -3,6 +3,10 @@ import loggingfrom typing import Callable, Dictfrom .advanced_search_system.strategies.iterdrag_strategy import IterDRAGStrategy+from .advanced_search_system.strategies.parallel_search_strategy import (+ ParallelSearchStrategy,+)+from .advanced_search_system.strategies.rapid_search_strategy import RapidSearchStrategyfrom .advanced_search_system.strategies.standard_strategy import StandardSearchStrategyfrom .config.config_files import settingsfrom .config.llm_config import get_llm@@ -12,7 +16,7 @@ logger = logging.getLogger(__name__)class AdvancedSearchSystem:- def __init__(self, strategy_name: str = "iterdrag"):+ def __init__(self, strategy_name: str = "parallel"):"""Initialize the advanced search system.@@ -34,6 +38,12 @@ class AdvancedSearchSystem:if strategy_name.lower() == "iterdrag":logger.info("Creating IterDRAGStrategy instance")self.strategy = IterDRAGStrategy(model=self.model, search=self.search)+ elif strategy_name.lower() == "parallel":+ logger.info("Creating ParallelSearchStrategy instance")+ self.strategy = ParallelSearchStrategy(model=self.model, search=self.search)+ elif strategy_name.lower() == "rapid":+ logger.info("Creating RapidSearchStrategy instance")+ self.strategy = RapidSearchStrategy(model=self.model, search=self.search)else:logger.info("Creating StandardSearchStrategy instance")self.strategy = StandardSearchStrategy(model=self.model, search=self.search)@@ -57,12 +67,10 @@ class AdvancedSearchSystem:self.strategy.set_progress_callback(callback)def analyze_topic(self, query: str) -> Dict:-"""Analyze a topic using the current strategy."""# Use the strategy to analyze the topicresult = self.strategy.analyze_topic(query)-# Update our attributes for backward compatibilityif hasattr(self.strategy, "questions_by_iteration"):self.questions_by_iteration = self.strategy.questions_by_iteration