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 search strategies

LearningCircuitdbe7c0b48a93
diff --git a/src/local_deep_research/advanced_search_system/findings/repository.py b/src/local_deep_research/advanced_search_system/findings/repository.py
index 3d2b7fbdbb..647c4e0038 100644
--- a/src/local_deep_research/advanced_search_system/findings/repository.py
+++ b/src/local_deep_research/advanced_search_system/findings/repository.py
@@ -3,7 +3,7 @@ Findings repository for managing research findings.
"""
import logging
-from typing import Dict, List
+from typing import Dict, List, Union
from langchain_core.documents import Document
@@ -45,20 +45,42 @@ class FindingsRepository(BaseFindingsRepository):
self.documents: List[Document] = []
self.questions_by_iteration: Dict[int, List[str]] = {}
- def add_finding(self, query: str, finding: Dict) -> None:
+ def add_finding(self, query: str, finding: Union[Dict, str]) -> None:
"""Add a finding for a query."""
if query not in self.findings:
self.findings[query] = []
- self.findings[query].append(finding)
+
+ # Convert to dictionary if it's a string
+ if isinstance(finding, str):
+ finding_dict = {
+ "phase": "Synthesis",
+ "content": finding,
+ "question": query,
+ "search_results": [],
+ "documents": [],
+ }
+ self.findings[query].append(finding_dict)
+ else:
+ # It's already a dictionary
+ self.findings[query].append(finding)
+
+ # Store raw synthesized content if it's the final synthesis
+ # Only check for phase if it's a dictionary
+ if isinstance(finding, dict) and finding.get("phase") == "Final synthesis":
+ self.findings[query + "_synthesis"] = [
+ {
+ "phase": "Synthesis",
+ "content": finding.get("content", ""),
+ "question": query,
+ "search_results": [],
+ "documents": [],
+ }
+ ]
+
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.
@@ -146,34 +168,82 @@ class FindingsRepository(BaseFindingsRepository):
self,
query: str,
sub_queries: List[str],
- findings: List[str],
- accumulated_knowledge: str,
- old_formatting=True,
+ findings: List[Union[Dict, str]],
+ accumulated_knowledge: str = None,
+ old_formatting: bool = False,
) -> 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)
- findings: List of findings strings from previous steps.
+ sub_queries: List of sub-queries (for context)
+ findings: List of findings strings or dictionaries from previous steps
+ accumulated_knowledge: Optional pre-existing knowledge to incorporate
+ old_formatting: Whether to use the old formatting approach
Returns:
str: Synthesized final answer content.
"""
+ logger.info(f"synthesize_findings called with query: '{query}'")
+ logger.info(
+ f"sub_queries type: {type(sub_queries)}, length: {len(sub_queries)}"
+ )
+ logger.info(f"findings type: {type(findings)}, length: {len(findings)}")
+
+ # Use provided accumulated_knowledge or join findings if it's None
+ if accumulated_knowledge is None:
+ # Convert findings to text if they are dictionaries
+ finding_texts = []
+ for item in findings:
+ if isinstance(item, dict) and "content" in item:
+ finding_texts.append(item["content"])
+ elif isinstance(item, str):
+ finding_texts.append(item)
+ accumulated_knowledge = "\n\n".join(finding_texts) if finding_texts else ""
+
+ if findings:
+ logger.info(f"first finding type: {type(findings[0])}")
+ if isinstance(findings[0], dict):
+ logger.info(
+ f"first finding keys: {list(findings[0].keys()) if hasattr(findings[0], 'keys') else 'No keys'}"
+ )
+ if "content" in findings[0]:
+ logger.info(
+ f"first finding content type: {type(findings[0]['content'])}"
+ )
+ elif isinstance(findings[0], str):
+ logger.info(f"first finding string length: {len(findings[0])}")
+ logger.info(f"first finding string preview: {findings[0][:100]}...")
+
if old_formatting:
+ # Convert findings list if it contains strings instead of dictionaries
+ findings_list = []
+ for i, item in enumerate(findings):
+ if isinstance(item, str):
+ findings_list.append({"phase": f"Finding {i + 1}", "content": item})
+ elif isinstance(item, dict):
+ findings_list.append(item)
+
return format_findings(
- findings_list=findings,
+ findings_list=findings_list,
synthesized_content=accumulated_knowledge,
questions_by_iteration=self.questions_by_iteration,
)
-
try:
- # Convert findings list to accumulated knowledge string
- current_knowledge = "\n\n".join(findings) if findings else ""
+ # Extract finding content texts for the prompt
+ finding_texts = []
+ for item in findings:
+ if isinstance(item, dict) and "content" in item:
+ finding_texts.append(item["content"])
+ elif isinstance(item, str):
+ finding_texts.append(item)
+
+ # Use finding_texts for the prompt
+ current_knowledge = "\n\n".join(finding_texts) if finding_texts else ""
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.
+Format the response with clear sections, citations, and a concise summary, following the structure provided below.
Original Query: {query}
@@ -183,32 +253,17 @@ Accumulated 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]
+Generate a well-structured, concise answer that:
+1. Starts with a clear explanation of the most important points
+2. Organizes information into logical sections with headers if needed
+3. Includes specific, numbered citations like [1], [2], etc. for important claims
+4. Maintains logical flow and prioritizes important information over minor details
+5. Highlights key insights and actionable recommendations
+6. Uses bullet points for lists of techniques or approaches
+7. Avoids repetition and unnecessary detail
+
+Format your response in a clean, succinct style that prioritizes readability while maintaining depth of information.
+Use numbered citations [1], [2], etc. for important sources - these will be linked to the actual sources after generation.
"""
logger.info(
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
index d49b45ad10..4866ef612b 100644
--- a/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py
@@ -165,7 +165,7 @@ Initial Search Results:
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}",
+ f"Processing sub-query {i} of {total_subqueries}: {sub_query}",
int(progress_base),
{"phase": "subquery", "subquery_index": i},
)
@@ -182,7 +182,7 @@ Initial Search Results:
sub_results = []
else:
self._update_progress(
- f"Found {len(sub_results)} results for sub-query",
+ f"Found {len(sub_results)} results for sub-query: {sub_query}",
int(progress_base + 2),
{
"phase": "search_complete",
@@ -250,9 +250,9 @@ Initial Search Results:
# Synthesize findings into a final answer
final_answer = self.findings_repository.synthesize_findings(
- query,
- sub_queries,
- finding_contents,
+ query=query,
+ sub_queries=sub_queries,
+ findings=finding_contents,
accumulated_knowledge=current_knowledge,
)
@@ -273,6 +273,9 @@ Initial Search Results:
current_knowledge = final_answer
except Exception as e:
logger.error(f"Error synthesizing final answer: {str(e)}")
+ import traceback
+
+ print(traceback.format_exc())
# If synthesis fails, keep existing knowledge
final_answer = current_knowledge # Fallback to pre-synthesis knowledge
@@ -294,9 +297,13 @@ Initial Search Results:
)
try:
- # Format the findings using the repository's formatting method
- formatted_findings = self.findings_repository.format_findings_to_text(
- findings, final_answer
+ # Get a formatted version with search questions and sources included
+ formatted_findings = self.findings_repository.synthesize_findings(
+ query=query,
+ sub_queries=sub_queries,
+ findings=findings, # Pass full findings list
+ accumulated_knowledge=final_answer,
+ old_formatting=True, # Use old_formatting to format with questions and sources
)
except Exception as e:
logger.error(f"Error formatting final findings: {str(e)}")
diff --git a/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py b/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
index 8c2a2c654f..9fc44c59d8 100644
--- a/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
@@ -274,8 +274,9 @@ class StandardSearchStrategy(BaseSearchStrategy):
formatted_findings = self.findings_repository.synthesize_findings(
query,
finding_contents,
- finding_contents,
+ findings, # Pass the full findings list with search results
accumulated_knowledge=current_knowledge,
+ old_formatting=True, # Use old_formatting to format with questions and sources
)
# Add the formatted findings to the repository
self.findings_repository.add_finding(query, formatted_findings)
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index 1be4caf42f..bbc8027a77 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -12,7 +12,7 @@ logger = logging.getLogger(__name__)
class AdvancedSearchSystem:
- def __init__(self, strategy_name: str = "standard"):
+ def __init__(self, strategy_name: str = "iterdrag"):
"""
Initialize the advanced search system.
@@ -25,12 +25,22 @@ class AdvancedSearchSystem:
self.max_iterations = settings.search.iterations
self.questions_per_iteration = settings.search.questions_per_iteration
+ # Log the strategy name that's being used
+ logger.info(
+ f"Initializing AdvancedSearchSystem with strategy_name='{strategy_name}'"
+ )
+
# Initialize strategy based on name
if strategy_name.lower() == "iterdrag":
+ logger.info("Creating IterDRAGStrategy instance")
self.strategy = IterDRAGStrategy(model=self.model, search=self.search)
else:
+ logger.info("Creating StandardSearchStrategy instance")
self.strategy = StandardSearchStrategy(model=self.model, search=self.search)
+ # Log the actual strategy class
+ logger.info(f"Created strategy of type: {type(self.strategy).__name__}")
+
# For backward compatibility
self.questions_by_iteration = {}
self.progress_callback = None
diff --git a/src/local_deep_research/utilties/search_utilities.py b/src/local_deep_research/utilties/search_utilities.py
index 71a0f84c95..71bb3e1a35 100644
--- a/src/local_deep_research/utilties/search_utilities.py
+++ b/src/local_deep_research/utilties/search_utilities.py
@@ -63,8 +63,35 @@ def format_findings(
)
formatted_text = ""
+ # Extract all sources from findings
+ all_links = []
+ for finding in findings_list:
+ search_results = finding.get("search_results", [])
+ if search_results:
+ try:
+ links = extract_links_from_search_results(search_results)
+ all_links.extend(links)
+ except Exception as link_err:
+ logger.error(f"Error processing search results/links: {link_err}")
+
# Start with the synthesized content (passed as synthesized_content)
formatted_text += f"{synthesized_content}\n\n"
+
+ # Add sources section after synthesized content if sources exist
+ if all_links:
+ formatted_text += "SOURCES:\n"
+ formatted_text += "=" * 80 + "\n\n"
+ seen_urls = set()
+ link_counter = 1
+ for link in all_links:
+ url = link.get("url")
+ title = link.get("title", "Untitled")
+ if url and url not in seen_urls:
+ formatted_text += f"[{link_counter}] {title}\n URL: {url}\n\n"
+ seen_urls.add(url)
+ link_counter += 1
+ formatted_text += "\n"
+
# formatted_text += "=" * 80 + "\n\n" # Separator after synthesized content
# Add Search Questions by Iteration section
@@ -82,7 +109,6 @@ def format_findings(
# 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):
@@ -97,6 +123,7 @@ def format_findings(
formatted_text += f"PHASE: {phase}\n"
formatted_text += f"{'=' * 80}\n\n"
+ question_displayed = False
# If this is a follow-up phase, try to show the corresponding question
if isinstance(phase, str) and phase.startswith("Follow-up"):
try:
@@ -111,6 +138,7 @@ def format_findings(
< len(questions_by_iteration[iteration])
):
formatted_text += f"SEARCH QUESTION:\n{questions_by_iteration[iteration][question_index]}\n\n"
+ question_displayed = True
else:
logger.warning(
f"Could not find matching question for phase: {phase}"
@@ -123,6 +151,29 @@ def format_findings(
logger.warning(
f"Could not parse iteration/index from phase: {phase}"
)
+ # Handle Sub-query phases from IterDRAG strategy
+ elif isinstance(phase, str) and phase.startswith("Sub-query"):
+ try:
+ # Extract the index number from "Sub-query X"
+ query_index = int(phase.replace("Sub-query ", "")) - 1
+ # In IterDRAG, sub-queries are stored in iteration 0
+ if 0 in questions_by_iteration and query_index < len(
+ questions_by_iteration[0]
+ ):
+ formatted_text += f"SEARCH QUESTION:\n{questions_by_iteration[0][query_index]}\n\n"
+ question_displayed = True
+ else:
+ logger.warning(
+ f"Could not find matching question for phase: {phase}"
+ )
+ except ValueError:
+ logger.warning(
+ f"Could not parse question index from phase: {phase}"
+ )
+
+ # If the question is in the finding itself, display it
+ if not question_displayed and "question" in finding and finding["question"]:
+ formatted_text += f"SEARCH QUESTION:\n{finding['question']}\n\n"
# Content
formatted_text += f"CONTENT:\n{content}\n\n"
@@ -134,7 +185,6 @@ def format_findings(
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}"
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 623dc09762..2e69ded36b 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -10,6 +10,9 @@ from ...config.llm_config import get_llm
from ...config.search_config import get_search
from ...report_generator import IntegratedReportGenerator
from ...search_system import AdvancedSearchSystem
+from ...utilties.search_utilities import (
+ extract_links_from_search_results,
+)
from ..models.database import add_log_to_db, calculate_duration, get_db_connection
from .socket_service import emit_to_subscribers # Keep if needed directly
@@ -379,7 +382,43 @@ def run_research_process(
)
try:
+ # Get the synthesized content from the LLM directly
clean_markdown = raw_formatted_findings
+
+ # Extract all sources from findings to add them to the summary
+ all_links = []
+ for finding in results.get("findings", []):
+ search_results = finding.get("search_results", [])
+ if search_results:
+ try:
+ links = extract_links_from_search_results(
+ search_results
+ )
+ all_links.extend(links)
+ except Exception as link_err:
+ logger.error(
+ f"Error processing search results/links: {link_err}"
+ )
+
+ # Format a sources section if we have links
+ sources_section = ""
+ if all_links:
+ sources_section = "\n\nSOURCES:\n" + "=" * 80 + "\n\n"
+ seen_urls = set()
+ link_counter = 1
+ for link in all_links:
+ url = link.get("url")
+ title = link.get("title", "Untitled")
+ if url and url not in seen_urls:
+ sources_section += (
+ f"[{link_counter}] {title}\n URL: {url}\n\n"
+ )
+ seen_urls.add(url)
+ link_counter += 1
+
+ # Add sources section to the markdown
+ clean_markdown = clean_markdown + sources_section
+
logger.info(
f"Successfully converted to clean markdown of length: {len(clean_markdown)}"
)
diff --git a/src/local_deep_research/web/services/research_service.py.bak b/src/local_deep_research/web/services/research_service.py.bak
new file mode 100644
index 0000000000..1a6048a452
--- /dev/null
+++ b/src/local_deep_research/web/services/research_service.py.bak
@@ -0,0 +1,811 @@
+import json
+import logging
+import os
+import threading
+import traceback
+from datetime import datetime
+
+from ...config.config_files import settings
+from ...config.llm_config import get_llm
+from ...config.search_config import get_search
+from ...report_generator import IntegratedReportGenerator
+from ...search_system import AdvancedSearchSystem
+from ..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__)
+
+# Output directory for research results
+OUTPUT_DIR = "research_outputs"
+
+
+def start_research_process(
+ research_id,
+ query,
+ mode,
+ active_research,
+ termination_flags,
+ run_research_callback,
+ **kwargs,
+):
+ """
+ Start a research process in a background thread.
+
+ Args:
+ research_id: The ID of the research
+ query: The research query
+ mode: The research mode (quick/detailed)
+ active_research: Dictionary of active research processes
+ termination_flags: Dictionary of termination flags
+ run_research_callback: The callback function to run the research
+ **kwargs: Additional parameters to pass to the research process (model, search_engine, etc.)
+
+ Returns:
+ threading.Thread: The thread running the research
+ """
+ # Start research process in a background thread
+ thread = threading.Thread(
+ target=run_research_callback,
+ args=(research_id, query, mode, active_research, termination_flags),
+ kwargs=kwargs,
+ )
+ thread.daemon = True
+ thread.start()
+
+ active_research[research_id] = {
+ "thread": thread,
+ "progress": 0,
+ "status": "in_progress",
+ "log": [
+ {
+ "time": datetime.utcnow().isoformat(),
+ "message": "Research started",
+ "progress": 0,
+ }
+ ],
+ "settings": kwargs, # Store settings for reference
+ }
+
+ return thread
+
+
+def run_research_process(
+ research_id, query, mode, active_research, termination_flags, **kwargs
+):
+ """
+ Run the research process in the background for a given research ID.
+
+ Args:
+ research_id: The ID of the research
+ query: The research query
+ mode: The research mode (quick/detailed)
+ active_research: Dictionary of active research processes
+ termination_flags: Dictionary of termination flags
+ **kwargs: Additional parameters for the research (model, search_engine, etc.)
+ """
+ try:
+ # Check if this research has been terminated before we even start
+ if research_id in termination_flags and termination_flags[research_id]:
+ logger.info(f"Research {research_id} was terminated before starting")
+ cleanup_research_resources(research_id, active_research, termination_flags)
+ return
+
+ logger.info(f"Starting research process for ID {research_id}, query: {query}")
+
+ # Extract key parameters
+ model = kwargs.get("model")
+ search_engine = kwargs.get("search_engine")
+ max_results = kwargs.get("max_results")
+ time_period = kwargs.get("time_period")
+ iterations = kwargs.get("iterations")
+ questions_per_iteration = kwargs.get("questions_per_iteration")
+
+ # Log all parameters for debugging
+ logger.info(
+ f"Research parameters: model={model}, search_engine={search_engine}, max_results={max_results}, time_period={time_period}, iterations={iterations}, questions_per_iteration={questions_per_iteration}"
+ )
+
+ # Set up the AI Context Manager
+ output_dir = os.path.join(OUTPUT_DIR, f"research_{research_id}")
+ os.makedirs(output_dir, exist_ok=True)
+
+ # Set up progress callback
+ def progress_callback(message, progress_percent, metadata):
+ # Frequent termination check
+ if research_id in termination_flags and termination_flags[research_id]:
+ handle_termination(research_id, active_research, termination_flags)
+ raise Exception("Research was terminated by user")
+
+ timestamp = datetime.utcnow().isoformat()
+
+ # Adjust progress based on research mode
+ adjusted_progress = progress_percent
+ if mode == "detailed" and metadata.get("phase") == "output_generation":
+ # For detailed mode, adjust the progress range for output generation
+ adjusted_progress = min(80, progress_percent)
+ elif mode == "detailed" and metadata.get("phase") == "report_generation":
+ # Scale the progress from 80% to 95% for the report generation phase
+ if progress_percent is not None:
+ normalized = progress_percent / 100
+ adjusted_progress = 80 + (normalized * 15)
+ elif mode == "quick" and metadata.get("phase") == "output_generation":
+ # For quick mode, ensure we're at least at 85% during output generation
+ adjusted_progress = max(85, progress_percent)
+ # Map any further progress within output_generation to 85-95% range
+ if progress_percent is not None and progress_percent > 0:
+ normalized = progress_percent / 100
+ adjusted_progress = 85 + (normalized * 10)
+
+ # Don't let progress go backwards
+ if research_id in active_research and adjusted_progress is not None:
+ current_progress = active_research[research_id].get("progress", 0)
+ adjusted_progress = max(current_progress, adjusted_progress)
+
+ log_entry = {
+ "time": timestamp,
+ "message": message,
+ "progress": adjusted_progress,
+ "metadata": metadata,
+ }
+
+ # Update active research record
+ if research_id in active_research:
+ active_research[research_id]["log"].append(log_entry)
+ if adjusted_progress is not None:
+ active_research[research_id]["progress"] = adjusted_progress
+
+ # Determine log type for database storage
+ log_type = "info"
+ if metadata and metadata.get("phase"):
+ phase = metadata.get("phase")
+ if phase in ["complete", "iteration_complete"]:
+ log_type = "milestone"
+ elif phase == "error" or "error" in message.lower():
+ log_type = "error"
+
+ # Save logs to the database
+ add_log_to_db(
+ research_id,
+ message,
+ log_type=log_type,
+ progress=adjusted_progress,
+ metadata=metadata,
+ )
+
+ # Update progress in the research_history table (for backward compatibility)
+ conn = get_db_connection()
+ cursor = conn.cursor()
+
+ # Update the progress and log separately to avoid race conditions
+ if adjusted_progress is not None:
+ cursor.execute(
+ "UPDATE research_history SET progress = ? WHERE id = ?",
+ (adjusted_progress, research_id),
+ )
+
+ # Add the log entry to the progress_log
+ cursor.execute(
+ "SELECT progress_log FROM research_history WHERE id = ?",
+ (research_id,),
+ )
+ log_result = cursor.fetchone()
+
+ if log_result:
+ try:
+ current_log = json.loads(log_result[0])
+ except Exception:
+ current_log = []
+
+ current_log.append(log_entry)
+ cursor.execute(
+ "UPDATE research_history SET progress_log = ? WHERE id = ?",
+ (json.dumps(current_log), research_id),
+ )
+
+ conn.commit()
+ conn.close()
+
+ # Emit a socket event
+ try:
+ # Basic event data
+ event_data = {"message": message, "progress": adjusted_progress}
+
+ # Add log entry in full format for detailed logging on client
+ if metadata:
+ event_data["log_entry"] = log_entry
+
+ emit_to_subscribers("research_progress", research_id, event_data)
+ except Exception as e:
+ logger.error(f"Socket emit error (non-critical): {str(e)}")
+
+ # Function to check termination during long-running operations
+ def check_termination():
+ if research_id in termination_flags and termination_flags[research_id]:
+ handle_termination(research_id, active_research, termination_flags)
+ raise Exception(
+ "Research was terminated by user during long-running operation"
+ )
+ return False # Not terminated
+
+ # Set the progress callback in the system
+ system = AdvancedSearchSystem(strategy_name="standard")
+ system.set_progress_callback(progress_callback)
+
+ # Configure the system with the specified parameters
+ if model or search_engine:
+ # Log that we're overriding system settings
+ logger.info(
+ f"Overriding system settings with: model={model}, search_engine={search_engine}"
+ )
+
+ # Override LLM if specified
+ if model:
+ try:
+ # Temporarily override the model setting
+ original_model = settings.llm.model
+ settings.llm.model = model
+ system.model = get_llm()
+ # Restore original setting
+ settings.llm.model = original_model
+ logger.info(f"Successfully set LLM to: {model}")
+ except Exception as e:
+ logger.error(f"Error setting LLM model to {model}: {str(e)}")
+
+ # Override search engine if specified
+ if search_engine:
+ try:
+ # Temporarily override the search setting
+ original_search = settings.search.tool
+ settings.search.tool = search_engine
+
+ # Set other search parameters if provided
+ if max_results:
+ original_max_results = settings.search.max_results
+ settings.search.max_results = int(max_results)
+
+ if time_period:
+ original_time_period = settings.search.time_period
+ settings.search.time_period = time_period
+
+ if iterations:
+ original_iterations = settings.search.iterations
+ settings.search.iterations = int(iterations)
+ system.max_iterations = int(iterations)
+
+ if questions_per_iteration:
+ original_questions = settings.search.questions_per_iteration
+ settings.search.questions_per_iteration = int(
+ questions_per_iteration
+ )
+ system.questions_per_iteration = int(questions_per_iteration)
+
+ # Create a new search object with these settings
+ system.search = get_search(
+ search_tool=search_engine, llm_instance=system.model
+ )
+
+ # Restore original settings
+ settings.search.tool = original_search
+ if max_results:
+ settings.search.max_results = original_max_results
+ if time_period:
+ settings.search.time_period = original_time_period
+ if iterations:
+ settings.search.iterations = original_iterations
+ if questions_per_iteration:
+ settings.search.questions_per_iteration = original_questions
+
+ logger.info(f"Successfully set search engine to: {search_engine}")
+ except Exception as e:
+ logger.error(
+ f"Error setting search engine to {search_engine}: {str(e)}"
+ )
+
+ # Run the search
+ progress_callback("Starting research process", 5, {"phase": "init"})
+
+ try:
+ results = system.analyze_topic(query)
+ if mode == "quick":
+ progress_callback(
+ "Search complete, preparing to generate summary...",
+ 85,
+ {"phase": "output_generation"},
+ )
+ else:
+ progress_callback(
+ "Search complete, generating output",
+ 80,
+ {"phase": "output_generation"},
+ )
+ except Exception as search_error:
+ # Better handling of specific search errors
+ error_message = str(search_error)
+ error_type = "unknown"
+
+ # Extract error details for common issues
+ if "status code: 503" in error_message:
+ error_message = "Ollama AI service is unavailable (HTTP 503). Please check that Ollama is running properly on your system."
+ error_type = "ollama_unavailable"
+ elif "status code: 404" in error_message:
+ error_message = "Ollama model not found (HTTP 404). Please check that you have pulled the required model."
+ error_type = "model_not_found"
+ elif "status code:" in error_message:
+ # Extract the status code for other HTTP errors
+ status_code = error_message.split("status code:")[1].strip()
+ error_message = f"API request failed with status code {status_code}. Please check your configuration."
+ error_type = "api_error"
+ elif "connection" in error_message.lower():
+ error_message = "Connection error. Please check that your LLM service (Ollama/API) is running and accessible."
+ error_type = "connection_error"
+
+ # Raise with improved error message
+ raise Exception(f"{error_message} (Error type: {error_type})")
+
+ # Generate output based on mode
+ if mode == "quick":
+ # Quick Summary
+ if results.get("findings") or results.get("formatted_findings"):
+ raw_formatted_findings = results["formatted_findings"]
+
+ # Check if formatted_findings contains an error message
+ if isinstance(
+ raw_formatted_findings, str
+ ) and raw_formatted_findings.startswith("Error:"):
+ # Extract synthesized content from findings if available
+ synthesized_content = ""
+ for finding in results.get("findings", []):
+ if finding.get("phase") == "Final synthesis":
+ synthesized_content = finding.get("content", "")
+ break
+
+ # Use synthesized content as fallback
+ if synthesized_content:
+ raw_formatted_findings = synthesized_content
+ # Or use current_knowledge as another fallback
+ elif results.get("current_knowledge"):
+ raw_formatted_findings = results["current_knowledge"]
+ # Or combine all finding contents as last resort
+ elif results.get("findings"):
+ raw_formatted_findings = "\n\n".join(
+ f"## {finding.get('phase', 'Finding')}\n\n{finding.get('content', '')}"
+ for finding in results.get("findings", [])
+ if finding.get("content")
+ )
+
+ logger.info(
+ f"Found formatted_findings of length: {len(str(raw_formatted_findings))}"
+ )
+
+ try:
+ clean_markdown = raw_formatted_findings
+ logger.info(
+ f"Successfully converted to clean markdown of length: {len(clean_markdown)}"
+ )
+
+ # First send a progress update for generating the summary
+ progress_callback(
+ "Generating clean summary from research data...",
+ 90,
+ {"phase": "output_generation"},
+ )
+
+ # Save as markdown file
+ if not os.path.exists(OUTPUT_DIR):
+ os.makedirs(OUTPUT_DIR)
+
+ safe_query = "".join(
+ x for x in query if x.isalnum() or x in [" ", "-", "_"]
+ )[:50]
+ safe_query = safe_query.replace(" ", "_").lower()
+ report_path = os.path.join(
+ OUTPUT_DIR, f"quick_summary_{safe_query}.md"
+ )
+
+ # Send progress update for writing to file
+ progress_callback(
+ "Writing research report to file...",
+ 95,
+ {"phase": "report_complete"},
+ )
+
+ logger.info(f"Writing report to: {report_path}")
+ with open(report_path, "w", encoding="utf-8") as f:
+ f.write("# Quick Research Summary\n\n")
+ f.write(f"Query: {query}\n\n")
+ f.write(clean_markdown)
+ f.write("\n\n## Research Metrics\n")
+ f.write(f"- Search Iterations: {results['iterations']}\n")
+ f.write(f"- Generated at: {datetime.utcnow().isoformat()}\n")
+
+ # Update database
+ metadata = {
+ "iterations": results["iterations"],
+ "generated_at": datetime.utcnow().isoformat(),
+ }
+
+ # Calculate duration in seconds - using UTC consistently
+ now = datetime.utcnow()
+ completed_at = now.isoformat()
+
+ logger.info(f"Updating database for research_id: {research_id}")
+ # Get the start time from the database
+ conn = get_db_connection()
+ cursor = conn.cursor()
+ cursor.execute(
+ "SELECT created_at FROM research_history WHERE id = ?",
+ (research_id,),
+ )
+ result = cursor.fetchone()
+
+ # Use the helper function for consistent duration calculation
+ duration_seconds = calculate_duration(result[0])
+
+ # Update the record
+ cursor.execute(
+ "UPDATE research_history SET status = ?, completed_at = ?, duration_seconds = ?, report_path = ?, metadata = ? WHERE id = ?",
+ (
+ "completed",
+ completed_at,
+ duration_seconds,
+ report_path,
+ json.dumps(metadata),
+ research_id,
+ ),
+ )
+ conn.commit()
+ conn.close()
+ logger.info(
+ f"Database updated successfully for research_id: {research_id}"
+ )
+
+ # Send the final completion message
+ progress_callback(
+ "Research completed successfully",
+ 100,
+ {"phase": "complete", "report_path": report_path},
+ )
+
+ # Clean up resources
+ logger.info(f"Cleaning up resources for research_id: {research_id}")
+ cleanup_research_resources(
+ research_id, active_research, termination_flags
+ )
+ logger.info(f"Resources cleaned up for research_id: {research_id}")
+
+ except Exception as inner_e:
+ logger.error(
+ f"Error during quick summary generation: {str(inner_e)}"
+ )
+ logger.error(traceback.format_exc())
+ raise Exception(f"Error generating quick summary: {str(inner_e)}")
+ else:
+ raise Exception(
+ "No research findings were generated. Please try again."
+ )
+ else:
+ # Full Report
+ progress_callback(
+ "Generating detailed report...", 85, {"phase": "report_generation"}
+ )
+
+ report_generator = IntegratedReportGenerator()
+ final_report = report_generator.generate_report(results, query)
+
+ progress_callback(
+ "Report generation complete", 95, {"phase": "report_complete"}
+ )
+
+ # Save as markdown file
+ if not os.path.exists(OUTPUT_DIR):
+ os.makedirs(OUTPUT_DIR)
+
+ safe_query = "".join(
+ x for x in query if x.isalnum() or x in [" ", "-", "_"]
+ )[:50]
+ safe_query = safe_query.replace(" ", "_").lower()
+ report_path = os.path.join(OUTPUT_DIR, f"detailed_report_{safe_query}.md")
+
+ with open(report_path, "w", encoding="utf-8") as f:
+ f.write(final_report["content"])
+
+ # Update database
+ metadata = final_report["metadata"]
+ metadata["iterations"] = results["iterations"]
+
+ # Calculate duration in seconds - using UTC consistently
+ now = datetime.utcnow()
+ completed_at = now.isoformat()
+
+ # Get the start time from the database
+ conn = get_db_connection()
+ cursor = conn.cursor()
+ cursor.execute(
+ "SELECT created_at FROM research_history WHERE id = ?", (research_id,)
+ )
+ result = cursor.fetchone()
+
+ # Use the helper function for consistent duration calculation
+ duration_seconds = calculate_duration(result[0])
+
+ cursor.execute(
+ "UPDATE research_history SET status = ?, completed_at = ?, duration_seconds = ?, report_path = ?, metadata = ? WHERE id = ?",
+ (
+ "completed",
+ completed_at,
+ duration_seconds,
+ report_path,
+ json.dumps(metadata),
+ research_id,
+ ),
+ )
+ conn.commit()
+ conn.close()
+
+ progress_callback(
+ "Research completed successfully",
+ 100,
+ {"phase": "complete", "report_path": report_path},
+ )
+
+ # Clean up resources
+ cleanup_research_resources(research_id, active_research, termination_flags)
+
+ except Exception as e:
+ # Handle error
+ error_message = f"Research failed: {str(e)}"
+ logger.error(error_message)
+ try:
+ # Check for common Ollama error patterns in the exception and provide more user-friendly errors
+ user_friendly_error = str(e)
+ error_context = {}
+
+ if "Error type: ollama_unavailable" in user_friendly_error:
+ user_friendly_error = "Ollama AI service is unavailable. Please check that Ollama is running properly on your system."
+ error_context = {
+ "solution": "Start Ollama with 'ollama serve' or check if it's installed correctly."
+ }
+ elif "Error type: model_not_found" in user_friendly_error:
+ user_friendly_error = (
+ "Required Ollama model not found. Please pull the model first."
+ )
+ error_context = {
+ "solution": "Run 'ollama pull mistral' to download the required model."
+ }
+ elif "Error type: connection_error" in user_friendly_error:
+ user_friendly_error = "Connection error with LLM service. Please check that your AI service is running."
+ error_context = {
+ "solution": "Ensure Ollama or your API service is running and accessible."
+ }
+ elif "Error type: api_error" in user_friendly_error:
+ # Keep the original error message as it's already improved
+ error_context = {"solution": "Check API configuration and credentials."}
+
+ # Update metadata with more context about the error
+ metadata = {"phase": "error", "error": user_friendly_error}
+ if error_context:
+ metadata.update(error_context)
+
+ # If we still have an active research record, update its log
+ if research_id in active_research:
+ progress_callback(user_friendly_error, None, metadata)
+
+ conn = get_db_connection()
+ cursor = conn.cursor()
+
+ # If termination was requested, mark as suspended instead of failed
+ status = (
+ "suspended"
+ if (research_id in termination_flags and termination_flags[research_id])
+ else "failed"
+ )
+ message = (
+ "Research was terminated by user"
+ if status == "suspended"
+ else user_friendly_error
+ )
+
+ # Calculate duration up to termination point - using UTC consistently
+ now = datetime.utcnow()
+ completed_at = now.isoformat()
+
+ # Get the start time from the database
+ duration_seconds = None
+ cursor.execute(
+ "SELECT created_at FROM research_history WHERE id = ?", (research_id,)
+ )
+ result = cursor.fetchone()
+
+ # Use the helper function for consistent duration calculation
+ if result and result[0]:
+ duration_seconds = calculate_duration(result[0])
+
+ cursor.execute(
+ "UPDATE research_history SET status = ?, completed_at = ?, duration_seconds = ?, metadata = ? WHERE id = ?",
+ (
+ status,
+ completed_at,
+ duration_seconds,
+ json.dumps(metadata),
+ research_id,
+ ),
+ )
+ conn.commit()
+ conn.close()
+
+ try:
+ emit_to_subscribers(
+ "research_progress",
+ research_id,
+ {"status": status, "error": message},
+ )
+ except Exception as socket_error:
+ logger.error(f"Failed to emit error via socket: {str(socket_error)}")
+
+ except Exception as inner_e:
+ logger.error(f"Error in error handler: {str(inner_e)}")
+ logger.error(traceback.format_exc())
+
+ # Clean up resources
+ cleanup_research_resources(research_id, active_research, termination_flags)
+
+
+def cleanup_research_resources(research_id, active_research, termination_flags):
+ """
+ Clean up resources for a completed research.
+
+ Args:
+ research_id: The ID of the research
+ active_research: Dictionary of active research processes
+ termination_flags: Dictionary of termination flags
+ """
+ logger.info(f"Cleaning up resources for research {research_id}")
+
+ # Get the current status from the database to determine the final status message
+ current_status = "completed" # Default
+ try:
+ conn = get_db_connection()
+ cursor = conn.cursor()
+ cursor.execute(
+ "SELECT status FROM research_history WHERE id = ?", (research_id,)
+ )
+ result = cursor.fetchone()
+ if result and result[0]:
+ current_status = result[0]
+ conn.close()
+ except Exception as e:
+ logger.error(f"Error retrieving research status during cleanup: {e}")
+
+ # Remove from active research
+ if research_id in active_research:
+ del active_research[research_id]
+
+ # Remove from termination flags
+ if research_id in termination_flags:
+ del termination_flags[research_id]
+
+ # Send a final message to subscribers
+ try:
+ # Import here to avoid circular imports
+ from ..routes.research_routes import get_globals
+
+ globals_dict = get_globals()
+ socket_subscriptions = globals_dict.get("socket_subscriptions", {})
+
+ # Send a final message to any remaining subscribers with explicit status
+ if research_id in socket_subscriptions and socket_subscriptions[research_id]:
+ # Use the proper status message based on database status
+ if current_status == "suspended" or current_status == "failed":
+ final_message = {
+ "status": current_status,
+ "message": f"Research was {current_status}",
+ "progress": 0, # For suspended research, show 0% not 100%
+ }
+ else:
+ final_message = {
+ "status": "completed",
+ "message": "Research process has ended and resources have been cleaned up",
+ "progress": 100,
+ }
+
+ logger.info(
+ f"Sending final {current_status} socket message for research {research_id}"
+ )
+
+ emit_to_subscribers("research_progress", research_id, final_message)
+
+ except Exception as e:
+ logger.error(f"Error sending final cleanup message: {e}")
+
+
+def handle_termination(research_id, active_research, termination_flags):
+ """
+ Handle the termination of a research process.
+
+ Args:
+ research_id: The ID of the research
+ active_research: Dictionary of active research processes
+ termination_flags: Dictionary of termination flags
+ """
+ # Explicitly set the status to suspended in the database
+ conn = get_db_connection()
+ cursor = conn.cursor()
+
+ # Calculate duration up to termination point - using UTC consistently
+ now = datetime.utcnow()
+ completed_at = now.isoformat()
+
+ # Get the start time from the database
+ cursor.execute(
+ "SELECT created_at FROM research_history WHERE id = ?",
+ (research_id,),
+ )
+ result = cursor.fetchone()
+
+ # Calculate the duration
+ duration_seconds = calculate_duration(result[0]) if result and result[0] else None
+
+ # Update the database with suspended status
+ cursor.execute(
+ "UPDATE research_history SET status = ?, completed_at = ?, duration_seconds = ? WHERE id = ?",
+ ("suspended", completed_at, duration_seconds, research_id),
+ )
+ conn.commit()
+ conn.close()
+
+ # Clean up resources
+ cleanup_research_resources(research_id, active_research, termination_flags)
+
+
+def cancel_research(research_id):
+ """
+ Cancel/terminate a research process
+
+ Args:
+ research_id: The ID of the research to cancel
+
+ Returns:
+ bool: True if the research was found and cancelled, False otherwise
+ """
+ # Import globals from research routes
+ from ..routes.research_routes import get_globals
+
+ globals_dict = get_globals()
+ active_research = globals_dict["active_research"]
+ termination_flags = globals_dict["termination_flags"]
+
+ # Set termination flag
+ termination_flags[research_id] = True
+
+ # Check if the research is active
+ if research_id in active_research:
+ # Call handle_termination to update database
+ handle_termination(research_id, active_research, termination_flags)
+ return True
+ else:
+ # Update database directly if not found in active_research
+ from ..models.database import get_db_connection
+
+ conn = get_db_connection()
+ cursor = conn.cursor()
+
+ # First check if the research exists
+ cursor.execute(
+ "SELECT status FROM research_history WHERE id = ?", (research_id,)
+ )
+ result = cursor.fetchone()
+
+ if not result:
+ conn.close()
+ return False
+
+ # If it exists but isn't in active_research, still update status
+ cursor.execute(
+ "UPDATE research_history SET status = ? WHERE id = ?",
+ ("suspended", research_id),
+ )
+ conn.commit()
+ conn.close()
+
+ return True