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

LearningCircuit06ede6b09f50
diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.py
index 4800f3a79b..5dc7541ab7 100644
--- a/src/local_deep_research/api/research_functions.py
+++ b/src/local_deep_research/api/research_functions.py
@@ -53,58 +53,49 @@ def quick_summary(
"""
logger.info(f"Generating quick summary for query: {query}")
- try:
- # Get language model with custom temperature
- llm = get_llm(temperature=temperature)
-
- # Create search system with custom parameters
- system = AdvancedSearchSystem()
-
- # Override default settings with user-provided values
- system.max_iterations = iterations
- system.questions_per_iteration = questions_per_iteration
- system.model = llm # Ensure the model is directly attached to the system
-
- # Set the search engine if specified
- if search_tool:
- search_engine = get_search(search_tool)
- if search_engine:
- system.search = search_engine
- else:
- logger.warning(f"Could not create search engine '{search_tool}', using default.")
-
- # Set progress callback if provided
- if progress_callback:
- system.set_progress_callback(progress_callback)
-
- # Perform the search and analysis
- results = system.analyze_topic(query)
-
- # Extract the summary from the current knowledge
- if results and "current_knowledge" in results:
- summary = results["current_knowledge"]
+
+ # Get language model with custom temperature
+ llm = get_llm(temperature=temperature)
+
+ # Create search system with custom parameters
+ system = AdvancedSearchSystem()
+
+ # Override default settings with user-provided values
+ system.max_iterations = iterations
+ system.questions_per_iteration = questions_per_iteration
+ system.model = llm # Ensure the model is directly attached to the system
+
+ # Set the search engine if specified
+ if search_tool:
+ search_engine = get_search(search_tool)
+ if search_engine:
+ system.search = search_engine
else:
- summary = "Unable to generate summary for the query."
-
- # Prepare the return value
- return {
- "summary": summary,
- "findings": results.get("findings", []),
- "iterations": results.get("iterations", 0),
- "questions": results.get("questions", {}),
- "formatted_findings": results.get("formatted_findings", ""),
- "sources": results.get("all_links_of_system", [])
- }
- except Exception as e:
- logger.error(f"Error in quick_summary: {str(e)}")
- logger.error(traceback.format_exc())
- return {
- "summary": f"Error occurred while generating summary: {str(e)}",
- "error": str(e),
- "findings": [],
- "iterations": 0,
- "questions": {}
- }
+ logger.warning(f"Could not create search engine '{search_tool}', using default.")
+
+ # Set progress callback if provided
+ if progress_callback:
+ system.set_progress_callback(progress_callback)
+
+ # Perform the search and analysis
+ results = system.analyze_topic(query)
+
+ # Extract the summary from the current knowledge
+ if results and "current_knowledge" in results:
+ summary = results["current_knowledge"]
+ else:
+ summary = "Unable to generate summary for the query."
+
+ # Prepare the return value
+ return {
+ "summary": summary,
+ "findings": results.get("findings", []),
+ "iterations": results.get("iterations", 0),
+ "questions": results.get("questions", {}),
+ "formatted_findings": results.get("formatted_findings", ""),
+ "sources": results.get("all_links_of_system", [])
+ }
+
def generate_report(
query: str,
@@ -146,70 +137,55 @@ def generate_report(
"""
logger.info(f"Generating comprehensive research report for query: {query}")
- try:
- # Get language model with custom temperature
- llm = get_llm(temperature=temperature)
-
- # Create search system with custom parameters
- system = AdvancedSearchSystem()
-
- # Override default settings with user-provided values
- system.max_iterations = iterations
- system.questions_per_iteration = questions_per_iteration
- system.model = llm # Ensure the model is directly attached to the system
-
- # Set the search engine if specified
- if search_tool:
- search_engine = get_search(
- search_tool,
- llm_instance=llm,
- max_results=max_results,
- max_filtered_results=max_filtered_results,
- region=region,
- time_period=time_period,
- safe_search=safe_search
- )
- if search_engine:
- system.search = search_engine
- else:
- logger.warning(f"Could not create search engine '{search_tool}', using default.")
-
- # Set progress callback if provided
- if progress_callback:
- system.set_progress_callback(progress_callback)
-
- # Perform the initial research
- initial_findings = system.analyze_topic(query)
-
- # Generate the structured report
- report_generator = IntegratedReportGenerator(searches_per_section=searches_per_section)
- report_generator.model = llm # Ensure the model is set on the report generator too
- report = report_generator.generate_report(initial_findings, query)
-
- # Save report to file if path is provided
- if output_file and report and "content" in report:
- try:
- with open(output_file, "w", encoding="utf-8") as f:
- f.write(report["content"])
- logger.info(f"Report saved to {output_file}")
- report["file_path"] = output_file
- except Exception as e:
- logger.error(f"Error saving report to file: {e}")
- report["file_error"] = str(e)
-
- return report
- except Exception as e:
- logger.error(f"Error in generate_report: {str(e)}")
- logger.error(traceback.format_exc())
- return {
- "content": f"Error occurred while generating report: {str(e)}",
- "error": str(e),
- "metadata": {
- "query": query,
- "status": "error",
- "error_message": str(e)
- }
- }
+
+ # Get language model with custom temperature
+ llm = get_llm(temperature=temperature)
+
+ # Create search system with custom parameters
+ system = AdvancedSearchSystem()
+
+ # Override default settings with user-provided values
+ system.max_iterations = iterations
+ system.questions_per_iteration = questions_per_iteration
+ system.model = llm # Ensure the model is directly attached to the system
+
+ # Set the search engine if specified
+ if search_tool:
+ search_engine = get_search(
+ search_tool,
+ llm_instance=llm,
+ max_results=max_results,
+ max_filtered_results=max_filtered_results,
+ region=region,
+ time_period=time_period,
+ safe_search=safe_search
+ )
+ if search_engine:
+ system.search = search_engine
+ else:
+ logger.warning(f"Could not create search engine '{search_tool}', using default.")
+
+ # Set progress callback if provided
+ if progress_callback:
+ system.set_progress_callback(progress_callback)
+
+ # Perform the initial research
+ initial_findings = system.analyze_topic(query)
+
+ # Generate the structured report
+ report_generator = IntegratedReportGenerator(searches_per_section=searches_per_section)
+ report_generator.model = llm # Ensure the model is set on the report generator too
+ report = report_generator.generate_report(initial_findings, query)
+
+ # Save report to file if path is provided
+ if output_file and report and "content" in report:
+ with open(output_file, "w", encoding="utf-8") as f:
+ f.write(report["content"])
+ logger.info(f"Report saved to {output_file}")
+ report["file_path"] = output_file
+ return report
+
+
def analyze_documents(
query: str,
@@ -237,99 +213,79 @@ def analyze_documents(
"""
logger.info(f"Analyzing documents in collection '{collection_name}' for query: {query}")
- try:
- # Get language model with custom temperature
- llm = get_llm(temperature=temperature)
-
- # Get search engine for the specified collection
- search = get_search(collection_name, llm_instance=llm)
-
- if not search:
- return {
- "summary": f"Error: Collection '{collection_name}' not found or not properly configured.",
- "documents": []
- }
-
- # Set max results
- search.max_results = max_results
-
- # Force reindex if requested
- if force_reindex and hasattr(search, 'embedding_manager'):
- try:
- for folder_path in search.folder_paths:
- search.embedding_manager.index_folder(folder_path, force_reindex=True)
- except Exception as e:
- logger.error(f"Error during reindexing: {e}")
- # Continue with search even if reindexing fails
-
- # Perform the search
- results = search.run(query)
-
- if not results:
- return {
- "summary": f"No documents found in collection '{collection_name}' for query: '{query}'",
- "documents": []
- }
-
- # Get LLM to generate a summary of the results
- try:
- docs_text = "\n\n".join([f"Document {i+1}: {doc.get('content', doc.get('snippet', ''))[:1000]}"
- for i, doc in enumerate(results[:5])]) # Limit to first 5 docs and 1000 chars each
-
- summary_prompt = f"""Analyze these document excerpts related to the query: "{query}"
-
- {docs_text}
-
- Provide a concise summary of the key information found in these documents related to the query.
- """
-
- summary_response = llm.invoke(summary_prompt)
- if hasattr(summary_response, 'content'):
- summary = remove_think_tags(summary_response.content)
- else:
- summary = str(summary_response)
- except Exception as e:
- logger.error(f"Error generating summary: {e}")
- summary = f"Found {len(results)} relevant documents in collection '{collection_name}'."
-
- # Create result dictionary
- analysis_result = {
- "summary": summary,
- "documents": results,
- "collection": collection_name,
- "document_count": len(results)
+
+ # Get language model with custom temperature
+ llm = get_llm(temperature=temperature)
+
+ # Get search engine for the specified collection
+ search = get_search(collection_name, llm_instance=llm)
+
+ if not search:
+ return {
+ "summary": f"Error: Collection '{collection_name}' not found or not properly configured.",
+ "documents": []
}
-
- # Save to file if requested
- if output_file:
- try:
- with open(output_file, "w", encoding="utf-8") as f:
- f.write(f"# Document Analysis: {query}\n\n")
- f.write(f"## Summary\n\n{summary}\n\n")
- f.write(f"## Documents Found: {len(results)}\n\n")
-
- for i, doc in enumerate(results):
- f.write(f"### Document {i+1}: {doc.get('title', 'Untitled')}\n\n")
- f.write(f"**Source:** {doc.get('link', 'Unknown')}\n\n")
- f.write(f"**Content:**\n\n{doc.get('content', doc.get('snippet', 'No content available'))[:1000]}...\n\n")
- f.write("---\n\n")
-
- analysis_result["file_path"] = output_file
- logger.info(f"Analysis saved to {output_file}")
- except Exception as e:
- logger.error(f"Error saving analysis to file: {e}")
- analysis_result["file_error"] = str(e)
-
- return analysis_result
- except Exception as e:
- logger.error(f"Error in analyze_documents: {str(e)}")
- logger.error(traceback.format_exc())
+
+ # Set max results
+ search.max_results = max_results
+
+ # Force reindex if requested
+ if force_reindex and hasattr(search, 'embedding_manager'):
+ for folder_path in search.folder_paths:
+ search.embedding_manager.index_folder(folder_path, force_reindex=True)
+
+ # Perform the search
+ results = search.run(query)
+
+ if not results:
return {
- "summary": f"Error occurred while analyzing documents: {str(e)}",
- "error": str(e),
- "documents": [],
- "collection": collection_name
+ "summary": f"No documents found in collection '{collection_name}' for query: '{query}'",
+ "documents": []
}
+
+ # Get LLM to generate a summary of the results
+
+ docs_text = "\n\n".join([f"Document {i+1}: {doc.get('content', doc.get('snippet', ''))[:1000]}"
+ for i, doc in enumerate(results[:5])]) # Limit to first 5 docs and 1000 chars each
+
+ summary_prompt = f"""Analyze these document excerpts related to the query: "{query}"
+
+ {docs_text}
+
+ Provide a concise summary of the key information found in these documents related to the query.
+ """
+
+ summary_response = llm.invoke(summary_prompt)
+ if hasattr(summary_response, 'content'):
+ summary = remove_think_tags(summary_response.content)
+ else:
+ summary = str(summary_response)
+
+ # Create result dictionary
+ analysis_result = {
+ "summary": summary,
+ "documents": results,
+ "collection": collection_name,
+ "document_count": len(results)
+ }
+
+ # Save to file if requested
+ if output_file:
+ with open(output_file, "w", encoding="utf-8") as f:
+ f.write(f"# Document Analysis: {query}\n\n")
+ f.write(f"## Summary\n\n{summary}\n\n")
+ f.write(f"## Documents Found: {len(results)}\n\n")
+
+ for i, doc in enumerate(results):
+ f.write(f"### Document {i+1}: {doc.get('title', 'Untitled')}\n\n")
+ f.write(f"**Source:** {doc.get('link', 'Unknown')}\n\n")
+ f.write(f"**Content:**\n\n{doc.get('content', doc.get('snippet', 'No content available'))[:1000]}...\n\n")
+ f.write("---\n\n")
+
+ analysis_result["file_path"] = output_file
+ logger.info(f"Analysis saved to {output_file}")
+
+ return analysis_result
def get_available_search_engines() -> Dict[str, str]:
"""
@@ -338,25 +294,23 @@ def get_available_search_engines() -> Dict[str, str]:
Returns:
Dictionary mapping engine names to descriptions
"""
- try:
- from ..web_search_engines.search_engine_factory import get_available_engines
- engines = get_available_engines()
-
- # Add some descriptions for common engines
- descriptions = {
- "auto": "Automatic selection based on query type",
- "wikipedia": "Wikipedia articles and general knowledge",
- "arxiv": "Scientific papers and research",
- "pubmed": "Medical and biomedical literature",
- "semantic_scholar": "Academic papers across all fields",
- "github": "Code repositories and technical documentation",
- "local_all": "All local document collections"
- }
-
- return {engine: descriptions.get(engine, "Search engine") for engine in engines}
- except Exception as e:
- logger.error(f"Error getting available search engines: {e}")
- return {}
+
+ from ..web_search_engines.search_engine_factory import get_available_engines
+ engines = get_available_engines()
+
+ # Add some descriptions for common engines
+ descriptions = {
+ "auto": "Automatic selection based on query type",
+ "wikipedia": "Wikipedia articles and general knowledge",
+ "arxiv": "Scientific papers and research",
+ "pubmed": "Medical and biomedical literature",
+ "semantic_scholar": "Academic papers across all fields",
+ "github": "Code repositories and technical documentation",
+ "local_all": "All local document collections"
+ }
+
+ return {engine: descriptions.get(engine, "Search engine") for engine in engines}
+
def get_available_collections() -> Dict[str, Dict[str, Any]]:
"""
@@ -365,18 +319,12 @@ def get_available_collections() -> Dict[str, Dict[str, Any]]:
Returns:
Dictionary mapping collection names to their configuration
"""
- try:
- import toml
- from ..config import LOCAL_COLLECTIONS_FILE
-
- if os.path.exists(LOCAL_COLLECTIONS_FILE):
- try:
- collections = toml.load(LOCAL_COLLECTIONS_FILE)
- return collections
- except Exception as e:
- logger.error(f"Error loading collections: {e}")
-
- return {}
- except Exception as e:
- logger.error(f"Error getting available collections: {e}")
- return {}
\ No newline at end of file
+
+ import toml
+ from ..config import LOCAL_COLLECTIONS_FILE
+
+ if os.path.exists(LOCAL_COLLECTIONS_FILE):
+ collections = toml.load(LOCAL_COLLECTIONS_FILE)
+ return collections
+
+ return {}