Skip to content

~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.

working on advanced search system

LearningCircuit58850602e065
diff --git a/src/local_deep_research/__init__.py b/src/local_deep_research/__init__.py
index 80d922c0f0..7a77a4d544 100644
--- a/src/local_deep_research/__init__.py
+++ b/src/local_deep_research/__init__.py
@@ -1,74 +1,34 @@
"""
-Local Deep Research - AI-powered research assistant
-
-A powerful AI research system with iterative analysis capabilities
-and multiple search engines integration.
+Local Deep Research - A tool for conducting deep research using AI.
"""
__version__ = "0.1.0"
+__author__ = "Your Name"
+__description__ = "A tool for conducting deep research using AI"
-# Initialize configuration on module import
-from .utilties.setup_utils import setup_user_directories
-
-
-# Create reexport functions to avoid circular imports
-def get_llm(*args, **kwargs):
- """Get a language model instance based on settings."""
- from .config.llm_config import get_llm as _get_llm
-
- return _get_llm(*args, **kwargs)
-
-
-def get_search(*args, **kwargs):
- """Get a search engine instance based on settings."""
- from .config.search_config import get_search as _get_search
-
- return _get_search(*args, **kwargs)
+from .config.llm_config import get_llm
+from .config.search_config import get_search
+from .report_generator import get_report_generator
-def get_report_generator(*args, **kwargs):
- """Get a report generator instance."""
- from .report_generator import IntegratedReportGenerator
+def get_advanced_search_system(strategy_name: str = "iterdrag"):
+ """
+ Get an instance of the advanced search system.
- return IntegratedReportGenerator(*args, **kwargs)
+ Args:
+ strategy_name: The name of the search strategy to use ("standard" or "iterdrag")
-
-# Define a function to import AdvancedSearchSystem to avoid circular imports
-def get_advanced_search_system(*args, **kwargs):
- """Get an AdvancedSearchSystem instance."""
+ Returns:
+ AdvancedSearchSystem: An instance of the advanced search system
+ """
from .search_system import AdvancedSearchSystem
- return AdvancedSearchSystem(*args, **kwargs)
-
-
-# Lazy import API functions to avoid circular imports
-def _import_api():
- from .api import (
- analyze_documents,
- generate_report,
- get_available_collections,
- get_available_search_engines,
- quick_summary,
- )
-
- return {
- "analyze_documents": analyze_documents,
- "generate_report": generate_report,
- "get_available_collections": get_available_collections,
- "get_available_search_engines": get_available_search_engines,
- "quick_summary": quick_summary,
- }
+ return AdvancedSearchSystem(strategy_name=strategy_name)
-# Export it
__all__ = [
- "get_advanced_search_system",
"get_llm",
"get_search",
"get_report_generator",
+ "get_advanced_search_system",
]
-
-# Add API functions to __all__ dynamically
-for name, func in _import_api().items():
- globals()[name] = func
- __all__.append(name)
diff --git a/src/local_deep_research/advanced_search_system/__init__.py b/src/local_deep_research/advanced_search_system/__init__.py
new file mode 100644
index 0000000000..d19ab15a3f
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/__init__.py
@@ -0,0 +1,4 @@
+# Search System Package
+# AdvancedSearchSystem is now in search_system.py
+
+__all__ = []
diff --git a/src/local_deep_research/advanced_search_system/findings/base_findings.py b/src/local_deep_research/advanced_search_system/findings/base_findings.py
new file mode 100644
index 0000000000..d7d821188e
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/findings/base_findings.py
@@ -0,0 +1,75 @@
+"""
+Base class for all findings repositories.
+Defines the common interface and shared functionality for different findings management approaches.
+"""
+
+import logging
+from abc import ABC, abstractmethod
+from typing import Dict, List
+
+logger = logging.getLogger(__name__)
+
+
+class BaseFindingsRepository(ABC):
+ """Abstract base class for all findings repositories."""
+
+ def __init__(self, model):
+ """
+ Initialize the findings repository.
+
+ Args:
+ model: The language model to use for findings operations
+ """
+ self.model = model
+ self.findings: Dict[str, List[str]] = {}
+
+ @abstractmethod
+ def add_finding(self, query: str, finding: str) -> None:
+ """
+ Add a finding to the repository.
+
+ Args:
+ query: The query associated with the finding
+ finding: The finding to add
+ """
+ pass
+
+ @abstractmethod
+ def get_findings(self, query: str) -> List[str]:
+ """
+ Get findings for a query.
+
+ Args:
+ query: The query to get findings for
+
+ Returns:
+ List[str]: List of findings for the query
+ """
+ pass
+
+ @abstractmethod
+ def clear_findings(self, query: str) -> None:
+ """
+ Clear findings for a query.
+
+ Args:
+ query: The query to clear findings for
+ """
+ pass
+
+ @abstractmethod
+ def synthesize_findings(
+ self, query: str, sub_queries: List[str], findings: List[str]
+ ) -> str:
+ """
+ Synthesize findings from sub-queries into a final answer.
+
+ Args:
+ query: The original query
+ sub_queries: List of sub-queries
+ findings: List of findings for each sub-query
+
+ Returns:
+ str: Synthesized final answer
+ """
+ pass
diff --git a/src/local_deep_research/advanced_search_system/findings/repository.py b/src/local_deep_research/advanced_search_system/findings/repository.py
new file mode 100644
index 0000000000..ea53a60b13
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/findings/repository.py
@@ -0,0 +1,228 @@
+"""
+Findings repository for managing research findings.
+"""
+
+import logging
+from typing import Dict, List
+
+from langchain_core.documents import Document
+
+from ...utilties.search_utilities import (
+ format_findings,
+ remove_think_tags,
+)
+from .base_findings import BaseFindingsRepository
+
+logger = logging.getLogger(__name__)
+
+
+def format_links(links: List[Dict]) -> str:
+ """Format a list of links into a readable string.
+
+ Args:
+ links: List of dictionaries containing 'title' and 'url' keys
+
+ Returns:
+ str: Formatted string of links
+ """
+ return "\n".join(
+ f"{i + 1}. {link['title']}\n URL: {link['url']}"
+ for i, link in enumerate(links)
+ )
+
+
+class FindingsRepository(BaseFindingsRepository):
+ """Repository for managing research findings."""
+
+ def __init__(self, model):
+ """Initialize the repository.
+
+ Args:
+ model: The LLM model to use for synthesis
+ """
+ super().__init__(model)
+ self.findings: Dict[str, List[Dict]] = {}
+ self.documents: List[Document] = []
+ self.questions_by_iteration: Dict[int, List[str]] = {}
+
+ def add_finding(self, query: str, finding: Dict) -> None:
+ """Add a finding for a query."""
+ if query not in self.findings:
+ self.findings[query] = []
+ self.findings[query].append(finding)
+ logger.info(
+ f"Added finding for query: {query}. Total findings: {len(self.findings[query])}"
+ )
+
+ # Store raw synthesized content if it's the final synthesis
+ # Check if the phase indicates final synthesis (adjust key if needed)
+ if finding.get("phase") == "Final synthesis":
+ self.add_finding(query + "_synthesis", finding.get("content", ""))
+
+ def get_findings(self, query: str) -> List[Dict]:
+ """Get findings for a query.
+
+ Args:
+ query: The query to get findings for
+
+ Returns:
+ List of findings for the query
+ """
+ return self.findings.get(query, [])
+
+ def clear_findings(self, query: str) -> None:
+ """Clear findings for a query.
+
+ Args:
+ query: The query to clear findings for
+ """
+ if query in self.findings:
+ del self.findings[query]
+ logger.info(f"Cleared findings for query: {query}")
+
+ def add_documents(self, documents: List[Document]) -> None:
+ """Add documents to the repository.
+
+ Args:
+ documents: List of documents to add
+ """
+ self.documents.extend(documents)
+ logger.info(f"Added {len(documents)} documents to repository")
+
+ def set_questions_by_iteration(
+ self, questions_by_iteration: Dict[int, List[str]]
+ ) -> None:
+ """Set the questions by iteration.
+
+ Args:
+ questions_by_iteration: Dictionary mapping iteration numbers to lists of questions
+ """
+ self.questions_by_iteration = questions_by_iteration
+ logger.info(f"Set questions for {len(questions_by_iteration)} iterations")
+
+ def format_findings_to_text(
+ self, findings_list: List[Dict], synthesized_content: str
+ ) -> str:
+ """Format findings into a detailed text output using the utility function.
+
+ Args:
+ findings_list: List of finding dictionaries from the strategy execution.
+ synthesized_content: The final synthesized content generated by the LLM.
+
+ Returns:
+ str: Formatted text output.
+ """
+ logger.info(
+ f"Formatting final report. Number of detailed findings: {len(findings_list)}. Synthesized content length: {len(synthesized_content)}. Number of question iterations: {len(self.questions_by_iteration)}"
+ )
+ # Log details about the inputs
+ logger.debug(
+ f"Detailed findings list structure (first item type if exists): {type(findings_list[0]) if findings_list else 'Empty'}"
+ )
+ logger.debug(
+ f"Questions by iteration keys: {list(self.questions_by_iteration.keys())}"
+ )
+ if findings_list:
+ logger.debug(f"First finding item keys: {list(findings_list[0].keys())}")
+
+ try:
+ # Pass the detailed findings list, the synthesized content (as current_knowledge), and the stored questions
+ formatted_report = format_findings(
+ findings_list,
+ synthesized_content, # This goes to the 'current_knowledge' param in format_findings
+ self.questions_by_iteration,
+ )
+ logger.info("Successfully formatted final report.")
+ return formatted_report
+ except Exception as e:
+ logger.error(
+ f"Error occurred during final report formatting: {str(e)}",
+ exc_info=True,
+ )
+ # Fallback: return just the synthesized content if formatting fails
+ return f"Error during final formatting. Raw Synthesized Content:\n\n{synthesized_content}"
+
+ def synthesize_findings(
+ self, query: str, sub_queries: List[str], current_knowledge: str
+ ) -> str:
+ """
+ Synthesize accumulated knowledge into a final answer.
+
+ Args:
+ query: The original query
+ sub_queries: List of sub-queries (for context, might be removed later if not needed)
+ current_knowledge: The accumulated knowledge string from previous steps.
+
+ Returns:
+ str: Synthesized final answer content.
+ """
+ try:
+ prompt = f"""Synthesize the following accumulated knowledge into a comprehensive answer for the original query.
+Format the response with clear sections, citations, and a one-sentence summary, following the structure provided below.
+
+Original Query: {query}
+
+Accumulated Knowledge:
+{current_knowledge}
+
+Sub-questions asked (for context):
+{chr(10).join(f"- {sq}" for sq in sub_queries)}
+
+Generate a well-structured answer that:
+1. Starts with a clear explanation section
+2. Organizes information into logical sections with headers
+3. Includes citations using [1], [2], etc. for all claims (referencing sources implicitly within the knowledge)
+4. Maintains logical flow and coherence
+5. Highlights key insights and conclusions
+6. Addresses any contradictions or uncertainties found in the knowledge
+7. Ends with a one-sentence summary
+
+Format your response strictly as:
+**Explanation:**
+[Your explanation with citations]
+
+**Section 1:**
+[Content with citations]
+
+**Section 2:**
+[Content with citations]
+
+...
+
+**Conclusion:**
+[Your conclusion with citations]
+
+**One-sentence answer:**
+[Your one-sentence summary with citations]
+"""
+
+ logger.info(
+ f"Synthesizing final answer. Query: '{query}'. Knowledge length: {len(current_knowledge)}. Prompt length: {len(prompt)}"
+ )
+ # Log first 500 chars of prompt for debugging context length issues
+ logger.debug(f"Synthesis prompt (first 500 chars): {prompt[:500]}...")
+
+ try:
+ response = self.model.invoke(prompt)
+ synthesized_content = remove_think_tags(response.content)
+ logger.info(
+ f"Successfully synthesized final answer for query: '{query}'"
+ )
+ # Return only the synthesized content from the LLM
+ return synthesized_content
+ except Exception as invoke_error:
+ logger.error(
+ f"LLM invocation failed during synthesis for query '{query}': {invoke_error}",
+ exc_info=True,
+ )
+ # Re-raise or return specific error
+ return "Error: Failed to synthesize final answer due to LLM error."
+
+ except Exception as e:
+ # Catch potential errors during prompt construction or logging itself
+ logger.error(
+ f"Error preparing or executing synthesis for query '{query}': {str(e)}",
+ exc_info=True,
+ )
+ # Return a specific error message for synthesis failure
+ return "Error: Failed to synthesize final answer from knowledge."
diff --git a/src/local_deep_research/search_system/knowledge/__init__.py b/src/local_deep_research/advanced_search_system/knowledge/__init__.py
similarity index 100%
rename from src/local_deep_research/search_system/knowledge/__init__.py
rename to src/local_deep_research/advanced_search_system/knowledge/__init__.py
diff --git a/src/local_deep_research/search_system/knowledge/base_knowledge.py b/src/local_deep_research/advanced_search_system/knowledge/base_knowledge.py
similarity index 53%
rename from src/local_deep_research/search_system/knowledge/base_knowledge.py
rename to src/local_deep_research/advanced_search_system/knowledge/base_knowledge.py
index 0630ffb4ea..f1e88a0f1e 100644
--- a/src/local_deep_research/search_system/knowledge/base_knowledge.py
+++ b/src/local_deep_research/advanced_search_system/knowledge/base_knowledge.py
@@ -1,36 +1,81 @@
"""
-Base class for all knowledge managers.
-Defines the common interface and shared functionality for different knowledge management approaches.
+Base class for knowledge extraction and generation.
"""
import logging
from abc import ABC, abstractmethod
from typing import List
+from langchain_core.language_models.chat_models import BaseChatModel
+
logger = logging.getLogger(__name__)
-class BaseKnowledgeManager(ABC):
- """Abstract base class for all knowledge managers."""
+class BaseKnowledgeGenerator(ABC):
+ """Base class for generating knowledge from text."""
- def __init__(self, model):
+ def __init__(self, model: BaseChatModel):
"""
- Initialize the knowledge manager.
+ Initialize the knowledge generator.
Args:
- model: The language model to use for knowledge operations
+ model: The language model to use
"""
self.model = model
@abstractmethod
- def compress_knowledge(self, knowledge: str, query: str, links: List[str]) -> str:
+ def generate(self, query: str, context: str) -> str:
+ """Generate knowledge from the given query and context."""
+ pass
+
+ @abstractmethod
+ def generate_knowledge(
+ self,
+ query: str,
+ context: str = "",
+ current_knowledge: str = "",
+ questions: List[str] = None,
+ ) -> str:
+ """
+ Generate knowledge based on query and context.
+
+ Args:
+ query: The query to generate knowledge for
+ context: Additional context for knowledge generation
+ current_knowledge: Current accumulated knowledge
+ questions: List of questions to address
+
+ Returns:
+ str: Generated knowledge
+ """
+ pass
+
+ @abstractmethod
+ def generate_sub_knowledge(self, sub_query: str, context: str = "") -> str:
+ """
+ Generate knowledge for a sub-question.
+
+ Args:
+ sub_query: The sub-question to generate knowledge for
+ context: Additional context for knowledge generation
+
+ Returns:
+ str: Generated knowledge for the sub-question
+ """
+ pass
+
+ @abstractmethod
+ def compress_knowledge(
+ self, current_knowledge: str, query: str, section_links: list, **kwargs
+ ) -> str:
"""
Compress and summarize accumulated knowledge.
Args:
- knowledge: The accumulated knowledge to compress
+ current_knowledge: The accumulated knowledge to compress
query: The original research query
- links: List of source links
+ section_links: List of source links
+ **kwargs: Additional arguments
Returns:
str: Compressed knowledge
diff --git a/src/local_deep_research/advanced_search_system/knowledge/standard_knowledge.py b/src/local_deep_research/advanced_search_system/knowledge/standard_knowledge.py
new file mode 100644
index 0000000000..026bbeb286
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/knowledge/standard_knowledge.py
@@ -0,0 +1,143 @@
+"""
+Standard knowledge generator implementation.
+"""
+
+import logging
+from datetime import datetime
+from typing import List
+
+from ...utilties.search_utilities import remove_think_tags
+from .base_knowledge import BaseKnowledgeGenerator
+
+logger = logging.getLogger(__name__)
+
+
+class StandardKnowledgeGenerator(BaseKnowledgeGenerator):
+ """Standard knowledge generator implementation."""
+
+ def generate_knowledge(
+ self,
+ query: str,
+ context: str = "",
+ current_knowledge: str = "",
+ questions: List[str] = None,
+ ) -> str:
+ """Generate knowledge based on query and context."""
+ now = datetime.now()
+ current_time = now.strftime("%Y-%m-%d")
+
+ logger.info("Generating knowledge...")
+
+ if questions:
+ prompt = f"""Based on the following query and questions, generate comprehensive knowledge:
+
+Query: {query}
+Current Time: {current_time}
+Context: {context}
+Current Knowledge: {current_knowledge}
+Questions: {questions}
+
+Generate detailed knowledge that:
+1. Directly answers the query
+2. Addresses each question
+3. Includes relevant facts and details
+4. Is up-to-date with current information
+5. Synthesizes information from multiple sources
+
+Format your response as a well-structured paragraph."""
+ else:
+ prompt = f"""Based on the following query, generate comprehensive knowledge:
+
+Query: {query}
+Current Time: {current_time}
+Context: {context}
+Current Knowledge: {current_knowledge}
+
+Generate detailed knowledge that:
+1. Directly answers the query
+2. Includes relevant facts and details
+3. Is up-to-date with current information
+4. Synthesizes information from multiple sources
+
+Format your response as a well-structured paragraph."""
+
+ response = self.model.invoke(prompt)
+ knowledge = remove_think_tags(response.content)
+
+ logger.info("Generated knowledge successfully")
+ return knowledge
+
+ def generate_sub_knowledge(self, sub_query: str, context: str = "") -> str:
+ """
+ Generate knowledge for a sub-question.
+
+ Args:
+ sub_query: The sub-question to generate knowledge for
+ context: Additional context for knowledge generation
+
+ Returns:
+ str: Generated knowledge for the sub-question
+ """
+ prompt = f"""Generate comprehensive knowledge to answer this sub-question:
+
+Sub-question: {sub_query}
+
+{context}
+
+Generate detailed knowledge that:
+1. Directly answers the sub-question
+2. Includes relevant facts and details
+3. Is up-to-date with current information
+4. Synthesizes information from multiple sources
+
+Format your response as a well-structured paragraph."""
+
+ try:
+ response = self.model.invoke(prompt)
+ return remove_think_tags(response.content)
+ except Exception as e:
+ logger.error(f"Error generating sub-knowledge: {str(e)}")
+ return ""
+
+ def compress_knowledge(self, query: str, accumulated_knowledge: str) -> str:
+ """Compress the accumulated knowledge for the given query."""
+ logger.info(
+ f"Compressing knowledge for query: {query}. Original length: {len(accumulated_knowledge)}"
+ )
+
+ prompt = f"""Compress the following accumulated knowledge relevant to the query '{query}'.
+Retain the key facts, findings, and citations. Remove redundancy.
+
+Accumulated Knowledge:
+{accumulated_knowledge}
+
+Compressed Knowledge:"""
+
+ try:
+ response = self.model.invoke(prompt)
+ compressed_knowledge = remove_think_tags(response.content)
+ logger.info(f"Compressed knowledge length: {len(compressed_knowledge)}")
+ return compressed_knowledge
+ except Exception as e:
+ logger.error(f"Error compressing knowledge: {str(e)}")
+ return accumulated_knowledge # Return original if compression fails
+
+ def format_citations(self, links: List[str]) -> str:
+ """
+ Format source links into citations using IEEE style.
+
+ Args:
+ links: List of source links
+
+ Returns:
+ str: Formatted citations in IEEE style
+ """
+ if not links:
+ return ""
+
+ # Format each link as an IEEE citation
+ citations = []
+ for i, link in enumerate(links, 1):
+ citations.append(f"[{i}] {link}")
+
+ return "\n".join(citations)
diff --git a/src/local_deep_research/search_system/questions/__init__.py b/src/local_deep_research/advanced_search_system/questions/__init__.py
similarity index 100%
rename from src/local_deep_research/search_system/questions/__init__.py
rename to src/local_deep_research/advanced_search_system/questions/__init__.py
diff --git a/src/local_deep_research/search_system/questions/base_question.py b/src/local_deep_research/advanced_search_system/questions/base_question.py
similarity index 100%
rename from src/local_deep_research/search_system/questions/base_question.py
rename to src/local_deep_research/advanced_search_system/questions/base_question.py
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.py
new file mode 100644
index 0000000000..7d02636264
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/questions/decomposition_question.py
@@ -0,0 +1,51 @@
+import logging
+from typing import Dict, List
+
+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"""Decompose the main query into 3-5 specific sub-queries that can be answered independently based on the provided context.
+Focus on breaking down complex concepts and identifying key aspects requiring separate investigation.
+Ensure sub-queries are clear, targeted, and help build a comprehensive understanding.
+
+Main Query: {query}
+
+Context (Initial Search Results):
+{context}
+
+Sub-queries (one per line):
+"""
+
+ 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
+ sub_queries = [
+ q.strip() for q in response.content.strip().split("\n") if q.strip()
+ ]
+ logger.info(f"Generated {len(sub_queries)} sub-questions.")
+ return sub_queries[: self.max_subqueries] # Limit to max_subqueries
diff --git a/src/local_deep_research/advanced_search_system/questions/standard_question.py b/src/local_deep_research/advanced_search_system/questions/standard_question.py
new file mode 100644
index 0000000000..2449ad7a75
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/questions/standard_question.py
@@ -0,0 +1,104 @@
+"""
+Standard question generation implementation.
+"""
+
+import logging
+from datetime import datetime
+from typing import List
+
+from ...utilties.search_utilities import remove_think_tags
+from .base_question import BaseQuestionGenerator
+
+logger = logging.getLogger(__name__)
+
+
+class StandardQuestionGenerator(BaseQuestionGenerator):
+ """Standard 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 questions
+
+ def generate_sub_questions(self, query: str, context: str = "") -> List[str]:
+ """
+ Generate sub-questions from a main query.
+
+ Args:
+ query: The main query to break down
+ context: Additional context for question generation
+
+ Returns:
+ List[str]: List of generated sub-questions
+ """
+ prompt = f"""You are an expert at breaking down complex questions into simpler sub-questions.
+
+Original Question: {query}
+
+{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-questions from the response
+ sub_questions = []
+ for line in content.strip().split("\n"):
+ line = line.strip()
+ if line and (line[0].isdigit() or line.startswith("-")):
+ # Extract sub-question from numbered or bulleted list
+ parts = line.split(".", 1) if "." in line else line.split(" ", 1)
+ if len(parts) > 1:
+ sub_question = parts[1].strip()
+ sub_questions.append(sub_question)
+
+ # Limit to at most 5 sub-questions
+ return sub_questions[:5]
+ except Exception as e:
+ logger.error(f"Error generating sub-questions: {str(e)}")
+ return []
diff --git a/src/local_deep_research/advanced_search_system/repositories/__init__.py b/src/local_deep_research/advanced_search_system/repositories/__init__.py
new file mode 100644
index 0000000000..70118b4c58
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/repositories/__init__.py
@@ -0,0 +1,7 @@
+"""
+Repositories package for advanced search system.
+"""
+
+from .findings_repository import FindingsRepository
+
+__all__ = ["FindingsRepository"]
diff --git a/src/local_deep_research/advanced_search_system/repositories/findings_repository.py b/src/local_deep_research/advanced_search_system/repositories/findings_repository.py
new file mode 100644
index 0000000000..fc3026bbd0
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/repositories/findings_repository.py
@@ -0,0 +1,41 @@
+"""
+Repository for handling research findings.
+"""
+
+import logging
+from typing import Dict, List
+
+from ...utilties.search_utilities import format_findings_to_text
+
+logger = logging.getLogger(__name__)
+
+
+class FindingsRepository:
+ """Repository for handling 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.
+
+ Args:
+ findings: List of research findings
+ current_knowledge: Current accumulated knowledge
+ questions_by_iteration: Questions generated by iteration
+ query: The original research query
+
+ Returns:
+ str: Formatted findings
+ """
+ try:
+ return format_findings_to_text(
+ findings, current_knowledge, questions_by_iteration
+ )
+ except Exception as e:
+ logger.error(f"Error saving findings: {str(e)}")
+ return "Error: Could not format findings due to an error."
diff --git a/src/local_deep_research/search_system/strategies/__init__.py b/src/local_deep_research/advanced_search_system/strategies/__init__.py
similarity index 100%
rename from src/local_deep_research/search_system/strategies/__init__.py
rename to src/local_deep_research/advanced_search_system/strategies/__init__.py
diff --git a/src/local_deep_research/search_system/strategies/base_strategy.py b/src/local_deep_research/advanced_search_system/strategies/base_strategy.py
similarity index 100%
rename from src/local_deep_research/search_system/strategies/base_strategy.py
rename to src/local_deep_research/advanced_search_system/strategies/base_strategy.py
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.py
new file mode 100644
index 0000000000..f7c9375da7
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py
@@ -0,0 +1,323 @@
+"""
+IterDRAG strategy implementation.
+"""
+
+import json
+import logging
+from datetime import datetime
+from typing import Callable, Dict, List
+
+from ... import get_search
+from ...citation_handler import CitationHandler
+from ...config.config_files import settings
+from ...utilties.search_utilities import (
+ extract_links_from_search_results,
+)
+from ..findings.repository import FindingsRepository
+from ..knowledge.standard_knowledge import StandardKnowledgeGenerator
+from ..questions.decomposition_question import DecompositionQuestionGenerator
+from .base_strategy import BaseSearchStrategy
+
+logger = logging.getLogger(__name__)
+
+
+class IterDRAGStrategy(BaseSearchStrategy):
+ """IterDRAG strategy that breaks queries into sub-queries."""
+
+ def __init__(self, model):
+ """Initialize the strategy."""
+ super().__init__()
+ self.search = get_search()
+ self.model = model
+ self.citation_handler = CitationHandler(self.model)
+ self.progress_callback = None
+ self.all_links_of_system = list()
+ self.questions_by_iteration = {}
+
+ # Initialize components
+ self.question_generator = DecompositionQuestionGenerator(model)
+ self.knowledge_generator = StandardKnowledgeGenerator(model)
+ self.findings_repository = FindingsRepository(model)
+
+ 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], current_knowledge: str
+ ) -> List[str]:
+ """Generate sub-queries based on initial search results and the main query."""
+ try:
+ # Format context for question generation
+ context = f"""Current Query: {query}
+Current Date: {datetime.now().strftime('%Y-%m-%d')}
+Past Questions: {self.questions_by_iteration}
+Current Knowledge: {current_knowledge}
+
+Initial Search Results:
+{json.dumps(initial_results, indent=2)}"""
+
+ # Generate sub-queries using the question generator
+ return self.question_generator.generate_questions(query, context)
+ except Exception as e:
+ logger.error(f"Error generating sub-queries: {str(e)}")
+ return []
+
+ 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(
+ "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, current_knowledge
+ )
+
+ # Store questions in repository
+ self.findings_repository.set_questions_by_iteration({0: sub_queries})
+
+ 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:
+ finding = {
+ "phase": "Direct answer",
+ "content": result["content"],
+ "question": query,
+ "search_results": initial_results,
+ "documents": result["documents"],
+ }
+ findings.append(finding)
+ self.findings_repository.add_finding(query, finding["content"])
+ self.findings_repository.add_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, 1):
+ progress_base = 25 + (i / total_subqueries * 50)
+ self._update_progress(
+ f"Processing sub-query {i} of {total_subqueries}",
+ int(progress_base),
+ {"phase": "subquery", "subquery_index": i},
+ )
+
+ # 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:
+ finding = {
+ "phase": f"Sub-query {i}",
+ "content": result["content"],
+ "question": sub_query,
+ "search_results": sub_results,
+ "documents": result["documents"],
+ }
+ findings.append(finding)
+ self.findings_repository.add_finding(sub_query, finding)
+ self.findings_repository.add_documents(result["documents"])
+
+ # Add to current knowledge with space around +
+ 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)}")
+ finding = {
+ "phase": f"Follow-up Iteration 0.{i + 1}",
+ "content": "Error analyzing sub-query results.",
+ "question": sub_query,
+ "search_results": [],
+ "documents": [],
+ }
+ findings.append(finding)
+ # Optionally update current_knowledge even if analysis failed?
+ # current_knowledge += f"\n\nError analyzing results for: {sub_query}"
+
+ # 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.findings_repository.synthesize_findings(
+ query, sub_queries, current_knowledge # Pass accumulated knowledge
+ )
+
+ finding = {
+ "phase": "Final synthesis",
+ "content": final_answer,
+ "question": query,
+ "search_results": [],
+ "documents": [],
+ }
+ findings.append(finding)
+ # Store the *raw synthesized content* associated with the main query
+ self.findings_repository.add_finding(
+ query + "_synthesis", finding["content"]
+ )
+
+ current_knowledge = (
+ final_answer # Update knowledge with the *synthesized* version
+ )
+ except Exception as e:
+ logger.error(f"Error synthesizing final answer: {str(e)}")
+ # If synthesis fails, keep existing knowledge, maybe add error note?
+ final_answer = current_knowledge # Fallback to pre-synthesis knowledge
+
+ # Compress knowledge if needed
+ if settings.general.knowledge_accumulation == "ITERATION":
+ try:
+ self._update_progress(
+ "Compressing knowledge", 90, {"phase": "knowledge_compression"}
+ )
+ current_knowledge = self.knowledge_generator.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:
+ # Use the final_answer (synthesized content) and original findings list
+ formatted_findings = self.findings_repository.format_findings_to_text(
+ findings, final_answer # Pass original findings and synthesized content
+ )
+ # Add the formatted findings to the repository (using a distinct name if needed)
+ # self.findings_repository.add_finding(query + "_formatted", formatted_findings)
+ except Exception as e:
+ logger.error(f"Error formatting final findings: {str(e)}")
+ formatted_findings = (
+ "Error: Could not format final findings due to an error."
+ )
+
+ self._update_progress("Research complete", 100, {"phase": "complete"})
+
+ return {
+ "findings": findings, # Keep the detailed findings list
+ "iterations": 1,
+ "questions": {"0": sub_queries},
+ "formatted_findings": formatted_findings, # This is the fully formatted string for UI
+ "current_knowledge": current_knowledge, # This is the synthesized content for knowledge base
+ }
diff --git a/src/local_deep_research/search_system/strategies/standard_strategy.py b/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
similarity index 92%
rename from src/local_deep_research/search_system/strategies/standard_strategy.py
rename to src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
index 63189d7d78..9926aea860 100644
--- a/src/local_deep_research/search_system/strategies/standard_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
@@ -6,9 +6,9 @@ from ...citation_handler import CitationHandler
from ...config.config_files import settings
from ...utilties.enums import KnowledgeAccumulationApproach
from ...utilties.search_utilities import extract_links_from_search_results
-from ..knowledge.standard_knowledge import StandardKnowledgeManager
+from ..findings.repository import FindingsRepository
+from ..knowledge.standard_knowledge import StandardKnowledgeGenerator
from ..questions.standard_question import StandardQuestionGenerator
-from ..repositories.findings_repository import FindingsRepository
from .base_strategy import BaseSearchStrategy
logger = logging.getLogger(__name__)
@@ -30,8 +30,8 @@ class StandardSearchStrategy(BaseSearchStrategy):
# Initialize directly with the specialized components
self.question_generator = StandardQuestionGenerator(self.model)
- self.knowledge_manager = StandardKnowledgeManager(self.model)
- self.findings_repository = FindingsRepository()
+ self.knowledge_generator = StandardKnowledgeGenerator(self.model)
+ self.findings_repository = FindingsRepository(self.model)
def set_progress_callback(self, callback: Callable[[str, int, dict], None]) -> None:
"""Set a callback function to receive progress updates."""
@@ -209,7 +209,7 @@ class StandardSearchStrategy(BaseSearchStrategy):
{"phase": "analysis"},
)
current_knowledge = (
- self.knowledge_manager.compress_knowledge(
+ self.knowledge_generator.compress_knowledge(
current_knowledge, query, section_links
)
)
@@ -241,7 +241,7 @@ class StandardSearchStrategy(BaseSearchStrategy):
):
try:
logger.info("ITERATION - Compressing Knowledge")
- current_knowledge = self.knowledge_manager.compress_knowledge(
+ current_knowledge = self.knowledge_generator.compress_knowledge(
current_knowledge, query, section_links
)
logger.info("FINISHED ITERATION - Compressing Knowledge")
@@ -261,17 +261,13 @@ class StandardSearchStrategy(BaseSearchStrategy):
)
try:
- formatted_findings = self.findings_repository.save_findings(
- findings, current_knowledge, self.questions_by_iteration, query
+ formatted_findings = self.findings_repository.synthesize_findings(
+ query, [f["content"] for f in findings], section_links
)
+ # Add the formatted findings to the repository
+ self.findings_repository.add_finding(query, formatted_findings)
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)},
- )
+ logger.error(f"Error saving findings: {str(e)}")
formatted_findings = "Error: Could not format findings due to an error."
self._update_progress("Research complete", 95, {"phase": "complete"})
diff --git a/src/local_deep_research/search_system/tools/__init__.py b/src/local_deep_research/advanced_search_system/tools/__init__.py
similarity index 100%
rename from src/local_deep_research/search_system/tools/__init__.py
rename to src/local_deep_research/advanced_search_system/tools/__init__.py
diff --git a/src/local_deep_research/search_system/tools/base_tool.py b/src/local_deep_research/advanced_search_system/tools/base_tool.py
similarity index 100%
rename from src/local_deep_research/search_system/tools/base_tool.py
rename to src/local_deep_research/advanced_search_system/tools/base_tool.py
diff --git a/src/local_deep_research/search_system/tools/knowledge_tools/__init__.py b/src/local_deep_research/advanced_search_system/tools/knowledge_tools/__init__.py
similarity index 100%
rename from src/local_deep_research/search_system/tools/knowledge_tools/__init__.py
rename to src/local_deep_research/advanced_search_system/tools/knowledge_tools/__init__.py
diff --git a/src/local_deep_research/search_system/tools/question_tools/__init__.py b/src/local_deep_research/advanced_search_system/tools/question_tools/__init__.py
similarity index 100%
rename from src/local_deep_research/search_system/tools/question_tools/__init__.py
rename to src/local_deep_research/advanced_search_system/tools/question_tools/__init__.py
diff --git a/src/local_deep_research/search_system/tools/search_tools/__init__.py b/src/local_deep_research/advanced_search_system/tools/search_tools/__init__.py
similarity index 100%
rename from src/local_deep_research/search_system/tools/search_tools/__init__.py
rename to src/local_deep_research/advanced_search_system/tools/search_tools/__init__.py
diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.py
index be7a2c5773..668284c670 100644
--- a/src/local_deep_research/api/research_functions.py
+++ b/src/local_deep_research/api/research_functions.py
@@ -12,7 +12,7 @@ import toml
from .. import get_report_generator # Use the lazy import function
from ..config.llm_config import get_llm
from ..config.search_config import get_search
-from ..search_system.search_system import AdvancedSearchSystem
+from ..search_system import AdvancedSearchSystem
from ..utilties.search_utilities import remove_think_tags
logger = logging.getLogger(__name__)
diff --git a/src/local_deep_research/report_generator.py b/src/local_deep_research/report_generator.py
index 8399034ce4..c16d69d3ce 100644
--- a/src/local_deep_research/report_generator.py
+++ b/src/local_deep_research/report_generator.py
@@ -1,220 +1,72 @@
-import importlib
-from typing import Dict, List
+"""
+Report generator module for Local Deep Research.
+"""
+
+import logging
+from typing import Dict, Optional
-# Fix circular import by importing directly from source modules
-from .config.llm_config import get_llm
from .search_system import AdvancedSearchSystem
+from .utilties.search_utilities import format_findings
-# from . import utilties
-from .utilties import search_utilities
+logger = logging.getLogger(__name__)
class IntegratedReportGenerator:
- 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.
+ """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
"""
+ self.search_system = search_system or AdvancedSearchSystem()
- 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]:
+ def generate_report(self, results: Dict, query: str) -> Dict:
"""
- This method is kept for compatibility but no longer used.
- The functionality has been moved to _research_and_generate_sections.
+ 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
"""
- 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_report
+ 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"]
diff --git a/src/local_deep_research/search_system/search_system.py b/src/local_deep_research/search_system.py
similarity index 68%
rename from src/local_deep_research/search_system/search_system.py
rename to src/local_deep_research/search_system.py
index acc6742315..b6ef4c0afc 100644
--- a/src/local_deep_research/search_system/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -2,24 +2,34 @@
import logging
from typing import Callable, Dict
-from ..config.config_files import settings
-from ..config.llm_config import get_llm
-from ..config.search_config import get_search
-from .strategies.standard_strategy import StandardSearchStrategy
+from .advanced_search_system.strategies.iterdrag_strategy import IterDRAGStrategy
+from .advanced_search_system.strategies.standard_strategy import StandardSearchStrategy
+from .config.config_files import settings
+from .config.llm_config import get_llm
+from .config.search_config import get_search
logger = logging.getLogger(__name__)
class AdvancedSearchSystem:
- def __init__(self):
+ def __init__(self, strategy_name: str = "standard"):
+ """
+ Initialize the advanced search system.
+
+ Args:
+ strategy_name: The name of the search strategy to use ("standard" or "iterdrag")
+ """
# Get configuration
self.search = get_search()
self.model = get_llm()
self.max_iterations = settings.search.iterations
self.questions_per_iteration = settings.search.questions_per_iteration
- # Initialize strategy
- self.strategy = StandardSearchStrategy()
+ # Initialize strategy based on name
+ if strategy_name.lower() == "iterdrag":
+ self.strategy = IterDRAGStrategy(self.model)
+ else:
+ self.strategy = StandardSearchStrategy()
# For backward compatibility
self.questions_by_iteration = {}
diff --git a/src/local_deep_research/search_system/__init__.py b/src/local_deep_research/search_system/__init__.py
deleted file mode 100644
index 2614545b6d..0000000000
--- a/src/local_deep_research/search_system/__init__.py
+++ /dev/null
@@ -1,4 +0,0 @@
-# Search System Package
-from .search_system import AdvancedSearchSystem
-
-__all__ = ["AdvancedSearchSystem"]
diff --git a/src/local_deep_research/search_system/knowledge/standard_knowledge.py b/src/local_deep_research/search_system/knowledge/standard_knowledge.py
deleted file mode 100644
index d2181057c6..0000000000
--- a/src/local_deep_research/search_system/knowledge/standard_knowledge.py
+++ /dev/null
@@ -1,30 +0,0 @@
-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/decomposition_question.py b/src/local_deep_research/search_system/questions/decomposition_question.py
deleted file mode 100644
index 8aaf1035ea..0000000000
--- a/src/local_deep_research/search_system/questions/decomposition_question.py
+++ /dev/null
@@ -1,64 +0,0 @@
-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.py
deleted file mode 100644
index ec6f4858d2..0000000000
--- a/src/local_deep_research/search_system/questions/standard_question.py
+++ /dev/null
@@ -1,42 +0,0 @@
-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 questions
diff --git a/src/local_deep_research/search_system/repositories/__init__.py b/src/local_deep_research/search_system/repositories/__init__.py
deleted file mode 100644
index 07ea4cfe97..0000000000
--- a/src/local_deep_research/search_system/repositories/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-# Search System Repositories Package
diff --git a/src/local_deep_research/search_system/repositories/findings_repository.py b/src/local_deep_research/search_system/repositories/findings_repository.py
deleted file mode 100644
index a323e39143..0000000000
--- a/src/local_deep_research/search_system/repositories/findings_repository.py
+++ /dev/null
@@ -1,14 +0,0 @@
-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
- pass
diff --git a/src/local_deep_research/search_system/strategies/iterdrag_strategy.py b/src/local_deep_research/search_system/strategies/iterdrag_strategy.py
deleted file mode 100644
index ae12f9dd81..0000000000
--- a/src/local_deep_research/search_system/strategies/iterdrag_strategy.py
+++ /dev/null
@@ -1,290 +0,0 @@
-# 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 file
diff --git a/src/local_deep_research/utilties/search_utilities.py b/src/local_deep_research/utilties/search_utilities.py
index 09bdca463e..71a0f84c95 100644
--- a/src/local_deep_research/utilties/search_utilities.py
+++ b/src/local_deep_research/utilties/search_utilities.py
@@ -1,5 +1,6 @@
import logging
import re
+from typing import Dict, List
logger = logging.getLogger(__name__)
@@ -9,7 +10,7 @@ def remove_think_tags(text: str) -> str:
return text
-def extract_links_from_search_results(search_results: list) -> list:
+def extract_links_from_search_results(search_results: List[Dict]) -> List[Dict]:
"""
Extracts links and titles from a list of search result dictionaries.
@@ -33,7 +34,7 @@ def extract_links_from_search_results(search_results: list) -> list:
return links
-def format_links(links):
+def format_links(links: List[Dict]) -> str:
formatted_links = ""
formatted_links += "SOURCES:\n"
for i, link in enumerate(links, 1):
@@ -42,71 +43,127 @@ def format_links(links):
return formatted_links
-def format_findings_to_text(findings_list, current_knowledge, questions_by_iteration):
- formatted_text = "COMPLETE RESEARCH OUTPUT \n\n"
-
- # Store the full current knowledge
-
- formatted_text += f"{current_knowledge}\n\n"
- formatted_text += "=" * 80 + "\n\n"
-
- # Store questions by iteration
- formatted_text += "SEARCH QUESTIONS BY ITERATION:\n"
- for iter_num, questions in questions_by_iteration.items():
- formatted_text += f"\nIteration {iter_num}:\n"
- for i, q in enumerate(questions, 1):
- formatted_text += f"{i}. {q}\n"
- formatted_text += "\n" + "=" * 80 + "\n\n"
-
- # Store detailed findings
- formatted_text += "DETAILED FINDINGS:\n\n"
- all_links = [] # To collect all sources
-
- for finding in findings_list:
- # Phase header
- formatted_text += f"{'=' * 80}\n"
- formatted_text += f"PHASE: {finding['phase']}\n"
- formatted_text += f"{'=' * 80}\n\n"
-
- # If this is a follow-up phase, show the corresponding question
- if finding["phase"].startswith("Follow-up"):
- iteration = int(finding["phase"].split(".")[0].split()[-1])
- question_index = int(finding["phase"].split(".")[-1]) - 1
- if iteration in questions_by_iteration and question_index < len(
- questions_by_iteration[iteration]
- ):
- formatted_text += f"SEARCH QUESTION:\n{questions_by_iteration[iteration][question_index]}\n\n"
-
- # Content
- formatted_text += f"CONTENT:\n{finding['content']}\n\n"
-
- # Search results if they exist
- if "search_results" in finding:
- # formatted_text += "SEARCH RESULTS:\n"
- # formatted_text += f"{finding['search_results']}\n\n"
-
- # Extract and format links for this finding
- links = extract_links_from_search_results(finding["search_results"])
- if links:
- formatted_text += "SOURCES USED IN THIS SECTION:\n"
- for i, link in enumerate(links, 1):
- formatted_text += f"{i}. {link['title']}\n URL: {link['url']}\n"
- formatted_text += "\n"
- all_links.extend(links)
-
- formatted_text += f"{'_' * 80}\n\n"
+def format_findings(
+ findings_list: List[Dict],
+ synthesized_content: str,
+ questions_by_iteration: Dict[int, List[str]],
+) -> str:
+ """Format findings into a detailed text output.
+
+ Args:
+ findings_list: List of finding dictionaries
+ synthesized_content: The synthesized content from the LLM.
+ questions_by_iteration: Dictionary mapping iteration numbers to lists of questions
+
+ Returns:
+ str: Formatted text output
+ """
+ logger.info(
+ f"Inside format_findings utility. Findings count: {len(findings_list)}, Questions iterations: {len(questions_by_iteration)}"
+ )
+ formatted_text = ""
+
+ # Start with the synthesized content (passed as synthesized_content)
+ formatted_text += f"{synthesized_content}\n\n"
+ # formatted_text += "=" * 80 + "\n\n" # Separator after synthesized content
+
+ # Add Search Questions by Iteration section
+ if questions_by_iteration:
+ formatted_text += "SEARCH QUESTIONS BY ITERATION:\n"
+ formatted_text += "=" * 80 + "\n"
+ for iter_num, questions in questions_by_iteration.items():
+ formatted_text += f"\nIteration {iter_num}:\n"
+ for i, q in enumerate(questions, 1):
+ formatted_text += f"{i}. {q}\n"
+ formatted_text += "\n" + "=" * 80 + "\n\n"
+ else:
+ logger.warning("No questions by iteration found to format.")
+
+ # Add Detailed Findings section
+ if findings_list:
+ formatted_text += "DETAILED FINDINGS:\n\n"
+ all_links = [] # To collect all sources
+ logger.info(f"Formatting {len(findings_list)} detailed finding items.")
+
+ for idx, finding in enumerate(findings_list):
+ logger.debug(f"Formatting finding item {idx}. Keys: {list(finding.keys())}")
+ # Use .get() for safety
+ phase = finding.get("phase", "Unknown Phase")
+ content = finding.get("content", "No content available.")
+ search_results = finding.get("search_results", [])
+
+ # Phase header
+ formatted_text += f"{'=' * 80}\n"
+ formatted_text += f"PHASE: {phase}\n"
+ formatted_text += f"{'=' * 80}\n\n"
+
+ # If this is a follow-up phase, try to show the corresponding question
+ if isinstance(phase, str) and phase.startswith("Follow-up"):
+ try:
+ parts = phase.replace("Follow-up Iteration ", "").split(".")
+ if len(parts) == 2:
+ iteration = int(parts[0])
+ question_index = int(parts[1]) - 1
+ if (
+ iteration in questions_by_iteration
+ and 0
+ <= question_index
+ < len(questions_by_iteration[iteration])
+ ):
+ formatted_text += f"SEARCH QUESTION:\n{questions_by_iteration[iteration][question_index]}\n\n"
+ else:
+ logger.warning(
+ f"Could not find matching question for phase: {phase}"
+ )
+ else:
+ logger.warning(
+ f"Could not parse iteration/index from phase: {phase}"
+ )
+ except ValueError:
+ logger.warning(
+ f"Could not parse iteration/index from phase: {phase}"
+ )
+
+ # Content
+ formatted_text += f"CONTENT:\n{content}\n\n"
+
+ # Search results if they exist
+ if search_results:
+ try:
+ links = extract_links_from_search_results(search_results)
+ if links:
+ formatted_text += "SOURCES USED IN THIS SECTION:\n"
+ formatted_text += format_links(links) + "\n\n"
+ all_links.extend(links)
+ except Exception as link_err:
+ logger.error(
+ f"Error processing search results/links for finding {idx}: {link_err}"
+ )
+ else:
+ logger.debug(f"No search_results found for finding item {idx}.")
+
+ formatted_text += f"{'_' * 80}\n\n"
+ else:
+ logger.warning("No detailed findings found to format.")
# Add summary of all sources at the end
if all_links:
- formatted_text += "\nALL SOURCES USED IN RESEARCH:\n"
+ formatted_text += "ALL SOURCES USED IN RESEARCH:\n"
formatted_text += "=" * 80 + "\n\n"
- seen_urls = set() # To prevent duplicates
- for i, link in enumerate(all_links, 1):
- if link["url"] not in seen_urls:
- formatted_text += f"{i}. {link['title']}\n URL: {link['url']}\n"
- seen_urls.add(link["url"])
+ 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:
+ formatted_text += f"{link_counter}. {title}\n URL: {url}\n"
+ seen_urls.add(url)
+ link_counter += 1
formatted_text += "\n" + "=" * 80 + "\n"
+ else:
+ logger.info("No unique sources found across all findings to list.")
+ logger.info("Finished format_findings utility.")
return formatted_text
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 7d8c04e1ee..224d6fd5cd 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -5,9 +5,13 @@ import threading
import traceback
from datetime import datetime
-from flask_socketio import emit
-
+from ...advanced_search_system import AdvancedSearchSystem
+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 ..models.database import add_log_to_db, calculate_duration, get_db_connection
+from .socket_service import emit_to_subscribers # Keep if needed directly
# Initialize logger
logger = logging.getLogger(__name__)
@@ -211,8 +215,6 @@ def run_research_process(
if metadata:
event_data["log_entry"] = log_entry
- from ..services.socket_service import emit_to_subscribers
-
emit_to_subscribers("research_progress", research_id, event_data)
except Exception as e:
logger.error(f"Socket emit error (non-critical): {str(e)}")
@@ -227,8 +229,6 @@ def run_research_process(
return False # Not terminated
# Set the progress callback in the system
- from ...search_system import AdvancedSearchSystem
-
system = AdvancedSearchSystem()
system.set_progress_callback(progress_callback)
@@ -239,11 +239,6 @@ def run_research_process(
f"Overriding system settings with: model={model}, search_engine={search_engine}"
)
- # 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 specified
if model:
try:
@@ -469,8 +464,6 @@ def run_research_process(
"Generating detailed report...", 85, {"phase": "report_generation"}
)
- from ...report_generator import IntegratedReportGenerator
-
report_generator = IntegratedReportGenerator()
final_report = report_generator.generate_report(results, query)
@@ -616,8 +609,6 @@ def run_research_process(
conn.close()
try:
- from ..services.socket_service import emit_to_subscribers
-
emit_to_subscribers(
"research_progress",
research_id,
@@ -696,8 +687,6 @@ def cleanup_research_resources(research_id, active_research, termination_flags):
f"Sending final {current_status} socket message for research {research_id}"
)
- from ..services.socket_service import emit_to_subscribers
-
emit_to_subscribers("research_progress", research_id, final_message)
except Exception as e: