~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
programatic access
LearningCircuit4055a256645d
diff --git a/src/local_deep_research/__init__.py b/src/local_deep_research/__init__.pyindex 770f408a5a..5054ba800d 100644--- a/src/local_deep_research/__init__.py+++ b/src/local_deep_research/__init__.py@@ -17,6 +17,7 @@ from .config import get_llm, get_search# Import API functionsfrom .api import quick_summary, generate_report, analyze_documents+from .api import get_available_search_engines, get_available_collections# Export it__all__ = [@@ -26,5 +27,7 @@ __all__ = ["get_search","quick_summary","generate_report",- "analyze_documents"+ "analyze_documents",+ "get_available_search_engines",+ "get_available_collections"]\ No newline at end of filediff --git a/src/local_deep_research/api/__init__.py b/src/local_deep_research/api/__init__.pyindex cb82f1ef0d..f02b6a34b7 100644--- a/src/local_deep_research/api/__init__.py+++ b/src/local_deep_research/api/__init__.py@@ -1,11 +1,20 @@+# src/local_deep_research/api/__init__.py"""API module for programmatic access to Local Deep Research functionality."""-from .research_functions import quick_summary, generate_report, analyze_documents+from .research_functions import (+ quick_summary,+ generate_report,+ analyze_documents,+ get_available_search_engines,+ get_available_collections+)__all__ = ["quick_summary","generate_report",- "analyze_documents"+ "analyze_documents",+ "get_available_search_engines",+ "get_available_collections"]\ No newline at end of filediff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.pyindex 65ce2aa0f4..4800f3a79b 100644--- a/src/local_deep_research/api/research_functions.py+++ b/src/local_deep_research/api/research_functions.py@@ -3,12 +3,15 @@ API module for Local Deep Research.Provides programmatic access to search and research capabilities."""-from typing import Dict, List, Optional, Union+from typing import Dict, List, Optional, Union, Any, Callableimport logging+import os+import tracebackfrom ..search_system import AdvancedSearchSystemfrom ..report_generator import IntegratedReportGenerator-from ..config import get_llm, get_search+from ..config import get_llm, get_search, settings+from ..utilties.search_utilities import remove_think_tagslogger = logging.getLogger(__name__)@@ -19,7 +22,12 @@ def quick_summary(questions_per_iteration: int = 1,max_results: int = 20,max_filtered_results: int = 5,-) -> Dict:+ region: str = "us",+ time_period: str = "y",+ safe_search: bool = True,+ temperature: float = 0.7,+ progress_callback: Optional[Callable] = None,+) -> Dict[str, Any]:"""Generate a quick research summary for a given query.@@ -30,6 +38,11 @@ def quick_summary(questions_per_iteration: Number of questions to generate per cyclemax_results: Maximum number of search results to considermax_filtered_results: Maximum results after relevance filtering+ region: Search region/locale+ time_period: Time period for search results (d=day, w=week, m=month, y=year)+ safe_search: Whether to enable safe search+ temperature: LLM temperature for generation+ progress_callback: Optional callback function to receive progress updatesReturns:Dictionary containing the research results with keys:@@ -40,36 +53,58 @@ def quick_summary("""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", {})- }+ 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"]+ 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": {}+ }def generate_report(query: str,@@ -77,7 +112,15 @@ def generate_report(iterations: int = 2,questions_per_iteration: int = 2,searches_per_section: int = 2,-) -> Dict:+ max_results: int = 50,+ max_filtered_results: int = 5,+ region: str = "us",+ time_period: str = "y",+ safe_search: bool = True,+ temperature: float = 0.7,+ output_file: Optional[str] = None,+ progress_callback: Optional[Callable] = None,+) -> Dict[str, Any]:"""Generate a comprehensive, structured research report for a given query.@@ -87,6 +130,14 @@ def generate_report(iterations: Number of research cycles to performquestions_per_iteration: Number of questions to generate per cyclesearches_per_section: Number of searches to perform per report section+ max_results: Maximum number of search results to consider+ max_filtered_results: Maximum results after relevance filtering+ region: Search region/locale+ time_period: Time period for search results (d=day, w=week, m=month, y=year)+ safe_search: Whether to enable safe search+ temperature: LLM temperature for generation+ output_file: Optional path to save report markdown file+ progress_callback: Optional callback function to receive progress updatesReturns:Dictionary containing the research report with keys:@@ -95,31 +146,79 @@ def generate_report("""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+ 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)+ }+ }def analyze_documents(query: str,collection_name: str,- max_results: int = 10-) -> Dict:+ max_results: int = 10,+ temperature: float = 0.7,+ force_reindex: bool = False,+ output_file: Optional[str] = None,+) -> Dict[str, Any]:"""Search and analyze documents in a specific local collection.@@ -127,6 +226,9 @@ def analyze_documents(query: The search querycollection_name: Name of the local document collection to searchmax_results: Maximum number of results to return+ temperature: LLM temperature for summary generation+ force_reindex: Whether to force reindexing the collection+ output_file: Optional path to save analysis results to a fileReturns:Dictionary containing:@@ -135,47 +237,146 @@ def analyze_documents("""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": []+ 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)}-- # Set max results- search.max_results = max_results-- # Perform the search- results = search.run(query)-- if not results:++ # 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())return {- "summary": f"No documents found in collection '{collection_name}' for query: '{query}'",- "documents": []+ "summary": f"Error occurred while analyzing documents: {str(e)}",+ "error": str(e),+ "documents": [],+ "collection": collection_name}-- # 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.++def get_available_search_engines() -> Dict[str, str]:"""+ Get a dictionary of available search engines.+ Returns:+ Dictionary mapping engine names to descriptions+ """try:- summary_response = llm.invoke(summary_prompt)- summary = summary_response.content+ 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 generating summary: {e}")- summary = f"Found {len(results)} relevant documents in collection '{collection_name}'."+ logger.error(f"Error getting available search engines: {e}")+ return {}++def get_available_collections() -> Dict[str, Dict[str, Any]]:+ """+ Get a dictionary of available local document collections.- return {- "summary": summary,- "documents": results- }\ No newline at end of file+ 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 filediff --git a/tests/test_programatic_access.ipynb b/tests/test_programatic_access.ipynbindex 298b7e3f38..49c39048c5 100644--- a/tests/test_programatic_access.ipynb+++ b/tests/test_programatic_access.ipynb@@ -1,122 +1,242 @@{"cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "# Local Deep Research API Tutorial\n",+ "\n",+ "This notebook demonstrates how to use the Local Deep Research API to programmatically conduct research."+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Basic Imports\n",+ "\n",+ "First, import the main functions from the package:"+ ]+ },{"cell_type": "code",- "execution_count": 2,+ "execution_count": 11,"metadata": {},"outputs": [],"source": ["from local_deep_research import quick_summary, generate_report, analyze_documents"]},+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Generating a Quick Summary\n",+ "\n",+ "The `quick_summary` function allows you to quickly research a topic and get a summary of findings."+ ]+ },{"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"- ]- }- ],+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Research a topic and get a quick summary\n",+ "summary_results = quick_summary(\"advances in fusion energy\")\n",+ "\n",+ "# Print the summary\n",+ "print(summary_results[\"summary\"])"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},"source": [+ "## Customizing Search Parameters\n","\n",+ "You can customize the search process by specifying parameters:"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Generate a summary with custom parameters\n",+ "custom_summary = quick_summary(\n",+ " query=\"renewable energy trends\",\n",+ " search_tool=\"wikipedia\", # Use Wikipedia as the search engine\n",+ ")\n",+ "\n",+ "print(f\"Research completed with {custom_summary['iterations']} iterations\")\n",+ "print(\"Questions researched:\")\n",+ "for iteration, questions in custom_summary['questions'].items():\n",+ " for q in questions:\n",+ " print(f\"- {q}\")\n",+ "\n",+ "# Print the first 500 characters of the summary\n",+ "print(\"\\nSummary preview:\")\n",+ "print(custom_summary[\"summary\"][:500] + \"...\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Generating a Comprehensive Report\n",+ "\n",+ "When you need more detailed research, use the `generate_report` function:"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Generate a comprehensive report\n",+ "report = generate_report(\"impact of artificial intelligence on healthcare\",\n",+ " iterations=1, \n",+ " questions_per_iteration=1, \n",+ " searches_per_section=1,\n",+ " )\n",+ "\n",+ "# Print report metadata\n",+ "print(\"Report metadata:\")\n",+ "for key, value in report[\"metadata\"].items():\n",+ " print(f\"- {key}: {value}\")\n",+ "\n",+ "# Preview the first 500 characters of the report\n",+ "print(\"\\nReport preview:\")\n",+ "print(report[\"content\"][:500] + \"...\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Saving the Report to a File"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Save the report content to a file\n",+ "with open(\"ai_healthcare_report.md\", \"w\", encoding=\"utf-8\") as f:\n",+ " f.write(report[\"content\"])\n",+ "\n",+ "print(\"Report saved to ai_healthcare_report.md\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Analyzing Local Documents\n",+ "\n",+ "If you have configured local document collections, you can search and analyze them:"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Get a list of available collections\n",+ "from local_deep_research.api import get_available_collections\n",+ "\n",+ "collections = get_available_collections()\n",+ "print(\"Available collections:\")\n",+ "for name, config in collections.items():\n",+ " print(f\"- {name}: {config.get('description', 'No description')}\")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# If you have a collection, you can analyze documents\n",+ "if collections:\n",+ " collection_name = next(iter(collections))\n",+ " \n",+ " analysis = analyze_documents(\n",+ " query=\"project requirements\",\n",+ " collection_name=collection_name\n",+ " )\n",+ " \n",+ " print(f\"\\nAnalysis results for collection '{collection_name}':\")\n",+ " print(f\"Found {len(analysis['documents'])} matching documents\")\n",+ " print(\"\\nSummary:\")\n",+ " print(analysis[\"summary\"])\n",+ "else:\n",+ " print(\"\\nNo collections configured. Please set up local document collections first.\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Checking Available Search Engines"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from local_deep_research.api import get_available_search_engines\n",+ "\n",+ "engines = get_available_search_engines()\n",+ "print(\"Available search engines:\")\n",+ "for name, description in engines.items():\n",+ " print(f\"- {name}: {description}\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Advanced Usage: Setting Custom Search Parameters"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Research with custom search settings\n",+ "advanced_summary = quick_summary(\n",+ " query=\"latest climate change research\",\n",+ " search_tool=\"auto\", # Auto-select best search engine\n",+ " iterations=2, # Perform 2 research cycles\n",+ " questions_per_iteration=3, # 3 questions per cycle\n",+ " max_results=50, # Consider up to 50 search results\n",+ " max_filtered_results=10, # Keep 10 most relevant results\n",+ " region=\"us\", # US region focus\n",+ " time_period=\"m\", # Focus on last month\n",+ " temperature=0.5 # Lower temperature for more focused generation\n",+ ")\n","\n",- "# Generate a quick summary\n",- "summary = quick_summary(\"advances in fusion energy\")\n",- "print(summary[\"summary\"])\n",- "\n"+ "print(f\"Research completed with {advanced_summary['iterations']} iterations\")\n",+ "print(f\"Generated {sum(len(qs) for qs in advanced_summary['questions'].values())} questions\")\n",+ "print(\"\\nSummary preview:\")\n",+ "print(advanced_summary[\"summary\"][:500] + \"...\")"]}],"metadata": {"kernelspec": {- "display_name": "venv",+ "display_name": "Python 3","language": "python","name": "python3"},@@ -130,9 +250,9 @@"name": "python","nbconvert_exporter": "python","pygments_lexer": "ipython3",- "version": "3.10.9"+ "version": "3.8.10"}},"nbformat": 4,- "nbformat_minor": 2+ "nbformat_minor": 4}