~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
Merge branch 'dev' into advanced-search-structure
LearningCircuit0392426595b2
diff --cc src/local_deep_research/search_system.pyindex 0baa0ca541,170041b567..fa1964fb7b--- a/src/local_deep_research/search_system.py+++ b/src/local_deep_research/search_system.py@@@ -25,50 -30,370 +25,52 @@@ class AdvancedSearchSystemself.max_iterations = settings.search.iterationsself.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()-- # Log the specific model and search engine for debugging- model_name = getattr(settings.llm, "model", "unknown")- search_tool = getattr(settings.search, "tool", "unknown")- logger.info(f"AdvancedSearchSystem initialized with LLM model: {model_name}")-- # Get search engine type for better logging- search_engine_type = "None"- if self.search is not None:- search_engine_type = type(self.search).__name__-+ # Log the strategy name that's being usedlogger.info(- f"AdvancedSearchSystem using search engine: {search_tool} (Type: {search_engine_type})"+ f"Initializing AdvancedSearchSystem with strategy_name='{strategy_name}'")- # Check if search is available, log warning if not- if self.search is None:- logger.info(- "WARNING: Search system initialized with no search engine! Research will not be effective."- )- self._update_progress(- "WARNING: No search engine available",- None,- {"error": "No search engine configured properly"},- )-- def set_progress_callback(self, callback: Callable[[str, int, dict], None]) -> None:- """Set a callback function to receive progress updates.-- Args:- callback: Function that takes (message, progress_percent, metadata)- """- 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.-- Args:- message: Description of the current progress state- progress_percent: Progress percentage (0-100), if applicable- metadata: Additional data about the progress state- """- if self.progress_callback:- self.progress_callback(message, progress_percent, metadata or {})-- def _get_follow_up_questions(self, current_knowledge: str, query: str) -> List[str]:- now = datetime.now()- current_time = now.strftime("%Y-%m-%d")-- self._update_progress(- "Generating follow-up questions...",- None,- {"iteration": len(self.questions_by_iteration)},- )-- if self.questions_by_iteration:- prompt = f"""Critically reflect current knowledge (e.g., timeliness), what {self.questions_per_iteration} high-quality internet search questions remain unanswered to exactly answer the query?- Query: {query}- Today: {current_time}- Past questions: {str(self.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"""+ # Initialize strategy based on name+ if strategy_name.lower() == "iterdrag":+ logger.info("Creating IterDRAGStrategy instance")+ self.strategy = IterDRAGStrategy(model=self.model, search=self.search)else:- prompt = f" You will have follow up questions. First, identify if your knowledge is outdated (high chance). Today: {current_time}. Generate {self.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:")- ][: self.questions_per_iteration]-- self._update_progress(- f"Generated {len(questions)} follow-up questions",- None,- {"questions": questions},- )-- return questions+ logger.info("Creating StandardSearchStrategy instance")+ self.strategy = StandardSearchStrategy(model=self.model, search=self.search)- def _compress_knowledge(- self, current_knowledge: str, query: str, section_links- ) -> List[str]:- self._update_progress("Compressing and summarizing knowledge...", None)+ # Log the actual strategy class+ logger.info(f"Created strategy of type: {type(self.strategy).__name__}")- formatted_links = format_links(links=section_links)- if self.questions_by_iteration:- 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)+ # For backward compatibility+ self.questions_by_iteration = {}+ self.progress_callback = None+ self.all_links_of_system = list()- self._update_progress("Knowledge compression complete", None)- response = remove_think_tags(response.content)- response = str(response) # + "\n\n" + str(formatted_links)+ # Configure the strategy with our attributes+ if hasattr(self, "progress_callback") and self.progress_callback:+ self.strategy.set_progress_callback(self.progress_callback)- return response+ def set_progress_callback(self, callback: Callable[[str, int, dict], None]) -> None:+ """Set a callback function to receive progress updates."""+ self.progress_callback = callback+ if hasattr(self, "strategy"):+ self.strategy.set_progress_callback(callback)def analyze_topic(self, query: str) -> Dict:- logger.info("Starting research on topic: %s", 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- questions = self._get_follow_up_questions(current_knowledge, query)- 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)},- )+ """Analyze a topic using the current strategy."""+ # Use the strategy to analyze the topic+ result = self.strategy.analyze_topic(query)- 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)- formatted_links = ""- if links:- formatted_links = format_links(links=links)-- logger.info(f"Generated questions: {formatted_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._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"},- )- logger.info(str(iteration))- logger.info(settings.general.knowledge_accumulation)- logger.info(str(KnowledgeAccumulationApproach.ITERATION.value))- if (- settings.general.knowledge_accumulation- == KnowledgeAccumulationApproach.ITERATION.value- ):- try:- logger.info("ITERATION - Compressing Knowledge")- current_knowledge = self._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._save_findings(- findings, current_knowledge, 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,- }-- def _save_findings(self, findings: List[Dict], current_knowledge: str, query: str):- logger.info("Saving findings ...")- self._update_progress("Saving research findings...", None)-- formatted_findings = format_findings_to_text(- findings, current_knowledge, self.questions_by_iteration- )- safe_query = "".join(x for x in query if x.isalnum() or x in [" ", "-", "_"])[- :50- ]- safe_query = safe_query.replace(" ", "_").lower()+ # Update our attributes for backward compatibility+ if hasattr(self.strategy, "questions_by_iteration"):+ self.questions_by_iteration = self.strategy.questions_by_iteration- output_dir = f"{get_config_dir()}/research_outputs"- if not os.path.exists(output_dir):- os.makedirs(output_dir)+ if hasattr(self.strategy, "all_links_of_system"):+ self.all_links_of_system = self.strategy.all_links_of_system- filename = os.path.join(output_dir, f"formatted_output_{safe_query}.txt")+ # Include the search system instance for access to citations+ result["search_system"] = self- with open(filename, "w", encoding="utf-8") as text_file:- text_file.write(formatted_findings)- logger.info("Saved findings")- self._update_progress("Research findings saved", None, {"filename": filename})- return formatted_findings+ return resultdiff --cc src/local_deep_research/web/services/research_service.pyindex ac070919a9,15e1880622..43ebb5441c--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@@ -5,16 -5,7 +5,18 @@@ import threadinimport tracebackfrom datetime import datetime+++from ...config.config_files import settings+from ...config.llm_config import get_llm+from ...config.search_config import get_search+from ...report_generator import IntegratedReportGenerator+from ...search_system import AdvancedSearchSystem+from ...utilties.search_utilities import (+ extract_links_from_search_results,+)++from ..models.database import add_log_to_db, calculate_duration, get_db_connection+from .socket_service import emit_to_subscribers # Keep if needed directly# Initialize loggerlogger = logging.getLogger(__name__)@@@ -245,24 -245,63 +261,64 @@@ def run_research_processsystem.set_progress_callback(progress_callback)# Configure the system with the specified parameters- if model or search_engine:+ if model or search_engine or model_provider:# Log that we're overriding system settingslogger.info(- f"Overriding system settings with: model={model}, search_engine={search_engine}"+ f"Overriding system settings with: provider={model_provider}, model={model}, search_engine={search_engine}")- # Override LLM if specified- if model:+++ # Import configuration modules+ from ...config.config_files import settings+ from ...config.llm_config import get_llm+ from ...config.search_config import get_search++ # Override LLM if model or model_provider specified+ if model or model_provider:try:- # Temporarily override the model setting+ # Temporarily override settingsoriginal_model = settings.llm.model- settings.llm.model = model+ original_provider = settings.llm.provider++ # Set model if provided+ if model:+ settings.llm.model = model++ # Set provider if provided+ if model_provider:+ settings.llm.provider = model_provider++ # Set custom endpoint if provided for OpenAI endpoint provider+ original_endpoint = None+ if custom_endpoint and model_provider == "OPENAI_ENDPOINT":+ if hasattr(settings.llm, "openai_endpoint_url"):+ original_endpoint = getattr(+ settings.llm, "openai_endpoint_url", None+ )+ settings.llm.openai_endpoint_url = custom_endpoint++ # Get LLM with the overridden settingssystem.model = get_llm()- # Restore original setting++ # Restore original settingssettings.llm.model = original_model- logger.info(f"Successfully set LLM to: {model}")+ settings.llm.provider = original_provider+ if original_endpoint is not None:+ settings.llm.openai_endpoint_url = original_endpoint++ logger.info(+ "Successfully set LLM to: provider=%s, model=%s",+ model_provider,+ model,+ )except Exception as e:- logger.error(f"Error setting LLM model to {model}: {str(e)}")+ logger.error(+ "Error setting LLM provider=%s, model=%s: %s",+ model_provider,+ model,+ str(e),+ )+ logger.error(traceback.format_exc())# Override search engine if specifiedif search_engine:@@@ -360,57 -411,16 +428,59 @@@# Quick Summaryif results.get("findings") or results.get("formatted_findings"):raw_formatted_findings = results["formatted_findings"]++ # Check if formatted_findings contains an error message+ if isinstance(+ raw_formatted_findings, str+ ) and raw_formatted_findings.startswith("Error:"):+ # Extract synthesized content from findings if available+ synthesized_content = ""+ for finding in results.get("findings", []):+ if finding.get("phase") == "Final synthesis":+ synthesized_content = finding.get("content", "")+ break++ # Use synthesized content as fallback+ if synthesized_content:+ raw_formatted_findings = synthesized_content+ # Or use current_knowledge as another fallback+ elif results.get("current_knowledge"):+ raw_formatted_findings = results["current_knowledge"]+ # Or combine all finding contents as last resort+ elif results.get("findings"):+ raw_formatted_findings = "\n\n".join(+ f"## {finding.get('phase', 'Finding')}\n\n{finding.get('content', '')}"+ for finding in results.get("findings", [])+ if finding.get("content")+ )+logger.info(- f"Found formatted_findings of length: {len(str(raw_formatted_findings))}"+ "Found formatted_findings of length: %s",+ len(str(raw_formatted_findings)),)try:+ # Get the synthesized content from the LLM directlyclean_markdown = raw_formatted_findings++ # Extract all sources from findings to add them to the summary+ all_links = []+ for finding in results.get("findings", []):+ search_results = finding.get("search_results", [])+ if search_results:+ try:+ links = extract_links_from_search_results(+ search_results+ )+ all_links.extend(links)+ except Exception as link_err:+ logger.error(+ f"Error processing search results/links: {link_err}"+ )+logger.info(- f"Successfully converted to clean markdown of length: {len(clean_markdown)}"+ "Successfully converted to clean markdown of length: %s",+ len(clean_markdown),)# First send a progress update for generating the summary@@@ -743,9 -755,13 +815,11 @@@ def cleanup_research_resources(research}logger.info(- f"Sending final {current_status} socket message for research {research_id}"+ "Sending final %s socket message for research %s",+ current_status,+ research_id,)- from ..services.socket_service import emit_to_subscribers-emit_to_subscribers("research_progress", research_id, final_message)except Exception as e: