~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
first version
LearningCircuit955ef9142ad6
diff --git a/.gitignore b/.gitignoreindex d694b04ac2..0f7129ce9d 100644--- a/.gitignore+++ b/.gitignore@@ -43,7 +43,7 @@ formatted_output.txtOutput.txtresearch_outputsreport.md-+data/# Logs*.loglogs/@@ -53,4 +53,4 @@ research_history.db# Data-.cache\ No newline at end of file+.cachediff --git a/src/local_deep_research/__init__.py b/src/local_deep_research/__init__.pyindex 755a3e4394..770f408a5a 100644--- a/src/local_deep_research/__init__.py+++ b/src/local_deep_research/__init__.py@@ -15,10 +15,16 @@ from .search_system import AdvancedSearchSystemfrom .report_generator import IntegratedReportGeneratorfrom .config import get_llm, get_search+# Import API functions+from .api import quick_summary, generate_report, analyze_documents+# Export it__all__ = ["AdvancedSearchSystem","IntegratedReportGenerator","get_llm",- "get_search"+ "get_search",+ "quick_summary",+ "generate_report",+ "analyze_documents"]\ No newline at end of filediff --git a/src/local_deep_research/api/__init__.py b/src/local_deep_research/api/__init__.pynew file mode 100644index 0000000000..cb82f1ef0d--- /dev/null+++ b/src/local_deep_research/api/__init__.py@@ -0,0 +1,11 @@+"""+API module for programmatic access to Local Deep Research functionality.+"""++from .research_functions import quick_summary, generate_report, analyze_documents++__all__ = [+ "quick_summary",+ "generate_report",+ "analyze_documents"+]\ No newline at end of filediff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.pynew file mode 100644index 0000000000..65ce2aa0f4--- /dev/null+++ b/src/local_deep_research/api/research_functions.py@@ -0,0 +1,181 @@+"""+API module for Local Deep Research.+Provides programmatic access to search and research capabilities.+"""++from typing import Dict, List, Optional, Union+import logging++from ..search_system import AdvancedSearchSystem+from ..report_generator import IntegratedReportGenerator+from ..config import get_llm, get_search++logger = logging.getLogger(__name__)++def quick_summary(+ query: str,+ search_tool: Optional[str] = None,+ iterations: int = 1,+ questions_per_iteration: int = 1,+ max_results: int = 20,+ max_filtered_results: int = 5,+) -> Dict:+ """+ Generate a quick research summary for a given query.++ Args:+ query: The research query to analyze+ search_tool: Search engine to use (auto, wikipedia, arxiv, etc.). If None, uses default+ iterations: Number of research cycles to perform+ questions_per_iteration: Number of questions to generate per cycle+ max_results: Maximum number of search results to consider+ max_filtered_results: Maximum results after relevance filtering++ Returns:+ Dictionary containing the research results with keys:+ - 'summary': The generated summary text+ - 'findings': List of detailed findings from each search+ - 'iterations': Number of iterations performed+ - 'questions': Questions generated during research+ """+ logger.info(f"Generating quick summary for query: {query}")++ # Get search engine and language model+ llm = get_llm()++ # 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++ # Set the search engine if specified+ if search_tool:+ system.search = get_search(search_tool)++ # 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", {})+ }++def generate_report(+ query: str,+ search_tool: Optional[str] = None,+ iterations: int = 2,+ questions_per_iteration: int = 2,+ searches_per_section: int = 2,+) -> Dict:+ """+ Generate a comprehensive, structured research report for a given query.++ Args:+ query: The research query to analyze+ search_tool: Search engine to use (auto, wikipedia, arxiv, etc.). If None, uses default+ iterations: Number of research cycles to perform+ questions_per_iteration: Number of questions to generate per cycle+ searches_per_section: Number of searches to perform per report section++ Returns:+ Dictionary containing the research report with keys:+ - 'content': The full report content in markdown format+ - 'metadata': Report metadata including generated timestamp and query+ """+ logger.info(f"Generating comprehensive research report for query: {query}")++ # 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++ # Set the search engine if specified+ if search_tool:+ system.search = get_search(search_tool)++ # Perform the initial research+ initial_findings = system.analyze_topic(query)++ # Generate the structured report+ report_generator = IntegratedReportGenerator(searches_per_section=searches_per_section)+ report = report_generator.generate_report(initial_findings, query)++ return report++def analyze_documents(+ query: str,+ collection_name: str,+ max_results: int = 10+) -> Dict:+ """+ Search and analyze documents in a specific local collection.++ Args:+ query: The search query+ collection_name: Name of the local document collection to search+ max_results: Maximum number of results to return++ Returns:+ Dictionary containing:+ - 'summary': Summary of the findings+ - 'documents': List of matching documents with content and metadata+ """+ logger.info(f"Analyzing documents in collection '{collection_name}' for query: {query}")++ # Get search engine for the specified collection+ search = get_search(collection_name)++ 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++ # 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+ llm = get_llm()+ docs_text = "\n\n".join([f"Document {i+1}: {doc.get('content', doc.get('snippet', ''))}"+ for i, doc in enumerate(results)])++ summary_prompt = f"""Analyze these document excerpts related to the query: "{query}"++ {docs_text[:8000]} # Truncate if too long++ Provide a concise summary of the key information found in these documents related to the query.+ """++ try:+ summary_response = llm.invoke(summary_prompt)+ summary = summary_response.content+ except Exception as e:+ logger.error(f"Error generating summary: {e}")+ summary = f"Found {len(results)} relevant documents in collection '{collection_name}'."++ return {+ "summary": summary,+ "documents": results+ }\ No newline at end of filediff --git a/tests/test_programatic_access.ipynb b/tests/test_programatic_access.ipynbnew file mode 100644index 0000000000..298b7e3f38--- /dev/null+++ b/tests/test_programatic_access.ipynb@@ -0,0 +1,138 @@+{+ "cells": [+ {+ "cell_type": "code",+ "execution_count": 2,+ "metadata": {},+ "outputs": [],+ "source": [+ "from local_deep_research import quick_summary, generate_report, analyze_documents"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 3,+ "metadata": {},+ "outputs": [+ {+ "name": "stderr",+ "output_type": "stream",+ "text": [+ "INFO:llm_config:Available providers: ['ollama', 'openai_endpoint']\n",+ "INFO:local_deep_research.config:Search config params: {'search_tool': 'auto', 'llm_instance': ChatOpenAI(client=<openai.resources.chat.completions.completions.Completions object at 0x79f62dfa0670>, async_client=<openai.resources.chat.completions.completions.AsyncCompletions object at 0x79f62dfa2440>, root_client=<openai.OpenAI object at 0x79f62df9e9b0>, root_async_client=<openai.AsyncOpenAI object at 0x79f62dfa06a0>, model_name='google/gemini-2.0-flash-001', temperature=0.7, model_kwargs={}, openai_api_key=SecretStr('**********'), openai_api_base='https://openrouter.ai/api/v1', max_tokens=30000), 'max_results': 50, 'region': 'us', 'time_period': 'y', 'safe_search': True, 'search_snippets_only': False, 'search_language': 'English', 'max_filtered_results': 5}\n",+ "INFO:local_deep_research.web_search_engines.search_engine_factory:Creating search engine for tool: auto with params: dict_keys(['max_results', 'llm', 'max_filtered_results'])\n",+ "INFO:local_deep_research.web_search_engines.search_engine_factory:Creating auto with filtered parameters: dict_keys(['use_api_key_services', 'max_engines_to_try', 'max_results', 'max_filtered_results', 'llm'])\n",+ "INFO:local_deep_research.web_search_engines.engines.meta_search_engine:Meta Search Engine initialized with 9 available engines: wikipedia, arxiv, pubmed, github, wayback, local_all, project_docs, research_papers, personal_notes\n",+ "INFO:local_deep_research.web_search_engines.search_engine_factory:Successfully created search engine of type: MetaSearchEngine\n",+ "INFO:local_deep_research.web_search_engines.search_engine_factory:Engine has 'run' method: <bound method BaseSearchEngine.run of <local_deep_research.web_search_engines.engines.meta_search_engine.MetaSearchEngine object at 0x79f62dfa2500>>\n",+ "INFO:llm_config:Available providers: ['ollama', 'openai_endpoint']\n",+ "INFO:local_deep_research.search_system:Starting research on topic: advances in fusion energy\n",+ "INFO:httpx:HTTP Request: POST https://openrouter.ai/api/v1/chat/completions \"HTTP/1.1 200 OK\"\n",+ "INFO:local_deep_research.search_system:Generated questions: ['What are the most recent breakthroughs and advancements in fusion energy research and technology as of March 2025?']\n",+ "INFO:local_deep_research.web_search_engines.engines.meta_search_engine:Processing search engine: wikipedia\n",+ "INFO:local_deep_research.web_search_engines.engines.meta_search_engine:Processing search engine: arxiv\n",+ "INFO:local_deep_research.web_search_engines.engines.meta_search_engine:Processing search engine: pubmed\n",+ "INFO:local_deep_research.web_search_engines.engines.meta_search_engine:Processing search engine: github\n",+ "INFO:local_deep_research.web_search_engines.engines.meta_search_engine:Processing search engine: wayback\n",+ "INFO:local_deep_research.web_search_engines.engines.meta_search_engine:Processing search engine: local_all\n",+ "INFO:local_deep_research.web_search_engines.engines.meta_search_engine:Processing search engine: project_docs\n",+ "INFO:local_deep_research.web_search_engines.engines.meta_search_engine:Processing search engine: research_papers\n",+ "INFO:local_deep_research.web_search_engines.engines.meta_search_engine:Processing search engine: personal_notes\n",+ "INFO:httpx:HTTP Request: POST https://openrouter.ai/api/v1/chat/completions \"HTTP/1.1 200 OK\"\n",+ "INFO:local_deep_research.web_search_engines.engines.meta_search_engine:Search plan created. Will try these engines in order: arxiv, research_papers, wikipedia\n",+ "INFO:local_deep_research.web_search_engines.engines.meta_search_engine:Trying search engine: arxiv\n",+ "INFO:local_deep_research.web_search_engines.search_engine_factory:Creating arxiv with filtered parameters: dict_keys(['max_results', 'sort_by', 'sort_order', 'max_filtered_results'])\n",+ "INFO:local_deep_research.web_search_engines.engines.search_engine_arxiv:Getting paper previews from arXiv\n",+ "INFO:arxiv:Requesting page (first: True, try: 0): https://export.arxiv.org/api/query?search_query=What+are+the+most+recent+breakthroughs+and+advancements+in+fusion+energy+research+and+technology+as+of+March+2025%3F&id_list=&sortBy=relevance&sortOrder=descending&start=0&max_results=50\n",+ "INFO:arxiv:Got first page: 50 of 2698912 total results\n",+ "INFO:local_deep_research.web_search_engines.engines.meta_search_engine:Successfully got 50 preview results from arxiv\n",+ "INFO:httpx:HTTP Request: POST https://openrouter.ai/api/v1/chat/completions \"HTTP/1.1 200 OK\"\n",+ "INFO:local_deep_research.web_search_engines.engines.meta_search_engine:Getting full content for relevant items\n",+ "INFO:local_deep_research.web_search_engines.engines.meta_search_engine:Using arxiv to get full content\n",+ "INFO:local_deep_research.web_search_engines.engines.search_engine_arxiv:Getting full content for relevant arXiv papers\n",+ "INFO:local_deep_research.search_system:len search: 2\n",+ "INFO:httpx:HTTP Request: POST https://openrouter.ai/api/v1/chat/completions \"HTTP/1.1 200 OK\"\n",+ "INFO:local_deep_research.search_system:Generated questions: SOURCES:\n",+ "1. Accelerating the Fusion Workforce\n",+ " URL: http://arxiv.org/abs/2501.03372v1\n",+ "2. Fusion energy commercialization requires solving social and environmental challenges\n",+ " URL: http://arxiv.org/abs/2403.05993v1\n",+ "\n",+ "\n",+ "INFO:local_deep_research.search_system:1\n",+ "INFO:local_deep_research.search_system:ITERATION\n",+ "INFO:local_deep_research.search_system:ITERATION\n",+ "INFO:local_deep_research.search_system:ITERATION - Compressing Knowledge\n",+ "INFO:httpx:HTTP Request: POST https://openrouter.ai/api/v1/chat/completions \"HTTP/1.1 200 OK\"\n",+ "INFO:local_deep_research.search_system:FINISHED ITERATION - Compressing Knowledge\n",+ "INFO:local_deep_research.search_system:Saving findings ...\n",+ "INFO:local_deep_research.config:Looking for config in: /home/martin/.config/local_deep_research\n",+ "INFO:local_deep_research.search_system:Saved findings\n"+ ]+ },+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Here's a 1-page explanation of recent advances in fusion energy, followed by a concise one-sentence answer to your query.\n",+ "\n",+ "**Recent Advances in Fusion Energy**\n",+ "\n",+ "The fusion energy sector is experiencing a period of rapid advancement, driven by both scientific progress and increasing private investment [1], [2]. While specific, detailed technical breakthroughs are not explicitly outlined in the provided sources, they emphasize significant trends shaping the field. A central theme is the growing focus on overcoming the barriers to commercialization, moving beyond purely scientific demonstrations of fusion feasibility [2]. This shift necessitates addressing a range of challenges, from workforce development to societal and environmental considerations.\n",+ "\n",+ "One critical area of focus is the emerging skills gap within the fusion industry. The demand for qualified personnel is outpacing the current capacity of academic programs to produce graduates with the necessary expertise [1]. This skills shortage threatens to impede the progress of fusion energy development and deployment. To address this challenge, collaborative initiatives are being fostered between public and private sector stakeholders [1]. These partnerships aim to enhance fusion research and education programs, ensuring a pipeline of skilled workers to support the growing industry. Strategies may include specialized training programs, internships, and curriculum development initiatives tailored to the specific needs of the fusion sector.\n",+ "\n",+ "Beyond the technical and economic aspects, the fusion community is increasingly aware of the importance of understanding and mitigating the potential societal and environmental impacts of fusion energy [2]. This proactive approach aims to ensure that fusion technology is developed and deployed in a responsible and sustainable manner. Research priorities are emerging around several key areas, including:\n",+ "\n",+ "* **Environmental Lifecycle Impacts:** Assessing the environmental footprint of fusion energy systems throughout their entire lifecycle, from resource extraction and manufacturing to operation and decommissioning [2].\n",+ "\n",+ "* **Risk and Safety Assessment Methodologies:** Developing robust methodologies for evaluating the risks associated with fusion energy facilities and ensuring the safety of workers, the public, and the environment [2].\n",+ "\n",+ "* **Community-Based Approaches:** Engaging with local communities to understand their concerns and incorporate their perspectives into the design and deployment of fusion technology [2]. This participatory approach can help build trust and minimize potential delays in project development by addressing community concerns proactively.\n",+ "\n",+ "By addressing these societal and environmental considerations early in the design process, the fusion community hopes to build public trust and create a more sustainable path towards commercialization [2]. This holistic approach, encompassing scientific advancements, workforce development, and societal engagement, represents a significant step forward in the pursuit of fusion energy as a clean and sustainable energy source.\n",+ "\n",+ "**References**\n",+ "\n",+ "[1] Accelerating the Fusion Workforce. http://arxiv.org/abs/2501.03372v1\n",+ "\n",+ "[2] Fusion energy commercialization requires solving social and environmental challenges. http://arxiv.org/abs/2403.05993v1\n",+ "\n",+ "**One-Sentence Answer:**\n",+ "\n",+ "Fusion energy advances in March 2025 are characterized by a growing focus on commercialization, including workforce development and addressing societal and environmental impacts.\n"+ ]+ }+ ],+ "source": [+ "\n",+ "\n",+ "# Generate a quick summary\n",+ "summary = quick_summary(\"advances in fusion energy\")\n",+ "print(summary[\"summary\"])\n",+ "\n"+ ]+ }+ ],+ "metadata": {+ "kernelspec": {+ "display_name": "venv",+ "language": "python",+ "name": "python3"+ },+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3",+ "version": "3.10.9"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 2+}