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.

minor

LearningCircuit47ce6383259e
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index d06d07424c..5e70a5deee 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -1,399 +1,51 @@
+# src/local_deep_research/search_system.py
import logging
-import os
-from datetime import datetime
-from typing import Callable, Dict, List
+from typing import Callable, Dict
-from .citation_handler import CitationHandler
-from .config.config_files import get_config_dir, settings
-
-# Fix circular import - import directly from the config module, not from parent package
+from .config.config_files import settings
from .config.llm_config import get_llm
from .config.search_config import get_search
-from .utilties.enums import KnowledgeAccumulationApproach
-from .utilties.search_utilities import (
- extract_links_from_search_results,
- format_findings_to_text,
- format_links,
- remove_think_tags,
-)
+from .search_system.strategies.standard_strategy import StandardSearchStrategy
logger = logging.getLogger(__name__)
class AdvancedSearchSystem:
def __init__(self):
-
- # Get fresh configuration
-
+ # 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
- self.context_limit = settings.general.knowledge_accumulation_context_limit
+ # Initialize strategy
+ self.strategy = StandardSearchStrategy()
+
+ # For backward compatibility
self.questions_by_iteration = {}
- self.citation_handler = CitationHandler(self.model)
self.progress_callback = None
self.all_links_of_system = list()
- # Log the specific model and search engine for debugging
- model_name = getattr(settings.llm, "model", "unknown")
- search_tool = getattr(settings.search, "tool", "unknown")
- logger.info(f"AdvancedSearchSystem initialized with LLM model: {model_name}")
-
- # Get search engine type for better logging
- search_engine_type = "None"
- if self.search is not None:
- search_engine_type = type(self.search).__name__
-
- logger.info(
- f"AdvancedSearchSystem using search engine: {search_tool} (Type: {search_engine_type})"
- )
-
- # Check if search is available, log warning if not
- if self.search is None:
- logger.info(
- "WARNING: Search system initialized with no search engine! Research will not be effective."
- )
- self._update_progress(
- "WARNING: No search engine available",
- None,
- {"error": "No search engine configured properly"},
- )
+ # Configure the strategy with our attributes
+ if hasattr(self, "progress_callback") and self.progress_callback:
+ self.strategy.set_progress_callback(self.progress_callback)
def set_progress_callback(self, callback: Callable[[str, int, dict], None]) -> None:
- """Set a callback function to receive progress updates.
-
- Args:
- callback: Function that takes (message, progress_percent, metadata)
- """
+ """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.
-
- Args:
- message: Description of the current progress state
- progress_percent: Progress percentage (0-100), if applicable
- metadata: Additional data about the progress state
- """
- if self.progress_callback:
- self.progress_callback(message, progress_percent, metadata or {})
-
- def _get_follow_up_questions(self, current_knowledge: str, query: str) -> List[str]:
- now = datetime.now()
- current_time = now.strftime("%Y-%m-%d")
-
- self._update_progress(
- "Generating follow-up questions...",
- None,
- {"iteration": len(self.questions_by_iteration)},
- )
-
- if self.questions_by_iteration:
- prompt = f"""Critically reflect current knowledge (e.g., timeliness), what {self.questions_per_iteration} high-quality internet search questions remain unanswered to exactly answer the query?
- Query: {query}
- Today: {current_time}
- Past questions: {str(self.questions_by_iteration)}
- Knowledge: {current_knowledge}
- Include questions that critically reflect current knowledge.
- \n\n\nFormat: One question per line, e.g. \n Q: question1 \n Q: question2\n\n"""
- else:
- prompt = f" You will have follow up questions. First, identify if your knowledge is outdated (high chance). Today: {current_time}. Generate {self.questions_per_iteration} high-quality internet search questions to exactly answer: {query}\n\n\nFormat: One question per line, e.g. \n Q: question1 \n Q: question2\n\n"
-
- response = self.model.invoke(prompt)
- questions = [
- q.replace("Q:", "").strip()
- for q in remove_think_tags(response.content).split("\n")
- if q.strip().startswith("Q:")
- ][: self.questions_per_iteration]
-
- self._update_progress(
- f"Generated {len(questions)} follow-up questions",
- None,
- {"questions": questions},
- )
-
- return questions
-
- def _compress_knowledge(
- self, current_knowledge: str, query: str, section_links
- ) -> List[str]:
- self._update_progress("Compressing and summarizing knowledge...", None)
-
- formatted_links = format_links(links=section_links)
- if self.questions_by_iteration:
- prompt = f"""First provide a high-quality 1 page explanation with IEEE Referencing Style e.g. [1,2]. Never make up sources. Than provide a exact high-quality one sentence-long answer to the query.
-
- Knowledge: {current_knowledge}
- Query: {query}
- I will append following text to your output for the sources (dont repeat it):\n\n {formatted_links}"""
- response = self.model.invoke(prompt)
-
- self._update_progress("Knowledge compression complete", None)
- response = remove_think_tags(response.content)
- response = str(response) # + "\n\n" + str(formatted_links)
-
- return response
+ if hasattr(self, "strategy"):
+ self.strategy.set_progress_callback(callback)
def analyze_topic(self, query: str) -> Dict:
- logger.info(f"Starting research on topic: {query}")
-
- findings = []
- current_knowledge = ""
- iteration = 0
- total_iterations = self.max_iterations
- section_links = list()
-
- self._update_progress(
- "Initializing research system",
- 5,
- {"phase": "init", "iterations_planned": total_iterations},
- )
-
- # Check if search engine is available
- if self.search is None:
- error_msg = (
- "Error: No search engine available. Please check your configuration."
- )
- self._update_progress(
- error_msg,
- 100,
- {
- "phase": "error",
- "error": "No search engine available",
- "status": "failed",
- },
- )
- return {
- "findings": [],
- "iterations": 0,
- "questions": {},
- "formatted_findings": "Error: Unable to conduct research without a search engine.",
- "current_knowledge": "",
- "error": error_msg,
- }
-
- while iteration < self.max_iterations:
- iteration_progress_base = (iteration / total_iterations) * 100
- self._update_progress(
- f"Starting iteration {iteration + 1} of {total_iterations}",
- int(iteration_progress_base),
- {"phase": "iteration_start", "iteration": iteration + 1},
- )
-
- # Generate questions for this iteration
- questions = self._get_follow_up_questions(current_knowledge, query)
- self.questions_by_iteration[iteration] = questions
- logger.info(f"Generated questions: {questions}")
- question_count = len(questions)
- for q_idx, question in enumerate(questions):
- question_progress_base = iteration_progress_base + (
- ((q_idx + 1) / question_count) * (100 / total_iterations) * 0.5
- )
-
- self._update_progress(
- f"Searching for: {question}",
- int(question_progress_base),
- {
- "phase": "search",
- "iteration": iteration + 1,
- "question_index": q_idx + 1,
- },
- )
-
- try:
- if self.search is None:
- self._update_progress(
- f"Search engine unavailable, skipping search for: {question}",
- int(question_progress_base + 2),
- {
- "phase": "search_error",
- "error": "No search engine available",
- },
- )
- search_results = []
- else:
- search_results = self.search.run(question)
- except Exception as e:
- error_msg = f"Error during search: {str(e)}"
- logger.info(f"SEARCH ERROR: {error_msg}")
- self._update_progress(
- error_msg,
- int(question_progress_base + 2),
- {"phase": "search_error", "error": str(e)},
- )
- search_results = []
-
- if search_results is None:
- self._update_progress(
- f"No search results found for question: {question}",
- int(question_progress_base + 2),
- {"phase": "search_complete", "result_count": 0},
- )
- search_results = [] # Initialize to empty list instead of None
- continue
-
- self._update_progress(
- f"Found {len(search_results)} results for question: {question}",
- int(question_progress_base + 2),
- {"phase": "search_complete", "result_count": len(search_results)},
- )
-
- logger.info(f"len search: {len(search_results)}")
-
- if len(search_results) == 0:
- continue
-
- self._update_progress(
- f"Analyzing results for: {question}",
- int(question_progress_base + 5),
- {"phase": "analysis"},
- )
-
- try:
- result = self.citation_handler.analyze_followup(
- question,
- search_results,
- current_knowledge,
- nr_of_links=len(self.all_links_of_system),
- )
- links = extract_links_from_search_results(search_results)
- self.all_links_of_system.extend(links)
- section_links.extend(links)
- formatted_links = ""
- if links:
- formatted_links = format_links(links=links)
-
- logger.info(f"Generated questions: {formatted_links}")
- if result is not None:
- results_with_links = str(result["content"])
- findings.append(
- {
- "phase": f"Follow-up {iteration}.{questions.index(question) + 1}",
- "content": results_with_links,
- "question": question,
- "search_results": search_results,
- "documents": result["documents"],
- }
- )
-
- if settings.general.knowledge_accumulation != str(
- KnowledgeAccumulationApproach.NO_KNOWLEDGE.value
- ):
- current_knowledge = (
- current_knowledge
- + "\n\n\n New: \n"
- + results_with_links
- )
-
- if settings.general.knowledge_accumulation == str(
- KnowledgeAccumulationApproach.QUESTION.value
- ):
- logger.info("Compressing knowledge")
- self._update_progress(
- f"Compress Knowledge for: {question}",
- int(question_progress_base + 0),
- {"phase": "analysis"},
- )
- current_knowledge = self._compress_knowledge(
- current_knowledge, query, section_links
- )
-
- self._update_progress(
- f"Analysis complete for question: {question}",
- int(question_progress_base + 10),
- {"phase": "analysis_complete"},
- )
- except Exception as e:
- error_msg = f"Error analyzing results: {str(e)}"
- logger.info(f"ANALYSIS ERROR: {error_msg}")
- self._update_progress(
- error_msg,
- int(question_progress_base + 10),
- {"phase": "analysis_error", "error": str(e)},
- )
- iteration += 1
-
- self._update_progress(
- f"Compressing knowledge after iteration {iteration}",
- int((iteration / total_iterations) * 100 - 5),
- {"phase": "knowledge_compression"},
- )
- logger.info(str(iteration))
- logger.info(settings.general.knowledge_accumulation)
- logger.info(str(KnowledgeAccumulationApproach.ITERATION.value))
- if (
- settings.general.knowledge_accumulation
- == KnowledgeAccumulationApproach.ITERATION.value
- ):
- try:
- logger.info("ITERATION - Compressing Knowledge")
- current_knowledge = self._compress_knowledge(
- current_knowledge, query, section_links
- )
- logger.info("FINISHED ITERATION - Compressing Knowledge")
- except Exception as e:
- error_msg = f"Error compressing knowledge: {str(e)}"
- logger.info(f"COMPRESSION ERROR: {error_msg}")
- self._update_progress(
- error_msg,
- int((iteration / total_iterations) * 100 - 3),
- {"phase": "compression_error", "error": str(e)},
- )
-
- self._update_progress(
- f"Iteration {iteration} complete",
- int((iteration / total_iterations) * 100),
- {"phase": "iteration_complete", "iteration": iteration},
- )
-
- try:
- formatted_findings = self._save_findings(
- findings, current_knowledge, query
- )
- except Exception as e:
- error_msg = f"Error saving findings: {str(e)}"
- logger.info(f"SAVE ERROR: {error_msg}")
- self._update_progress(
- error_msg,
- int((iteration / total_iterations) * 100),
- {"phase": "save_error", "error": str(e)},
- )
- formatted_findings = "Error: Could not format findings due to an error."
-
- self._update_progress("Research complete", 95, {"phase": "complete"})
-
- return {
- "findings": findings,
- "iterations": iteration,
- "questions": self.questions_by_iteration,
- "formatted_findings": formatted_findings,
- "current_knowledge": current_knowledge,
- }
-
- def _save_findings(self, findings: List[Dict], current_knowledge: str, query: str):
- logger.info("Saving findings ...")
- self._update_progress("Saving research findings...", None)
-
- formatted_findings = format_findings_to_text(
- findings, current_knowledge, self.questions_by_iteration
- )
- safe_query = "".join(x for x in query if x.isalnum() or x in [" ", "-", "_"])[
- :50
- ]
- safe_query = safe_query.replace(" ", "_").lower()
+ """Analyze a topic using the current strategy."""
+ # Use the strategy to analyze the topic
+ result = self.strategy.analyze_topic(query)
- output_dir = f"{get_config_dir()}/research_outputs"
- if not os.path.exists(output_dir):
- os.makedirs(output_dir)
+ # Update our attributes for backward compatibility
+ if hasattr(self.strategy, "questions_by_iteration"):
+ self.questions_by_iteration = self.strategy.questions_by_iteration
- filename = os.path.join(output_dir, f"formatted_output_{safe_query}.txt")
+ if hasattr(self.strategy, "all_links_of_system"):
+ self.all_links_of_system = self.strategy.all_links_of_system
- with open(filename, "w", encoding="utf-8") as text_file:
- text_file.write(formatted_findings)
- logger.info("Saved findings")
- self._update_progress("Research findings saved", None, {"filename": filename})
- return formatted_findings
+ return result
diff --git a/src/local_deep_research/search_system/strategies/standard_strategy.py b/src/local_deep_research/search_system/strategies/standard_strategy.py
index 013a8fb58b..9aaf4f1dc4 100644
--- a/src/local_deep_research/search_system/strategies/standard_strategy.py
+++ b/src/local_deep_research/search_system/strategies/standard_strategy.py
@@ -1,39 +1,21 @@
-from typing import Dict, List, Optional, Callable
-from datetime import datetime
import logging
-import os
+from typing import Callable, Dict
-from .base_strategy import BaseSearchStrategy
-from ..services.question_service import QuestionService
-from ..services.knowledge_service import KnowledgeService
-from ..repositories.findings_repository import FindingsRepository
from ...citation_handler import CitationHandler
-from ...config import settings, get_llm, get_search
-from ...utilties.search_utilities import extract_links_from_search_results
+from ...config import get_llm, get_search, settings
from ...utilties.enums import KnowledgeAccumulationApproach
-
-logger = logging.getLogger(__name__)
-
-# Update standard_strategy.py with full implementation
-from typing import Dict, List, Optional, Callable
-from datetime import datetime
-import logging
-import os
-
-from .base_strategy import BaseSearchStrategy
-from ..questions.standard_question import StandardQuestionGenerator
+from ...utilties.search_utilities import extract_links_from_search_results
from ..knowledge.standard_knowledge import StandardKnowledgeManager
+from ..questions.standard_question import StandardQuestionGenerator
from ..repositories.findings_repository import FindingsRepository
-from ...citation_handler import CitationHandler
-from ...config import settings, get_llm, get_search
-from ...utilties.search_utilities import extract_links_from_search_results
-from ...utilties.enums import KnowledgeAccumulationApproach
+from .base_strategy import BaseSearchStrategy
logger = logging.getLogger(__name__)
+
class StandardSearchStrategy(BaseSearchStrategy):
"""Standard iterative search strategy that generates follow-up questions."""
-
+
def __init__(self):
self.search = get_search()
self.model = get_llm()
@@ -44,118 +26,157 @@ class StandardSearchStrategy(BaseSearchStrategy):
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)
+
+ # Initialize directly with the specialized components
+ self.question_generator = StandardQuestionGenerator(self.model)
+ self.knowledge_manager = StandardKnowledgeManager(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:
+
+ def _update_progress(
+ self, message: str, progress_percent: int = None, metadata: dict = None
+ ) -> None:
"""Send a progress update via the callback if available."""
if self.progress_callback:
self.progress_callback(message, progress_percent, metadata or {})
-
+
def analyze_topic(self, query: str) -> Dict:
"""Standard implementation of the topic analysis process."""
logger.info(f"Starting research on topic: {query}")
-
+
findings = []
current_knowledge = ""
iteration = 0
total_iterations = self.max_iterations
section_links = list()
-
- self._update_progress("Initializing research system", 5, {
- "phase": "init",
- "iterations_planned": total_iterations
- })
-
+
+ self._update_progress(
+ "Initializing research system",
+ 5,
+ {"phase": "init", "iterations_planned": total_iterations},
+ )
+
# Check if search engine is available
if self.search is None:
- error_msg = "Error: No search engine available. Please check your configuration."
- self._update_progress(error_msg, 100, {
- "phase": "error",
- "error": "No search engine available",
- "status": "failed"
- })
+ 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
+ "error": error_msg,
}
while iteration < self.max_iterations:
iteration_progress_base = (iteration / total_iterations) * 100
- self._update_progress(f"Starting iteration {iteration + 1} of {total_iterations}",
- int(iteration_progress_base),
- {"phase": "iteration_start", "iteration": iteration + 1})
-
- # Generate questions for this iteration using the question service
- questions = self.question_service.get_follow_up_questions(
- current_knowledge, query, self.questions_per_iteration, self.questions_by_iteration)
-
+ self._update_progress(
+ f"Starting iteration {iteration + 1} of {total_iterations}",
+ int(iteration_progress_base),
+ {"phase": "iteration_start", "iteration": iteration + 1},
+ )
+
+ # Generate questions for this iteration using the question generator
+ questions = self.question_generator.generate_questions(
+ current_knowledge=current_knowledge,
+ query=query,
+ questions_per_iteration=self.questions_per_iteration,
+ questions_by_iteration=self.questions_by_iteration,
+ )
+
self.questions_by_iteration[iteration] = questions
logger.info(f"Generated questions: {questions}")
-
+
question_count = len(questions)
for q_idx, question in enumerate(questions):
- question_progress_base = iteration_progress_base + (((q_idx+1) / question_count) * (100/total_iterations) * 0.5)
-
- self._update_progress(f"Searching for: {question}",
- int(question_progress_base),
- {"phase": "search", "iteration": iteration + 1, "question_index": q_idx + 1})
-
+ question_progress_base = iteration_progress_base + (
+ ((q_idx + 1) / question_count) * (100 / total_iterations) * 0.5
+ )
+
+ self._update_progress(
+ f"Searching for: {question}",
+ int(question_progress_base),
+ {
+ "phase": "search",
+ "iteration": iteration + 1,
+ "question_index": q_idx + 1,
+ },
+ )
+
try:
if self.search is None:
- self._update_progress(f"Search engine unavailable, skipping search for: {question}",
- int(question_progress_base + 2),
- {"phase": "search_error", "error": "No search engine available"})
+ self._update_progress(
+ f"Search engine unavailable, skipping search for: {question}",
+ int(question_progress_base + 2),
+ {
+ "phase": "search_error",
+ "error": "No search engine available",
+ },
+ )
search_results = []
else:
search_results = self.search.run(question)
except Exception as e:
error_msg = f"Error during search: {str(e)}"
logger.info(f"SEARCH ERROR: {error_msg}")
- self._update_progress(error_msg,
- int(question_progress_base + 2),
- {"phase": "search_error", "error": str(e)})
+ self._update_progress(
+ error_msg,
+ int(question_progress_base + 2),
+ {"phase": "search_error", "error": str(e)},
+ )
search_results = []
-
+
if search_results is None:
- self._update_progress(f"No search results found for question: {question}",
- int(question_progress_base + 2),
- {"phase": "search_complete", "result_count": 0})
+ self._update_progress(
+ f"No search results found for question: {question}",
+ int(question_progress_base + 2),
+ {"phase": "search_complete", "result_count": 0},
+ )
search_results = [] # Initialize to empty list instead of None
continue
-
- self._update_progress(f"Found {len(search_results)} results for question: {question}",
- int(question_progress_base + 2),
- {"phase": "search_complete", "result_count": len(search_results)})
-
+
+ self._update_progress(
+ f"Found {len(search_results)} results for question: {question}",
+ int(question_progress_base + 2),
+ {"phase": "search_complete", "result_count": len(search_results)},
+ )
+
logger.info(f"len search: {len(search_results)}")
-
+
if len(search_results) == 0:
continue
- self._update_progress(f"Analyzing results for: {question}",
- int(question_progress_base + 5),
- {"phase": "analysis"})
+ self._update_progress(
+ f"Analyzing results for: {question}",
+ int(question_progress_base + 5),
+ {"phase": "analysis"},
+ )
try:
result = self.citation_handler.analyze_followup(
- question, search_results, current_knowledge, nr_of_links=len(self.all_links_of_system)
+ question,
+ search_results,
+ current_knowledge,
+ nr_of_links=len(self.all_links_of_system),
)
links = extract_links_from_search_results(search_results)
self.all_links_of_system.extend(links)
section_links.extend(links)
-
+
if result is not None:
results_with_links = str(result["content"])
findings.append(
@@ -168,64 +189,96 @@ class StandardSearchStrategy(BaseSearchStrategy):
}
)
- if settings.general.knowledge_accumulation != str(KnowledgeAccumulationApproach.NO_KNOWLEDGE.value):
- current_knowledge = current_knowledge + "\n\n\n New: \n" + results_with_links
-
- if settings.general.knowledge_accumulation == str(KnowledgeAccumulationApproach.QUESTION.value):
+ if settings.general.knowledge_accumulation != str(
+ KnowledgeAccumulationApproach.NO_KNOWLEDGE.value
+ ):
+ current_knowledge = (
+ current_knowledge
+ + "\n\n\n New: \n"
+ + results_with_links
+ )
+
+ if settings.general.knowledge_accumulation == str(
+ KnowledgeAccumulationApproach.QUESTION.value
+ ):
logger.info("Compressing knowledge")
- self._update_progress(f"Compress Knowledge for: {question}",
- int(question_progress_base + 0),
- {"phase": "analysis"})
- current_knowledge = self.knowledge_service.compress_knowledge(current_knowledge, query, section_links)
-
- self._update_progress(f"Analysis complete for question: {question}",
- int(question_progress_base + 10),
- {"phase": "analysis_complete"})
+ self._update_progress(
+ f"Compress Knowledge for: {question}",
+ int(question_progress_base + 0),
+ {"phase": "analysis"},
+ )
+ current_knowledge = (
+ self.knowledge_manager.compress_knowledge(
+ current_knowledge, query, section_links
+ )
+ )
+
+ self._update_progress(
+ f"Analysis complete for question: {question}",
+ int(question_progress_base + 10),
+ {"phase": "analysis_complete"},
+ )
except Exception as e:
error_msg = f"Error analyzing results: {str(e)}"
logger.info(f"ANALYSIS ERROR: {error_msg}")
- self._update_progress(error_msg,
- int(question_progress_base + 10),
- {"phase": "analysis_error", "error": str(e)})
+ self._update_progress(
+ error_msg,
+ int(question_progress_base + 10),
+ {"phase": "analysis_error", "error": str(e)},
+ )
iteration += 1
-
- self._update_progress(f"Compressing knowledge after iteration {iteration}",
- int((iteration / total_iterations) * 100 - 5),
- {"phase": "knowledge_compression"})
-
- if settings.general.knowledge_accumulation == KnowledgeAccumulationApproach.ITERATION.value:
+
+ self._update_progress(
+ f"Compressing knowledge after iteration {iteration}",
+ int((iteration / total_iterations) * 100 - 5),
+ {"phase": "knowledge_compression"},
+ )
+
+ if (
+ settings.general.knowledge_accumulation
+ == KnowledgeAccumulationApproach.ITERATION.value
+ ):
try:
logger.info("ITERATION - Compressing Knowledge")
- current_knowledge = self.knowledge_service.compress_knowledge(current_knowledge, query, section_links)
+ current_knowledge = self.knowledge_manager.compress_knowledge(
+ current_knowledge, query, section_links
+ )
logger.info("FINISHED ITERATION - Compressing Knowledge")
except Exception as e:
error_msg = f"Error compressing knowledge: {str(e)}"
logger.info(f"COMPRESSION ERROR: {error_msg}")
- self._update_progress(error_msg,
- int((iteration / total_iterations) * 100 - 3),
- {"phase": "compression_error", "error": str(e)})
-
- self._update_progress(f"Iteration {iteration} complete",
- int((iteration / total_iterations) * 100),
- {"phase": "iteration_complete", "iteration": iteration})
-
+ self._update_progress(
+ error_msg,
+ int((iteration / total_iterations) * 100 - 3),
+ {"phase": "compression_error", "error": str(e)},
+ )
+
+ self._update_progress(
+ f"Iteration {iteration} complete",
+ int((iteration / total_iterations) * 100),
+ {"phase": "iteration_complete", "iteration": iteration},
+ )
+
try:
formatted_findings = self.findings_repository.save_findings(
- findings, current_knowledge, self.questions_by_iteration, query)
+ findings, current_knowledge, self.questions_by_iteration, query
+ )
except Exception as e:
error_msg = f"Error saving findings: {str(e)}"
logger.info(f"SAVE ERROR: {error_msg}")
- self._update_progress(error_msg,
- int((iteration / total_iterations) * 100),
- {"phase": "save_error", "error": str(e)})
+ self._update_progress(
+ error_msg,
+ int((iteration / total_iterations) * 100),
+ {"phase": "save_error", "error": str(e)},
+ )
formatted_findings = "Error: Could not format findings due to an error."
self._update_progress("Research complete", 95, {"phase": "complete"})
-
+
return {
"findings": findings,
"iterations": iteration,
"questions": self.questions_by_iteration,
"formatted_findings": formatted_findings,
- "current_knowledge": current_knowledge
- }
\ No newline at end of file
+ "current_knowledge": current_knowledge,
+ }