~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
quick summary working
LearningCircuit0a5fe043bd4b
diff --git a/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py b/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.pyindex 6e4dbef9ba..6eb0940a64 100644--- a/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py@@ -146,8 +146,9 @@ Initial Search Results:query, initial_results, current_knowledge)- # Store questions in repository- self.findings_repository.set_questions_by_iteration({0: sub_queries})+ # Store questions in repository and in self.questions_by_iteration+ self.questions_by_iteration = {0: sub_queries}+ self.findings_repository.set_questions_by_iteration(self.questions_by_iteration)if not sub_queries:logger.error("No sub-queries were generated to analyze.")@@ -304,6 +305,11 @@ Initial Search Results:)final_answer = current_knowledge+ # Ensure latest questions are in the repository+ self.findings_repository.set_questions_by_iteration(+ self.questions_by_iteration+ )+# Now format the findings with search questions and sourcesformatted_findings = self.findings_repository.format_findings_to_text(findings, final_answerdiff --git a/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py b/src/local_deep_research/advanced_search_system/strategies/standard_strategy.pyindex 1bbb4f3f2d..09c0ee5af2 100644--- a/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py@@ -280,6 +280,11 @@ class StandardSearchStrategy(BaseSearchStrategy):old_formatting=False, # Don't format here, just synthesize content)+ # Transfer questions to the repository+ self.findings_repository.set_questions_by_iteration(+ self.questions_by_iteration+ )+# Now format the findings with search questions and sourcesformatted_findings = self.findings_repository.format_findings_to_text(findings, synthesized_contentdiff --git a/src/local_deep_research/report_generator.py b/src/local_deep_research/report_generator.pyindex c16d69d3ce..8399034ce4 100644--- a/src/local_deep_research/report_generator.py+++ b/src/local_deep_research/report_generator.py@@ -1,72 +1,220 @@-"""-Report generator module for Local Deep Research.-"""--import logging-from typing import Dict, Optional+import importlib+from typing import Dict, List+# Fix circular import by importing directly from source modules+from .config.llm_config import get_llmfrom .search_system import AdvancedSearchSystem-from .utilties.search_utilities import format_findings-logger = logging.getLogger(__name__)+# from . import utilties+from .utilties import search_utilitiesclass IntegratedReportGenerator:- """Integrated report generator that uses the search system."""-- def __init__(self, search_system: Optional[AdvancedSearchSystem] = None):- """- Initialize the report generator.-- Args:- search_system: Optional search system instance to use+ def __init__(self, searches_per_section: int = 2):+ self.model = get_llm()+ self.search_system = AdvancedSearchSystem()+ self.searches_per_section = (+ searches_per_section # Control search depth per section+ )++ def generate_report(self, initial_findings: Dict, query: str) -> Dict:+ """Generate a complete research report with section-specific research."""++ # Step 1: Determine structure+ structure = self._determine_report_structure(initial_findings, query)++ # Step 2: Research and generate content for each section in one step+ sections = self._research_and_generate_sections(+ initial_findings, structure, query+ )++ # Step 3: Format final report+ report = self._format_final_report(sections, structure, query)++ return report++ def _determine_report_structure(self, findings: Dict, query: str) -> List[Dict]:+ """Analyze content and determine optimal report structure."""+ combined_content = findings["current_knowledge"]+ prompt = f"""+ Analyze this research content about: {query}++ Content Summary:+ {combined_content[:1000]}... [truncated]++ Determine the most appropriate report structure by:+ 1. Analyzing the type of content (technical, business, academic, etc.)+ 2. Identifying main themes and logical groupings+ 3. Considering the depth and breadth of the research++ Return a table of contents structure in this exact format:+ STRUCTURE+ 1. [Section Name]+ - [Subsection] | [purpose]+ 2. [Section Name]+ - [Subsection] | [purpose]+ ...+ END_STRUCTURE++ Make the structure specific to the content, not generic.+ Each subsection must include its purpose after the | symbol."""- self.search_system = search_system or AdvancedSearchSystem()- def generate_report(self, results: Dict, query: str) -> Dict:+ response = search_utilities.remove_think_tags(self.model.invoke(prompt).content)++ # Parse the structure+ structure = []+ current_section = None++ for line in response.split("\n"):+ if line.strip() in ["STRUCTURE", "END_STRUCTURE"]:+ continue++ if line.strip().startswith(tuple("123456789")):+ # Main section+ section_name = line.split(".")[1].strip()+ current_section = {"name": section_name, "subsections": []}+ structure.append(current_section)+ elif line.strip().startswith("-") and current_section:+ # Subsection with purpose+ parts = line.strip("- ").split("|")+ if len(parts) == 2:+ current_section["subsections"].append(+ {"name": parts[0].strip(), "purpose": parts[1].strip()}+ )++ return structure++ def _research_and_generate_sections(+ self,+ initial_findings: Dict,+ structure: List[Dict],+ query: str,+ ) -> Dict[str, str]:+ """Research and generate content for each section in one step."""+ sections = {}++ for section in structure:+ print(f"Processing section: {section['name']}")+ section_content = []+ section_content.append(f"# {section['name']}\n")++ # Process each subsection by directly researching it+ for subsection in section["subsections"]:+ # Add subsection header+ section_content.append(f"## {subsection['name']}\n")+ section_content.append(f"_{subsection['purpose']}_\n\n")++ # Generate a specific search query for this subsection+ subsection_query = f"{query} {section['name']} {subsection['name']} {subsection['purpose']}"++ print(+ f"Researching subsection: {subsection['name']} with query: {subsection_query}"+ )++ # Configure search system for focused search+ original_max_iterations = self.search_system.max_iterations+ self.search_system.max_iterations = 1 # Keep search focused++ # Perform search for this subsection+ subsection_results = self.search_system.analyze_topic(subsection_query)++ # Restore original iterations setting+ self.search_system.max_iterations = original_max_iterations++ # Add the researched content for this subsection+ if (+ "current_knowledge" in subsection_results+ and subsection_results["current_knowledge"]+ ):+ section_content.append(subsection_results["current_knowledge"])+ else:+ section_content.append(+ "*Limited information was found for this subsection.*\n"+ )++ section_content.append("\n\n")++ # Combine all content for this section+ sections[section["name"]] = "\n".join(section_content)++ return sections++ def _generate_sections(+ self,+ initial_findings: Dict,+ section_research: Dict[str, List[Dict]],+ structure: List[Dict],+ query: str,+ ) -> Dict[str, str]:"""- Generate a report from research results.-- Args:- results: The research results from the search system- query: The original research query-- Returns:- Dict: The generated report with content and metadata+ This method is kept for compatibility but no longer used.+ The functionality has been moved to _research_and_generate_sections."""- try:- # Format the findings using the utility function- formatted_content = format_findings(- results.get("findings", []),- results.get("formatted_findings", ""),- results.get("questions", {}),- )-- return {- "content": formatted_content,- "metadata": {- "query": query,- "iterations": results.get("iterations", 0),- "generated_at": results.get("generated_at", ""),- "mode": "detailed",- },- }- except Exception as e:- logger.error(f"Error generating report: {str(e)}")- return {- "content": f"Error generating report: {str(e)}",- "metadata": {"query": query, "error": str(e)},- }---def get_report_generator(*args, **kwargs) -> IntegratedReportGenerator:- """- Get a report generator instance.-- Returns:- IntegratedReportGenerator: A report generator instance- """- return IntegratedReportGenerator(*args, **kwargs)---__all__ = ["IntegratedReportGenerator", "get_report_generator"]+ return {}++ def _format_final_report(+ self,+ sections: Dict[str, str],+ structure: List[Dict],+ query: str,+ ) -> Dict:+ """Format the final report with table of contents and sections."""+ # Generate TOC+ toc = ["# Table of Contents\n"]+ for i, section in enumerate(structure, 1):+ toc.append(f"{i}. **{section['name']}**")+ for j, subsection in enumerate(section["subsections"], 1):+ toc.append(+ f" {i}.{j} {subsection['name']} | _{subsection['purpose']}_"+ )++ # Combine TOC and sections+ report_parts = ["\n".join(toc), ""]++ # Add a summary of the research+ report_parts.append("# Research Summary")+ report_parts.append(+ "This report was researched using an advanced search system."+ )+ report_parts.append(+ "Research included targeted searches for each section and subsection."+ )+ report_parts.append("\n---\n")++ # Add each section's content+ for section in structure:+ if section["name"] in sections:+ report_parts.append(sections[section["name"]])+ report_parts.append("")++ # Format links from search system+ # Get utilties module dynamically to avoid circular imports+ utilties = importlib.import_module("local_deep_research.utilties")+ formatted_all_links = utilties.search_utilities.format_links(+ links=self.search_system.all_links_of_system+ )++ # Create final report with all parts+ final_report_content = "\n\n".join(report_parts)+ final_report_content = (+ final_report_content + "\n\n## Sources\n\n" + formatted_all_links+ )++ # Create metadata dictionary+ from datetime import datetime++ metadata = {+ "generated_at": datetime.utcnow().isoformat(),+ "initial_sources": len(self.search_system.all_links_of_system),+ "sections_researched": len(structure),+ "searches_per_section": self.searches_per_section,+ "query": query,+ }++ # Return both content and metadata+ return {"content": final_report_content, "metadata": metadata}++ def _generate_error_report(self, query: str, error_msg: str) -> str:+ error_report = f"=== ERROR REPORT ===\nQuery: {query}\nError: {error_msg}"+ return error_reportdiff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.pyindex bbc8027a77..b5bcc36045 100644--- a/src/local_deep_research/search_system.py+++ b/src/local_deep_research/search_system.py@@ -12,7 +12,7 @@ logger = logging.getLogger(__name__)class AdvancedSearchSystem:- def __init__(self, strategy_name: str = "iterdrag"):+ def __init__(self, strategy_name: str = "standard"):"""Initialize the advanced search system.diff --git a/src/local_deep_research/utilties/search_utilities.py b/src/local_deep_research/utilties/search_utilities.pyindex 023c03fb07..90b4e0ffce 100644--- a/src/local_deep_research/utilties/search_utilities.py+++ b/src/local_deep_research/utilties/search_utilities.py@@ -35,18 +35,14 @@ def extract_links_from_search_results(search_results: List[Dict]) -> List[Dict]:def format_links(links: List[Dict]) -> str:- formatted_links = ""- formatted_links += "SOURCES:\n"- for i, link in enumerate(links, 1):- formatted_links += f"{link['index']}. {link['title']}\n URL: {link['url']}\n"- formatted_links += "\n"+ formatted_links = format_links_to_markdown(links)return formatted_linksdef format_links_to_markdown(all_links: List[Dict]) -> str:formatted_text = ""if all_links:- formatted_text += "## SOURCES:\n"+# Group links by URL and collect all their indicesurl_to_indices = {}for link in all_links:@@ -64,7 +60,7 @@ def format_links_to_markdown(all_links: List[Dict]) -> str:title = link.get("title", "Untitled")if url and url not in seen_urls:# Get all indices for this URL- indices = url_to_indices[url]+ indices = set(url_to_indices[url])# Format as [1, 3, 5] if multiple indices, or just [1] if singleindices_str = f"[{', '.join(map(str, indices))}]"formatted_text += f"{indices_str} {title}\n URL: {url}\n\n"@@ -116,10 +112,10 @@ def format_findings(# Add Search Questions by Iteration sectionif questions_by_iteration:- formatted_text += "## SEARCH QUESTIONS BY ITERATION:\n"+ formatted_text += "## SEARCH QUESTIONS BY ITERATION\n"formatted_text += "\n"for iter_num, questions in questions_by_iteration.items():- formatted_text += f"\nIteration {iter_num}:\n"+ formatted_text += f"\n #### Iteration {iter_num}:\n"for i, q in enumerate(questions, 1):formatted_text += f"{i}. {q}\n"formatted_text += "\n" + "\n\n"@@ -128,7 +124,7 @@ def format_findings(# Add Detailed Findings sectionif findings_list:- formatted_text += "## DETAILED FINDINGS:\n\n"+ formatted_text += "## DETAILED FINDINGS\n\n"logger.info(f"Formatting {len(findings_list)} detailed finding items.")for idx, finding in enumerate(findings_list):@@ -220,6 +216,7 @@ def format_findings(# Add summary of all sources at the endif all_links:+ formatted_text += "## ALL SOURCES:\n"formatted_text += format_links_to_markdown(all_links)else:logger.info("No unique sources found across all findings to list.")diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 140821f169..0ac9d40c8b 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -409,25 +409,6 @@ def run_research_process(f"Error processing search results/links: {link_err}")- # Format a sources section if we have links- sources_section = ""- if all_links:- sources_section = "\n\nSOURCES:\n" + "=" * 80 + "\n\n"- seen_urls = set()- link_counter = 1- for link in all_links:- url = link.get("url")- title = link.get("title", "Untitled")- if url and url not in seen_urls:- sources_section += (- f"[{link_counter}] {title}\n URL: {url}\n\n"- )- seen_urls.add(url)- link_counter += 1-- # Add sources section to the markdown- clean_markdown = clean_markdown + sources_section-logger.info(f"Successfully converted to clean markdown of length: {len(clean_markdown)}")