~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
working on advanced search
LearningCircuit86885762769f
diff --git a/src/local_deep_research/search_system/__init__.py b/src/local_deep_research/search_system/__init__.pynew file mode 100644index 0000000000..8428fb7824--- /dev/null+++ b/src/local_deep_research/search_system/__init__.py@@ -0,0 +1 @@+# Search System Packagediff --git a/src/local_deep_research/search_system/knowledge/__init__.py b/src/local_deep_research/search_system/knowledge/__init__.pynew file mode 100644index 0000000000..3a48a7167b--- /dev/null+++ b/src/local_deep_research/search_system/knowledge/__init__.py@@ -0,0 +1 @@+# Search System Knowledge Packagediff --git a/src/local_deep_research/search_system/knowledge/base_knowledge.py b/src/local_deep_research/search_system/knowledge/base_knowledge.pynew file mode 100644index 0000000000..32a9b048e6--- /dev/null+++ b/src/local_deep_research/search_system/knowledge/base_knowledge.py@@ -0,0 +1,15 @@+from abc import ABC, abstractmethod+import logging++logger = logging.getLogger(__name__)++class BaseKnowledgeManager(ABC):+ """Base class for knowledge management services."""++ def __init__(self, model):+ self.model = model++ @abstractmethod+ def compress_knowledge(self, current_knowledge: str, query: str, section_links: list, **kwargs) -> str:+ """Compress and summarize accumulated knowledge."""+ passdiff --git a/src/local_deep_research/search_system/knowledge/standard_knowledge.py b/src/local_deep_research/search_system/knowledge/standard_knowledge.pynew file mode 100644index 0000000000..d2181057c6--- /dev/null+++ b/src/local_deep_research/search_system/knowledge/standard_knowledge.py@@ -0,0 +1,30 @@+import logging+from datetime import datetime+from ...utilties.search_utilities import remove_think_tags, format_links+from .base_knowledge import BaseKnowledgeManager++logger = logging.getLogger(__name__)++class StandardKnowledgeManager(BaseKnowledgeManager):+ """Standard knowledge management service."""++ def compress_knowledge(self, current_knowledge: str, query: str, section_links: list, **kwargs) -> str:+ """Compress and summarize accumulated knowledge."""+ logger.info("Compressing and summarizing knowledge...")++ now = datetime.now()+ current_time = now.strftime("%Y-%m-%d")+ formatted_links = format_links(links=section_links)++ prompt = f"""First provide a high-quality 1 page explanation with IEEE Referencing Style e.g. [1,2]. Never make up sources. Than provide a exact high-quality one sentence-long answer to the query.++ Knowledge: {current_knowledge}+ Query: {query}+ I will append following text to your output for the sources (dont repeat it):\n\n {formatted_links}"""++ response = self.model.invoke(prompt)++ logger.info("Knowledge compression complete")+ response = remove_think_tags(response.content)++ return str(response)diff --git a/src/local_deep_research/search_system/questions/__init__.py b/src/local_deep_research/search_system/questions/__init__.pynew file mode 100644index 0000000000..8b049392b8--- /dev/null+++ b/src/local_deep_research/search_system/questions/__init__.py@@ -0,0 +1 @@+# Search System Questions Packagediff --git a/src/local_deep_research/search_system/questions/base_question.py b/src/local_deep_research/search_system/questions/base_question.pynew file mode 100644index 0000000000..46007c1e62--- /dev/null+++ b/src/local_deep_research/search_system/questions/base_question.py@@ -0,0 +1,16 @@+from abc import ABC, abstractmethod+from typing import List, Dict+import logging++logger = logging.getLogger(__name__)++class BaseQuestionGenerator(ABC):+ """Base class for question generation services."""++ def __init__(self, model):+ self.model = model++ @abstractmethod+ def generate_questions(self, current_knowledge: str, query: str, **kwargs) -> List[str]:+ """Generate questions based on current knowledge and query."""+ passdiff --git a/src/local_deep_research/search_system/questions/decomposition_question.py b/src/local_deep_research/search_system/questions/decomposition_question.pynew file mode 100644index 0000000000..8aaf1035ea--- /dev/null+++ b/src/local_deep_research/search_system/questions/decomposition_question.py@@ -0,0 +1,64 @@+from typing import List, Dict+import logging+from ...utilties.search_utilities import remove_think_tags+from .base_question import BaseQuestionGenerator++logger = logging.getLogger(__name__)++class DecompositionQuestionGenerator(BaseQuestionGenerator):+ """Question generator for decomposing complex queries into sub-queries."""++ def generate_questions(self, current_knowledge: str, query: str,+ initial_results: List[Dict] = None, **kwargs) -> List[str]:+ """Generate sub-queries by decomposing the original query."""+ initial_results = initial_results or []++ # Format initial search results as context+ context = ""+ for i, result in enumerate(initial_results[:5]): # Use top 5 results as context+ context += f"Document {i+1}:\n"+ context += f"Title: {result.get('title', 'Untitled')}\n"+ context += f"Content: {result.get('snippet', result.get('content', ''))[:250]}...\n\n"++ # Prompt to decompose the query+ prompt = f"""You are an expert at breaking down complex questions into simpler sub-questions.++Original Question: {query}++Below is some initial context that might be helpful:+{context}++Break down the original question into 2-5 simpler sub-questions that would help answer the original question when answered in sequence.+Follow these guidelines:+1. Each sub-question should be specific and answerable on its own+2. Sub-questions should build towards answering the original question+3. For multi-hop or complex queries, identify the individual facts or entities needed+4. Ensure the sub-questions can be answered with separate searches++Format your response as a numbered list with ONLY the sub-questions, one per line:+1. First sub-question+2. Second sub-question+...++Only provide the numbered sub-questions, nothing else."""++ try:+ response = self.model.invoke(prompt)+ content = remove_think_tags(response.content)++ # Parse sub-queries from the response+ sub_queries = []+ for line in content.strip().split('\n'):+ line = line.strip()+ if line and (line[0].isdigit() or line.startswith('-')):+ # Extract sub-query from numbered or bulleted list+ parts = line.split('.', 1) if '.' in line else line.split(' ', 1)+ if len(parts) > 1:+ sub_query = parts[1].strip()+ sub_queries.append(sub_query)++ # Limit to at most 5 sub-queries+ return sub_queries[:5]+ except Exception as e:+ logger.error(f"Error generating sub-queries: {str(e)}")+ return []diff --git a/src/local_deep_research/search_system/questions/standard_question.py b/src/local_deep_research/search_system/questions/standard_question.pynew file mode 100644index 0000000000..ec6f4858d2--- /dev/null+++ b/src/local_deep_research/search_system/questions/standard_question.py@@ -0,0 +1,42 @@+from typing import List, Dict+import logging+from datetime import datetime+from ...utilties.search_utilities import remove_think_tags+from .base_question import BaseQuestionGenerator++logger = logging.getLogger(__name__)++class StandardQuestionGenerator(BaseQuestionGenerator):+ """Standard follow-up question generator."""++ def generate_questions(self, current_knowledge: str, query: str,+ questions_per_iteration: int = 2,+ questions_by_iteration: dict = None) -> List[str]:+ """Generate follow-up questions based on current knowledge."""+ now = datetime.now()+ current_time = now.strftime("%Y-%m-%d")+ questions_by_iteration = questions_by_iteration or {}++ logger.info("Generating follow-up questions...")++ if questions_by_iteration:+ prompt = f"""Critically reflect current knowledge (e.g., timeliness), what {questions_per_iteration} high-quality internet search questions remain unanswered to exactly answer the query?+ Query: {query}+ Today: {current_time}+ Past questions: {str(questions_by_iteration)}+ Knowledge: {current_knowledge}+ Include questions that critically reflect current knowledge.+ \n\n\nFormat: One question per line, e.g. \n Q: question1 \n Q: question2\n\n"""+ else:+ prompt = f" You will have follow up questions. First, identify if your knowledge is outdated (high chance). Today: {current_time}. Generate {questions_per_iteration} high-quality internet search questions to exactly answer: {query}\n\n\nFormat: One question per line, e.g. \n Q: question1 \n Q: question2\n\n"++ response = self.model.invoke(prompt)+ questions = [+ q.replace("Q:", "").strip()+ for q in remove_think_tags(response.content).split("\n")+ if q.strip().startswith("Q:")+ ][:questions_per_iteration]++ logger.info(f"Generated {len(questions)} follow-up questions")++ return questionsdiff --git a/src/local_deep_research/search_system/repositories/__init__.py b/src/local_deep_research/search_system/repositories/__init__.pynew file mode 100644index 0000000000..07ea4cfe97--- /dev/null+++ b/src/local_deep_research/search_system/repositories/__init__.py@@ -0,0 +1 @@+# Search System Repositories Packagediff --git a/src/local_deep_research/search_system/repositories/findings_repository.py b/src/local_deep_research/search_system/repositories/findings_repository.pynew file mode 100644index 0000000000..a323e39143--- /dev/null+++ b/src/local_deep_research/search_system/repositories/findings_repository.py@@ -0,0 +1,14 @@+from typing import Dict, List+import os+import logging++logger = logging.getLogger(__name__)++class FindingsRepository:+ """Repository for saving and loading research findings."""++ def save_findings(self, findings: List[Dict], current_knowledge: str,+ questions_by_iteration: dict, query: str) -> str:+ """Save research findings and return formatted output."""+ # This will contain the logic from _save_findings+ passdiff --git a/src/local_deep_research/search_system/strategies/__init__.py b/src/local_deep_research/search_system/strategies/__init__.pynew file mode 100644index 0000000000..14960f04b0--- /dev/null+++ b/src/local_deep_research/search_system/strategies/__init__.py@@ -0,0 +1 @@+# Search System Strategies Packagediff --git a/src/local_deep_research/search_system/strategies/base_strategy.py b/src/local_deep_research/search_system/strategies/base_strategy.pynew file mode 100644index 0000000000..e2daff88c9--- /dev/null+++ b/src/local_deep_research/search_system/strategies/base_strategy.py@@ -0,0 +1,10 @@+# Base Strategy Interface++from abc import ABC, abstractmethod+from typing import Dict++class BaseSearchStrategy(ABC):+ @abstractmethod+ def analyze_topic(self, query: str) -> Dict:+ """Analyze a topic and return findings."""+ passdiff --git a/src/local_deep_research/search_system/strategies/iterdrag_strategy.py b/src/local_deep_research/search_system/strategies/iterdrag_strategy.pynew file mode 100644index 0000000000..ae12f9dd81--- /dev/null+++ b/src/local_deep_research/search_system/strategies/iterdrag_strategy.py@@ -0,0 +1,290 @@+# Create iterdrag_strategy.py+from typing import Dict, List, Optional, Callable+import logging++from .base_strategy import BaseSearchStrategy+from ..services.question_service import QuestionService+from ..services.knowledge_service import KnowledgeService+from ..repositories.findings_repository import FindingsRepository+from ...citation_handler import CitationHandler+from ...config import settings, get_llm, get_search+from ...utilties.search_utilities import remove_think_tags, extract_links_from_search_results++logger = logging.getLogger(__name__)++class IterDRAGStrategy(BaseSearchStrategy):+ """IterDRAG strategy that breaks queries into sub-queries."""++ def __init__(self):+ self.search = get_search()+ self.model = get_llm()+ self.citation_handler = CitationHandler(self.model)+ self.progress_callback = None+ self.all_links_of_system = list()++ # Initialize service objects+ self.question_service = QuestionService(self.model)+ self.knowledge_service = KnowledgeService(self.model)+ self.findings_repository = FindingsRepository()++ def set_progress_callback(self, callback: Callable[[str, int, dict], None]) -> None:+ """Set a callback function to receive progress updates."""+ self.progress_callback = callback++ def _update_progress(self, message: str, progress_percent: int = None, metadata: dict = None) -> None:+ """Send a progress update via the callback if available."""+ if self.progress_callback:+ self.progress_callback(message, progress_percent, metadata or {})++ def _generate_subqueries(self, query: str, initial_results: List[Dict]) -> List[str]:+ """Generate sub-queries by decomposing the original query."""+ # Format initial search results as context+ context = ""+ for i, result in enumerate(initial_results[:5]): # Use top 5 results as context+ context += f"Document {i+1}:\n"+ context += f"Title: {result.get('title', 'Untitled')}\n"+ context += f"Content: {result.get('snippet', result.get('content', ''))[:250]}...\n\n"++ # Prompt to decompose the query+ prompt = f"""You are an expert at breaking down complex questions into simpler sub-questions.++Original Question: {query}++Below is some initial context that might be helpful:+{context}++Break down the original question into 2-5 simpler sub-questions that would help answer the original question when answered in sequence.+Follow these guidelines:+1. Each sub-question should be specific and answerable on its own+2. Sub-questions should build towards answering the original question+3. For multi-hop or complex queries, identify the individual facts or entities needed+4. Ensure the sub-questions can be answered with separate searches++Format your response as a numbered list with ONLY the sub-questions, one per line:+1. First sub-question+2. Second sub-question+...++Only provide the numbered sub-questions, nothing else."""++ try:+ response = self.model.invoke(prompt)+ content = remove_think_tags(response.content)++ # Parse sub-queries from the response+ sub_queries = []+ for line in content.strip().split('\n'):+ line = line.strip()+ if line and (line[0].isdigit() or line.startswith('-')):+ # Extract sub-query from numbered or bulleted list+ parts = line.split('.', 1) if '.' in line else line.split(' ', 1)+ if len(parts) > 1:+ sub_query = parts[1].strip()+ sub_queries.append(sub_query)++ # Limit to at most 5 sub-queries+ return sub_queries[:5]+ except Exception as e:+ logger.error(f"Error generating sub-queries: {str(e)}")+ return []++ def _synthesize_final_answer(self, query: str, findings: List[Dict], current_knowledge: str) -> str:+ """Synthesize a final answer based on all findings from sub-queries."""+ # Create a summary of sub-query findings+ sub_query_findings = "\n\n".join([+ f"Sub-query: {finding['question']}\nAnswer: {finding['content']}"+ for finding in findings+ if finding.get('phase', '').startswith('Sub-query')+ ])++ prompt = f"""You need to synthesize a final comprehensive answer to the original question based on the answers to several sub-questions.++Original Question: {query}++Sub-query Results:+{sub_query_findings}++Additional Knowledge:+{current_knowledge[:2000]} # Limit to avoid excessively long prompts++Synthesize a clear, comprehensive answer to the original question that integrates all the information from the sub-queries.+The answer should be coherent, well-structured, and directly address the original question.+Include only information that is relevant to answering the original question.++Answer:"""++ try:+ response = self.model.invoke(prompt)+ final_answer = remove_think_tags(response.content)+ return final_answer+ except Exception as e:+ logger.error(f"Error synthesizing final answer: {str(e)}")+ # Fall back to using the latest finding+ if findings:+ return findings[-1].get("content", "Unable to synthesize final answer")+ return "Unable to synthesize final answer"++ def analyze_topic(self, query: str) -> Dict:+ """IterDRAG implementation of the topic analysis process."""+ findings = []+ current_knowledge = ""+ section_links = list()++ self._update_progress("Initializing IterDRAG research system", 5, {+ "phase": "init",+ "strategy": "iterdrag"+ })++ # Check if search engine is available+ if self.search is None:+ error_msg = "Error: No search engine available. Please check your configuration."+ self._update_progress(error_msg, 100, {+ "phase": "error",+ "error": "No search engine available",+ "status": "failed"+ })+ return {+ "findings": [],+ "iterations": 0,+ "questions": {},+ "formatted_findings": "Error: Unable to conduct research without a search engine.",+ "current_knowledge": "",+ "error": error_msg+ }++ # Initial search for the main query+ self._update_progress(f"Performing initial search for main query", 10,+ {"phase": "search", "iteration": 1})++ 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 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)++ # Generate sub-queries+ self._update_progress("Generating sub-queries for IterDRAG analysis", 20, {"phase": "iterdrag_decomposition"})++ sub_queries = self._generate_subqueries(query, initial_results)++ if not sub_queries:+ # If no sub-queries generated, try to answer directly+ self._update_progress("No sub-queries generated, attempting direct answer", 25, {"phase": "direct_answer"})++ try:+ result = self.citation_handler.analyze_initial(query, initial_results)+ if result is not None:+ findings.append({+ "phase": "Direct answer",+ "content": result["content"],+ "question": query,+ "search_results": initial_results,+ "documents": result["documents"],+ })+ current_knowledge = result["content"]+ except Exception as e:+ logger.error(f"Error during direct answer: {str(e)}")+ else:+ # Process each sub-query+ total_subqueries = len(sub_queries)++ for i, sub_query in enumerate(sub_queries):+ progress_base = 25 + (i / total_subqueries * 50)+ self._update_progress(f"Processing sub-query {i+1} of {total_subqueries}: {sub_query}",+ int(progress_base),+ {"phase": "subquery", "subquery_index": i+1})++ # Search for the sub-query+ try:+ sub_results = self.search.run(sub_query)+ if not sub_results:+ self._update_progress(f"No results for sub-query: {sub_query}",+ int(progress_base + 2),+ {"phase": "search_complete", "result_count": 0})+ sub_results = []+ else:+ self._update_progress(f"Found {len(sub_results)} results for sub-query",+ int(progress_base + 2),+ {"phase": "search_complete", "result_count": len(sub_results)})+ except Exception as e:+ logger.error(f"Error searching for sub-query: {str(e)}")+ sub_results = []++ # Extract and save links+ sub_links = extract_links_from_search_results(sub_results)+ self.all_links_of_system.extend(sub_links)+ section_links.extend(sub_links)++ # Analyze sub-query results+ try:+ # Use previous knowledge to answer this sub-query+ result = self.citation_handler.analyze_followup(+ sub_query, sub_results, current_knowledge, nr_of_links=len(self.all_links_of_system)+ )++ if result is not None:+ findings.append({+ "phase": f"Sub-query {i+1}",+ "content": result["content"],+ "question": sub_query,+ "search_results": sub_results,+ "documents": result["documents"],+ })++ # Add to current knowledge+ if settings.general.knowledge_accumulation != "NONE":+ current_knowledge = current_knowledge + "\n\n\n New: \n" + result["content"]+ except Exception as e:+ logger.error(f"Error analyzing sub-query results: {str(e)}")++ # Final answer synthesis based on all sub-query findings+ self._update_progress("Synthesizing final answer from sub-queries", 80, {"phase": "final_synthesis"})++ try:+ final_answer = self._synthesize_final_answer(query, findings, current_knowledge)++ findings.append({+ "phase": "Final synthesis",+ "content": final_answer,+ "question": query,+ "search_results": [],+ "documents": [],+ })++ current_knowledge = final_answer+ except Exception as e:+ logger.error(f"Error synthesizing final answer: {str(e)}")++ # Compress knowledge if needed+ if settings.general.knowledge_accumulation == "ITERATION":+ try:+ self._update_progress("Compressing knowledge", 90, {"phase": "knowledge_compression"})+ current_knowledge = self.knowledge_service.compress_knowledge(current_knowledge, query, section_links)+ except Exception as e:+ logger.error(f"Error compressing knowledge: {str(e)}")++ # Format and save findings+ self._update_progress("Formatting and saving findings", 95, {"phase": "formatting"})++ try:+ formatted_findings = self.findings_repository.save_findings(findings, current_knowledge, {"0": sub_queries}, query)+ except Exception as e:+ logger.error(f"Error saving findings: {str(e)}")+ formatted_findings = "Error: Could not format findings due to an error."++ self._update_progress("Research complete", 100, {"phase": "complete"})++ return {+ "findings": findings,+ "iterations": 1, # IterDRAG counts as one iteration with multiple steps+ "questions": {"0": sub_queries},+ "formatted_findings": formatted_findings,+ "current_knowledge": current_knowledge+ }\ No newline at end of filediff --git a/src/local_deep_research/search_system/strategies/standard_strategy.py b/src/local_deep_research/search_system/strategies/standard_strategy.pynew file mode 100644index 0000000000..013a8fb58b--- /dev/null+++ b/src/local_deep_research/search_system/strategies/standard_strategy.py@@ -0,0 +1,231 @@+from typing import Dict, List, Optional, Callable+from datetime import datetime+import logging+import os++from .base_strategy import BaseSearchStrategy+from ..services.question_service import QuestionService+from ..services.knowledge_service import KnowledgeService+from ..repositories.findings_repository import FindingsRepository+from ...citation_handler import CitationHandler+from ...config import settings, get_llm, get_search+from ...utilties.search_utilities import extract_links_from_search_results+from ...utilties.enums import KnowledgeAccumulationApproach++logger = logging.getLogger(__name__)++# Update standard_strategy.py with full implementation+from typing import Dict, List, Optional, Callable+from datetime import datetime+import logging+import os++from .base_strategy import BaseSearchStrategy+from ..questions.standard_question import StandardQuestionGenerator+from ..knowledge.standard_knowledge import StandardKnowledgeManager+from ..repositories.findings_repository import FindingsRepository+from ...citation_handler import CitationHandler+from ...config import settings, get_llm, get_search+from ...utilties.search_utilities import extract_links_from_search_results+from ...utilties.enums import KnowledgeAccumulationApproach++logger = logging.getLogger(__name__)++class StandardSearchStrategy(BaseSearchStrategy):+ """Standard iterative search strategy that generates follow-up questions."""++ def __init__(self):+ self.search = get_search()+ self.model = get_llm()+ self.max_iterations = settings.search.iterations+ self.questions_per_iteration = settings.search.questions_per_iteration+ self.context_limit = settings.general.knowledge_accumulation_context_limit+ self.questions_by_iteration = {}+ self.citation_handler = CitationHandler(self.model)+ self.progress_callback = None+ self.all_links_of_system = list()++ # Initialize service objects+ self.question_service = QuestionService(self.model)+ self.knowledge_service = KnowledgeService(self.model)+ self.findings_repository = FindingsRepository()++ def set_progress_callback(self, callback: Callable[[str, int, dict], None]) -> None:+ """Set a callback function to receive progress updates."""+ self.progress_callback = callback++ def _update_progress(self, message: str, progress_percent: int = None, metadata: dict = None) -> None:+ """Send a progress update via the callback if available."""+ if self.progress_callback:+ self.progress_callback(message, progress_percent, metadata or {})++ def analyze_topic(self, query: str) -> Dict:+ """Standard implementation of the topic analysis process."""+ logger.info(f"Starting research on topic: {query}")++ findings = []+ current_knowledge = ""+ iteration = 0+ total_iterations = self.max_iterations+ section_links = list()++ self._update_progress("Initializing research system", 5, {+ "phase": "init",+ "iterations_planned": total_iterations+ })++ # Check if search engine is available+ if self.search is None:+ error_msg = "Error: No search engine available. Please check your configuration."+ self._update_progress(error_msg, 100, {+ "phase": "error",+ "error": "No search engine available",+ "status": "failed"+ })+ return {+ "findings": [],+ "iterations": 0,+ "questions": {},+ "formatted_findings": "Error: Unable to conduct research without a search engine.",+ "current_knowledge": "",+ "error": error_msg+ }++ while iteration < self.max_iterations:+ iteration_progress_base = (iteration / total_iterations) * 100+ self._update_progress(f"Starting iteration {iteration + 1} of {total_iterations}",+ int(iteration_progress_base),+ {"phase": "iteration_start", "iteration": iteration + 1})++ # Generate questions for this iteration using the question service+ questions = self.question_service.get_follow_up_questions(+ current_knowledge, query, self.questions_per_iteration, self.questions_by_iteration)++ self.questions_by_iteration[iteration] = questions+ logger.info(f"Generated questions: {questions}")++ question_count = len(questions)+ for q_idx, question in enumerate(questions):+ question_progress_base = iteration_progress_base + (((q_idx+1) / question_count) * (100/total_iterations) * 0.5)++ self._update_progress(f"Searching for: {question}",+ int(question_progress_base),+ {"phase": "search", "iteration": iteration + 1, "question_index": q_idx + 1})++ try:+ if self.search is None:+ self._update_progress(f"Search engine unavailable, skipping search for: {question}",+ int(question_progress_base + 2),+ {"phase": "search_error", "error": "No search engine available"})+ search_results = []+ else:+ search_results = self.search.run(question)+ except Exception as e:+ error_msg = f"Error during search: {str(e)}"+ logger.info(f"SEARCH ERROR: {error_msg}")+ self._update_progress(error_msg,+ int(question_progress_base + 2),+ {"phase": "search_error", "error": str(e)})+ search_results = []++ if search_results is None:+ self._update_progress(f"No search results found for question: {question}",+ int(question_progress_base + 2),+ {"phase": "search_complete", "result_count": 0})+ search_results = [] # Initialize to empty list instead of None+ continue++ self._update_progress(f"Found {len(search_results)} results for question: {question}",+ int(question_progress_base + 2),+ {"phase": "search_complete", "result_count": len(search_results)})++ logger.info(f"len search: {len(search_results)}")++ if len(search_results) == 0:+ continue++ self._update_progress(f"Analyzing results for: {question}",+ int(question_progress_base + 5),+ {"phase": "analysis"})++ try:+ result = self.citation_handler.analyze_followup(+ question, search_results, current_knowledge, nr_of_links=len(self.all_links_of_system)+ )+ links = extract_links_from_search_results(search_results)+ self.all_links_of_system.extend(links)+ section_links.extend(links)++ if result is not None:+ results_with_links = str(result["content"])+ findings.append(+ {+ "phase": f"Follow-up {iteration}.{questions.index(question) + 1}",+ "content": results_with_links,+ "question": question,+ "search_results": search_results,+ "documents": result["documents"],+ }+ )++ if settings.general.knowledge_accumulation != str(KnowledgeAccumulationApproach.NO_KNOWLEDGE.value):+ current_knowledge = current_knowledge + "\n\n\n New: \n" + results_with_links++ if settings.general.knowledge_accumulation == str(KnowledgeAccumulationApproach.QUESTION.value):+ logger.info("Compressing knowledge")+ self._update_progress(f"Compress Knowledge for: {question}",+ int(question_progress_base + 0),+ {"phase": "analysis"})+ current_knowledge = self.knowledge_service.compress_knowledge(current_knowledge, query, section_links)++ self._update_progress(f"Analysis complete for question: {question}",+ int(question_progress_base + 10),+ {"phase": "analysis_complete"})+ except Exception as e:+ error_msg = f"Error analyzing results: {str(e)}"+ logger.info(f"ANALYSIS ERROR: {error_msg}")+ self._update_progress(error_msg,+ int(question_progress_base + 10),+ {"phase": "analysis_error", "error": str(e)})+ iteration += 1++ self._update_progress(f"Compressing knowledge after iteration {iteration}",+ int((iteration / total_iterations) * 100 - 5),+ {"phase": "knowledge_compression"})++ if settings.general.knowledge_accumulation == KnowledgeAccumulationApproach.ITERATION.value:+ try:+ logger.info("ITERATION - Compressing Knowledge")+ current_knowledge = self.knowledge_service.compress_knowledge(current_knowledge, query, section_links)+ logger.info("FINISHED ITERATION - Compressing Knowledge")+ except Exception as e:+ error_msg = f"Error compressing knowledge: {str(e)}"+ logger.info(f"COMPRESSION ERROR: {error_msg}")+ self._update_progress(error_msg,+ int((iteration / total_iterations) * 100 - 3),+ {"phase": "compression_error", "error": str(e)})++ self._update_progress(f"Iteration {iteration} complete",+ int((iteration / total_iterations) * 100),+ {"phase": "iteration_complete", "iteration": iteration})++ try:+ formatted_findings = self.findings_repository.save_findings(+ findings, current_knowledge, self.questions_by_iteration, query)+ except Exception as e:+ error_msg = f"Error saving findings: {str(e)}"+ logger.info(f"SAVE ERROR: {error_msg}")+ self._update_progress(error_msg,+ int((iteration / total_iterations) * 100),+ {"phase": "save_error", "error": str(e)})+ formatted_findings = "Error: Could not format findings due to an error."++ self._update_progress("Research complete", 95, {"phase": "complete"})++ return {+ "findings": findings,+ "iterations": iteration,+ "questions": self.questions_by_iteration,+ "formatted_findings": formatted_findings,+ "current_knowledge": current_knowledge+ }\ No newline at end of filediff --git a/src/local_deep_research/search_system/tools/__init__.py b/src/local_deep_research/search_system/tools/__init__.pynew file mode 100644index 0000000000..8bdf9c60a1--- /dev/null+++ b/src/local_deep_research/search_system/tools/__init__.py@@ -0,0 +1 @@+# Search System Tools Package