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.

fix: Enable generate_report() to work in programmatic mode (#619)

LearningCircuit421a69f5bfbe
diff --git a/Dockerfile b/Dockerfile
index e7c00f47da..93f6172c90 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -81,24 +81,27 @@ RUN playwright install --with-deps chromium || echo "Playwright install failed,
COPY tests/api_tests_with_login/package.json /install/tests/api_tests_with_login/
COPY tests/ui_tests/package.json /install/tests/ui_tests/
-# Install npm packages - Puppeteer will download Chrome since PUPPETEER_SKIP_CHROMIUM_DOWNLOAD is not set
+# Install npm packages - Skip Puppeteer Chrome download since we have Playwright's Chrome
WORKDIR /install/tests/api_tests_with_login
+ENV PUPPETEER_SKIP_DOWNLOAD=true
+ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
RUN npm install
WORKDIR /install/tests/ui_tests
RUN npm install
-# Set CHROME_BIN to help Puppeteer find Chrome
-# Try to find and set Chrome binary path
+# Set CHROME_BIN to help Puppeteer find Chrome from Playwright
+# Try to find and set Chrome binary path from Playwright's installation
RUN CHROME_PATH=$(find /root/.cache/ms-playwright -name chrome -type f 2>/dev/null | head -1) && \
if [ -n "$CHROME_PATH" ]; then \
echo "export CHROME_BIN=$CHROME_PATH" >> /etc/profile.d/chrome.sh; \
- else \
- CHROME_PATH=$(find /app/puppeteer-cache -name chrome -type f 2>/dev/null | head -1) && \
- if [ -n "$CHROME_PATH" ]; then \
- echo "export CHROME_BIN=$CHROME_PATH" >> /etc/profile.d/chrome.sh; \
- fi; \
+ echo "export PUPPETEER_EXECUTABLE_PATH=$CHROME_PATH" >> /etc/profile.d/chrome.sh; \
fi || true
+# Set environment variables for Puppeteer to use Playwright's Chrome
+ENV PUPPETEER_SKIP_DOWNLOAD=true
+ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
+ENV PUPPETEER_EXECUTABLE_PATH=/root/.cache/ms-playwright/chromium-1181/chrome-linux/chrome
+
# Copy test files to /app where they will be run from
RUN mkdir -p /app && cp -r /install/tests /app/
diff --git a/examples/api_usage/programmatic/README.md b/examples/api_usage/programmatic/README.md
index 1e7f704a07..c5395c9806 100644
--- a/examples/api_usage/programmatic/README.md
+++ b/examples/api_usage/programmatic/README.md
@@ -11,10 +11,12 @@ from local_deep_research.api import quick_summary, detailed_research
from local_deep_research.api.settings_utils import create_settings_snapshot
# Create settings for programmatic mode
-settings = create_settings_snapshot({
- "programmatic_mode": True,
- "search.tool": "wikipedia"
-})
+settings = create_settings_snapshot(
+ overrides={
+ "programmatic_mode": True,
+ "search.tool": "wikipedia"
+ }
+)
# Run research
result = quick_summary("your topic", settings_snapshot=settings)
@@ -25,9 +27,10 @@ result = quick_summary("your topic", settings_snapshot=settings)
| Example | Purpose | Key Features | Difficulty |
|---------|---------|--------------|------------|
| **minimal_working_example.py** | Simplest possible example | Basic setup, minimal code | Beginner |
-| **simple_programmatic_example.py** | Common use cases with the new API | quick_summary, detailed_research, custom parameters | Beginner |
+| **simple_programmatic_example.py** | Common use cases with the new API | quick_summary, detailed_research, generate_report, custom parameters | Beginner |
| **search_strategies_example.py** | Demonstrates search strategies | source-based vs focused-iteration strategies | Intermediate |
| **hybrid_search_example.py** | Combine multiple search sources | Multiple retrievers, web + retriever combo | Intermediate |
+| **advanced_features_example.py** | Advanced programmatic features | generate_report, export formats, result analysis, keyword extraction | Advanced |
| **custom_llm_retriever_example.py** | Custom LLM and retriever integration | Ollama, custom retrievers, FAISS | Advanced |
| **searxng_example.py** | Web search with SearXNG | SearXNG integration, error handling | Advanced |
@@ -43,6 +46,7 @@ result = quick_summary("your topic", settings_snapshot=settings)
**Purpose:** Demonstrate the main API functions with practical examples.
- `quick_summary()` - Fast research with summary
- `detailed_research()` - Comprehensive research with findings
+- `generate_report()` - Create full markdown reports
- Custom search parameters
- Different search tools (Wikipedia, auto, etc.)
@@ -60,6 +64,14 @@ result = quick_summary("your topic", settings_snapshot=settings)
- Source analysis and tracking
- Meta search configuration
+### advanced_features_example.py
+**Purpose:** Demonstrate advanced programmatic features and analysis capabilities.
+- `generate_report()` - Create comprehensive markdown reports
+- Export formats - JSON, Markdown, custom formats
+- Result analysis - Extract insights and patterns
+- Keyword extraction - Identify key terms and concepts
+- Batch research - Process multiple queries efficiently
+
### custom_llm_retriever_example.py
**Purpose:** Advanced integration with custom components.
- Custom LLM implementation (using Ollama)
@@ -79,7 +91,7 @@ result = quick_summary("your topic", settings_snapshot=settings)
### Programmatic Mode
All examples use `programmatic_mode: True` in settings to bypass authentication:
```python
-settings = create_settings_snapshot({"programmatic_mode": True})
+settings = create_settings_snapshot(overrides={"programmatic_mode": True})
```
### Search Strategies
@@ -113,7 +125,7 @@ Generate a quick research summary:
from local_deep_research.api import quick_summary
from local_deep_research.api.settings_utils import create_settings_snapshot
-settings = create_settings_snapshot({"programmatic_mode": True})
+settings = create_settings_snapshot(overrides={"programmatic_mode": True})
result = quick_summary(
query="Your research question",
settings_snapshot=settings,
@@ -137,11 +149,12 @@ result = detailed_research(
```
### `generate_report()`
-*Note: Currently requires authentication. Fix coming in separate PR.*
+Generate comprehensive markdown reports with structured sections:
```python
from local_deep_research.api import generate_report
+from local_deep_research.api.settings_utils import create_settings_snapshot
-# After auth fix is merged:
+settings = create_settings_snapshot(overrides={"programmatic_mode": True})
result = generate_report(
query="Your research question",
settings_snapshot=settings,
@@ -183,7 +196,7 @@ result = generate_report(
### "No settings context available" Error
Make sure to pass `settings_snapshot` to all API functions:
```python
-settings = create_settings_snapshot({"programmatic_mode": True})
+settings = create_settings_snapshot(overrides={"programmatic_mode": True})
result = quick_summary("topic", settings_snapshot=settings)
```
@@ -199,9 +212,6 @@ Start a SearXNG instance or use the fallback in the example:
docker run -p 8080:8080 searxng/searxng
```
-## Coming Soon
-
-The `generate_report()` function currently requires authentication. A fix is planned in a separate PR to enable programmatic report generation without authentication.
## Contributing
diff --git a/examples/api_usage/programmatic/advanced_features_example.py b/examples/api_usage/programmatic/advanced_features_example.py
new file mode 100644
index 0000000000..123a408b0e
--- /dev/null
+++ b/examples/api_usage/programmatic/advanced_features_example.py
@@ -0,0 +1,611 @@
+#!/usr/bin/env python3
+"""
+Advanced Features Example for Local Deep Research
+
+This example demonstrates advanced programmatic features including:
+1. generate_report() - Create comprehensive markdown reports
+2. Export formats - Save reports in different formats
+3. Result analysis - Extract and analyze research findings
+4. Keyword extraction - Identify key topics and concepts
+"""
+
+import json
+from typing import Dict, List, Any
+
+from local_deep_research.api import (
+ generate_report,
+ detailed_research,
+ quick_summary,
+)
+from local_deep_research.api.settings_utils import create_settings_snapshot
+
+
+def demonstrate_report_generation():
+ """
+ Generate a comprehensive research report using generate_report().
+
+ This function creates a structured markdown report with:
+ - Executive summary
+ - Detailed findings organized by sections
+ - Source citations
+ - Conclusions and recommendations
+ """
+ print("=" * 70)
+ print("GENERATE COMPREHENSIVE REPORT")
+ print("=" * 70)
+ print("""
+This demonstrates the generate_report() function which:
+- Creates a structured markdown report
+- Performs multiple searches per section
+- Organizes findings into coherent sections
+- Includes citations and references
+ """)
+
+ # Configure settings for programmatic mode
+ settings = create_settings_snapshot(
+ overrides={
+ "programmatic_mode": True,
+ "search.tool": "wikipedia",
+ "llm.temperature": 0.5, # Lower for more focused output
+ }
+ )
+
+ # Generate a comprehensive report
+ print(
+ "Generating report on 'Applications of Machine Learning in Healthcare'..."
+ )
+ report = generate_report(
+ query="Applications of Machine Learning in Healthcare",
+ output_file="ml_healthcare_report.md",
+ searches_per_section=2, # Multiple searches per section for depth
+ settings_snapshot=settings,
+ iterations=2,
+ questions_per_iteration=3,
+ )
+
+ print("\n✓ Report generated successfully!")
+ print(f" - Report length: {len(report['content'])} characters")
+ print(
+ f" - File saved to: {report.get('file_path', 'ml_healthcare_report.md')}"
+ )
+
+ # Show first part of report
+ print("\nReport preview (first 500 chars):")
+ print("-" * 40)
+ print(report["content"][:500] + "...")
+
+ return report
+
+
+def demonstrate_export_formats():
+ """
+ Show how to export research results in different formats.
+
+ Demonstrates:
+ - Markdown export (default)
+ - JSON export for programmatic processing
+ - Custom formatting with templates
+ """
+ print("\n" + "=" * 70)
+ print("EXPORT FORMATS")
+ print("=" * 70)
+ print("""
+Exporting research in different formats:
+- Markdown: Human-readable reports
+- JSON: Structured data for processing
+- Custom: Template-based formatting
+ """)
+
+ settings = create_settings_snapshot(
+ overrides={
+ "programmatic_mode": True,
+ "search.tool": "wikipedia",
+ }
+ )
+
+ # Get research results
+ result = detailed_research(
+ query="Renewable energy technologies",
+ settings_snapshot=settings,
+ iterations=1,
+ questions_per_iteration=2,
+ )
+
+ # Export as JSON
+ json_file = "research_results.json"
+ with open(json_file, "w", encoding="utf-8") as f:
+ json.dump(result, f, indent=2, default=str)
+ print(f"\n✓ JSON export saved to: {json_file}")
+ print(f" - Contains: {len(result.get('findings', []))} findings")
+ print(f" - Sources: {len(result.get('sources', []))} sources")
+
+ # Export as Markdown
+ md_content = format_as_markdown(result)
+ md_file = "research_results.md"
+ with open(md_file, "w", encoding="utf-8") as f:
+ f.write(md_content)
+ print(f"\n✓ Markdown export saved to: {md_file}")
+ print(f" - Length: {len(md_content)} characters")
+
+ # Export as custom format (e.g., BibTeX-like citations)
+ citations = extract_citations(result)
+ cite_file = "research_citations.txt"
+ with open(cite_file, "w", encoding="utf-8") as f:
+ for i, citation in enumerate(citations, 1):
+ f.write(f"[{i}] {citation}\n")
+ print(f"\n✓ Citations export saved to: {cite_file}")
+ print(f" - Total citations: {len(citations)}")
+
+ return result
+
+
+def demonstrate_result_analysis():
+ """
+ Analyze research results to extract insights and patterns.
+
+ Shows how to:
+ - Extract key findings
+ - Identify recurring themes
+ - Analyze source reliability
+ - Generate statistics
+ """
+ print("\n" + "=" * 70)
+ print("RESULT ANALYSIS")
+ print("=" * 70)
+ print("""
+Analyzing research results to extract:
+- Key findings and insights
+- Common themes and patterns
+- Source statistics
+- Quality metrics
+ """)
+
+ settings = create_settings_snapshot(
+ overrides={
+ "programmatic_mode": True,
+ "search.tool": "wikipedia",
+ }
+ )
+
+ # Perform research
+ result = detailed_research(
+ query="Impact of artificial intelligence on employment",
+ settings_snapshot=settings,
+ search_strategy="source-based",
+ iterations=2,
+ questions_per_iteration=3,
+ )
+
+ # Analyze findings
+ analysis = analyze_findings(result)
+
+ print("\n📊 Research Analysis:")
+ print(f" - Total findings: {analysis['total_findings']}")
+ print(f" - Unique sources: {analysis['unique_sources']}")
+ print(f" - Questions explored: {analysis['total_questions']}")
+ print(f" - Iterations completed: {analysis['iterations']}")
+
+ print("\n🔍 Finding Categories:")
+ for category, count in analysis["categories"].items():
+ print(f" - {category}: {count} findings")
+
+ print("\n📈 Source Distribution:")
+ for source_type, count in analysis["source_types"].items():
+ print(f" - {source_type}: {count} sources")
+
+ # Extract themes
+ themes = extract_themes(result)
+ print("\n🎯 Key Themes Identified:")
+ for i, theme in enumerate(themes[:5], 1):
+ print(f" {i}. {theme}")
+
+ return analysis
+
+
+def demonstrate_keyword_extraction():
+ """
+ Extract keywords and key concepts from research results.
+
+ Demonstrates:
+ - Keyword extraction from findings
+ - Concept identification
+ - Topic clustering
+ - Trend analysis
+ """
+ print("\n" + "=" * 70)
+ print("KEYWORD & CONCEPT EXTRACTION")
+ print("=" * 70)
+ print("""
+Extracting keywords and concepts:
+- Important terms and phrases
+- Technical concepts
+- Named entities
+- Trend indicators
+ """)
+
+ settings = create_settings_snapshot(
+ overrides={
+ "programmatic_mode": True,
+ "search.tool": "wikipedia",
+ }
+ )
+
+ # Quick research for keyword extraction
+ result = quick_summary(
+ query="Quantum computing breakthroughs 2024",
+ settings_snapshot=settings,
+ iterations=1,
+ questions_per_iteration=3,
+ )
+
+ # Extract keywords
+ keywords = extract_keywords(result)
+
+ print("\n🔑 Top Keywords:")
+ for keyword, frequency in keywords[:10]:
+ print(f" - {keyword}: {frequency} occurrences")
+
+ # Extract concepts
+ concepts = extract_concepts(result)
+
+ print("\n💡 Key Concepts:")
+ for i, concept in enumerate(concepts[:5], 1):
+ print(f" {i}. {concept}")
+
+ # Identify technical terms
+ technical_terms = extract_technical_terms(result)
+
+ print("\n🔬 Technical Terms:")
+ for term in technical_terms[:8]:
+ print(f" - {term}")
+
+ return keywords, concepts
+
+
+def format_as_markdown(result: Dict[str, Any]) -> str:
+ """Convert research results to markdown format."""
+ md = f"# Research Report: {result['query']}\n\n"
+ md += f"**Research ID:** {result.get('research_id', 'N/A')}\n\n"
+
+ # Summary
+ md += "## Summary\n\n"
+ md += result.get("summary", "No summary available") + "\n\n"
+
+ # Findings
+ md += "## Key Findings\n\n"
+ findings = result.get("findings", [])
+ for i, finding in enumerate(findings, 1):
+ finding_text = finding if isinstance(finding, str) else str(finding)
+ md += f"{i}. {finding_text}\n\n"
+
+ # Sources
+ md += "## Sources\n\n"
+ sources = result.get("sources", [])
+ for i, source in enumerate(sources, 1):
+ source_text = source if isinstance(source, str) else str(source)
+ md += f"- [{i}] {source_text}\n"
+
+ # Metadata
+ md += "\n## Metadata\n\n"
+ metadata = result.get("metadata", {})
+ for key, value in metadata.items():
+ md += f"- **{key}:** {value}\n"
+
+ return md
+
+
+def extract_citations(result: Dict[str, Any]) -> List[str]:
+ """Extract citations from research results."""
+ citations = []
+ sources = result.get("sources", [])
+
+ for source in sources:
+ if isinstance(source, dict):
+ # Extract URL or title
+ citation = source.get("url", source.get("title", str(source)))
+ else:
+ citation = str(source)
+ citations.append(citation)
+
+ return citations
+
+
+def analyze_findings(result: Dict[str, Any]) -> Dict[str, Any]:
+ """Analyze research findings for patterns and statistics."""
+ findings = result.get("findings", [])
+ sources = result.get("sources", [])
+ questions = result.get("questions", {})
+
+ # Categorize findings (simplified)
+ categories = {
+ "positive": 0,
+ "negative": 0,
+ "neutral": 0,
+ "technical": 0,
+ }
+
+ for finding in findings:
+ finding_text = str(finding).lower()
+ if any(
+ word in finding_text
+ for word in ["benefit", "improve", "enhance", "positive"]
+ ):
+ categories["positive"] += 1
+ elif any(
+ word in finding_text
+ for word in ["risk", "challenge", "negative", "concern"]
+ ):
+ categories["negative"] += 1
+ elif any(
+ word in finding_text
+ for word in ["algorithm", "system", "technology", "method"]
+ ):
+ categories["technical"] += 1
+ else:
+ categories["neutral"] += 1
+
+ # Analyze sources
+ source_types = {}
+ for source in sources:
+ source_text = str(source).lower()
+ if "wikipedia" in source_text:
+ source_type = "Wikipedia"
+ elif "arxiv" in source_text:
+ source_type = "ArXiv"
+ elif "github" in source_text:
+ source_type = "GitHub"
+ else:
+ source_type = "Other"
+ source_types[source_type] = source_types.get(source_type, 0) + 1
+
+ return {
+ "total_findings": len(findings),
+ "unique_sources": len(sources),
+ "total_questions": sum(len(qs) for qs in questions.values()),
+ "iterations": result.get("iterations", 0),
+ "categories": categories,
+ "source_types": source_types,
+ }
+
+
+def extract_themes(result: Dict[str, Any]) -> List[str]:
+ """Extract main themes from research results."""
+ # Simplified theme extraction based on common patterns
+ themes = []
+ summary = result.get("summary", "")
+ findings = result.get("findings", [])
+
+ # Combine text for analysis
+ full_text = summary + " ".join(str(f) for f in findings)
+
+ # Simple theme patterns (in production, use NLP libraries)
+ theme_patterns = {
+ "automation": ["automation", "automated", "automatic"],
+ "job displacement": ["job loss", "unemployment", "displacement"],
+ "skill requirements": ["skills", "training", "education"],
+ "economic impact": ["economy", "economic", "gdp", "growth"],
+ "innovation": ["innovation", "innovative", "breakthrough"],
+ }
+
+ for theme, keywords in theme_patterns.items():
+ if any(keyword in full_text.lower() for keyword in keywords):
+ themes.append(theme.title())
+
+ return themes
+
+
+def extract_keywords(result: Dict[str, Any]) -> List[tuple]:
+ """Extract keywords with frequency from research results."""
+ from collections import Counter
+ import re
+
+ # Combine all text
+ summary = result.get("summary", "")
+ findings = " ".join(str(f) for f in result.get("findings", []))
+ full_text = f"{summary} {findings}".lower()
+
+ # Simple word extraction (in production, use NLP libraries)
+ words = re.findall(r"\b[a-z]{4,}\b", full_text)
+
+ # Filter common words
+ stopwords = {
+ "that",
+ "this",
+ "with",
+ "from",
+ "have",
+ "been",
+ "were",
+ "which",
+ "their",
+ "about",
+ }
+ words = [w for w in words if w not in stopwords]
+
+ # Count frequencies
+ word_freq = Counter(words)
+
+ return word_freq.most_common(20)
+
+
+def extract_concepts(result: Dict[str, Any]) -> List[str]:
+ """Extract key concepts from research results."""
+ concepts = []
+ summary = result.get("summary", "")
+
+ # Simple concept patterns (in production, use NLP for entity extraction)
+ concept_patterns = [
+ r"quantum \w+",
+ r"\w+ computing",
+ r"\w+ algorithm",
+ r"machine learning",
+ r"artificial intelligence",
+ r"\w+ technology",
+ ]
+
+ import re
+
+ for pattern in concept_patterns:
+ matches = re.findall(pattern, summary.lower())
+ concepts.extend(matches)
+
+ # Deduplicate and clean
+ concepts = list(set(concepts))
+
+ return concepts[:10]
+
+
+def extract_technical_terms(result: Dict[str, Any]) -> List[str]:
+ """Extract technical terms from research results."""
+ technical_terms = []
+
+ # Common technical term patterns
+ tech_indicators = [
+ "algorithm",
+ "system",
+ "protocol",
+ "framework",
+ "architecture",
+ "quantum",
+ "neural",
+ "network",
+ "model",
+ "optimization",
+ ]
+
+ summary = result.get("summary", "").lower()
+ import re
+
+ for indicator in tech_indicators:
+ # Find words containing or adjacent to technical indicators
+ pattern = rf"\b\w*{indicator}\w*\b"
+ matches = re.findall(pattern, summary)
+ technical_terms.extend(matches)
+
+ # Deduplicate
+ technical_terms = list(set(technical_terms))
+
+ return technical_terms
+
+
+def demonstrate_batch_research():
+ """
+ Show how to perform batch research on multiple topics.
+
+ Useful for:
+ - Comparative analysis
+ - Trend monitoring
+ - Systematic reviews
+ """
+ print("\n" + "=" * 70)
+ print("BATCH RESEARCH PROCESSING")
+ print("=" * 70)
+ print("""
+Processing multiple research queries:
+- Efficient batch processing
+- Comparative analysis
+- Result aggregation
+ """)
+
+ settings = create_settings_snapshot(
+ overrides={
+ "programmatic_mode": True,
+ "search.tool": "wikipedia",
+ }
+ )
+
+ # Topics for batch research
+ topics = [
+ "Solar energy innovations",
+ "Wind power technology",
+ "Hydrogen fuel cells",
+ ]
+
+ batch_results = {}
+
+ print("\n📚 Batch Research:")
+ for topic in topics:
+ print(f"\n Researching: {topic}")
+ result = quick_summary(
+ query=topic,
+ settings_snapshot=settings,
+ iterations=1,
+ questions_per_iteration=2,
+ )
+ batch_results[topic] = result
+ print(f" ✓ Found {len(result.get('findings', []))} findings")
+
+ # Aggregate results
+ print("\n📊 Aggregate Analysis:")
+ total_findings = sum(
+ len(r.get("findings", [])) for r in batch_results.values()
+ )
+ total_sources = sum(
+ len(r.get("sources", [])) for r in batch_results.values()
+ )
+
+ print(f" - Total topics researched: {len(topics)}")
+ print(f" - Total findings: {total_findings}")
+ print(f" - Total sources: {total_sources}")
+ print(f" - Average findings per topic: {total_findings / len(topics):.1f}")
+
+ # Save batch results
+ batch_file = "batch_research_results.json"
+ with open(batch_file, "w", encoding="utf-8") as f:
+ json.dump(batch_results, f, indent=2, default=str)
+ print(f"\n✓ Batch results saved to: {batch_file}")
+
+ return batch_results
+
+
+def main():
+ """Run all advanced feature demonstrations."""
+ print("=" * 70)
+ print("LOCAL DEEP RESEARCH - ADVANCED FEATURES DEMONSTRATION")
+ print("=" * 70)
+ print("""
+This example demonstrates advanced programmatic features:
+1. Report generation with generate_report()
+2. Multiple export formats
+3. Result analysis and insights
+4. Keyword and concept extraction
+5. Batch research processing
+ """)
+
+ # Run demonstrations
+ demonstrate_report_generation()
+ demonstrate_export_formats()
+ demonstrate_result_analysis()
+ demonstrate_keyword_extraction()
+ demonstrate_batch_research()
+
+ print("\n" + "=" * 70)
+ print("DEMONSTRATION COMPLETE")
+ print("=" * 70)
+ print("""
+✓ All advanced features demonstrated successfully!
+
+Key Takeaways:
+1. generate_report() creates comprehensive markdown reports
+2. Results can be exported in multiple formats (JSON, MD, custom)
+3. Analysis tools extract insights, themes, and patterns
+4. Keyword extraction identifies important terms and concepts
+5. Batch processing enables systematic research
+
+Files created:
+- ml_healthcare_report.md - Full research report
+- research_results.json - Structured research data
+- research_results.md - Markdown formatted results
+- research_citations.txt - Extracted citations
+- batch_research_results.json - Batch research results
+
+Next Steps:
+- Customize report templates for your domain
+- Integrate with data visualization tools
+- Build automated research pipelines
+- Create domain-specific analysis functions
+ """)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/api_usage/programmatic/hybrid_search_example.py b/examples/api_usage/programmatic/hybrid_search_example.py
index c24afd7a20..5ce89c5f15 100644
--- a/examples/api_usage/programmatic/hybrid_search_example.py
+++ b/examples/api_usage/programmatic/hybrid_search_example.py
@@ -129,7 +129,7 @@ Each provides different perspectives on the same topic.
# Configure settings
settings = create_settings_snapshot(
- {
+ overrides={
"programmatic_mode": True,
"search.tool": "auto", # Will use all provided retrievers
}
@@ -189,7 +189,7 @@ This provides both specific and general information.
# Configure settings to use both retriever and web
settings = create_settings_snapshot(
- {
+ overrides={
"programmatic_mode": True,
"search.tool": "wikipedia", # Also use Wikipedia
}
@@ -255,7 +255,7 @@ Analyzing source quality and relevance:
business_retriever = BusinessDocsRetriever()
settings = create_settings_snapshot(
- {
+ overrides={
"programmatic_mode": True,
"search.tool": "wikipedia",
}
@@ -328,7 +328,7 @@ Using meta search for sophisticated search strategies:
tech_retriever = TechnicalDocsRetriever()
settings = create_settings_snapshot(
- {
+ overrides={
"programmatic_mode": True,
}
)
diff --git a/examples/api_usage/programmatic/search_strategies_example.py b/examples/api_usage/programmatic/search_strategies_example.py
index fb23afd30e..0852857b56 100644
--- a/examples/api_usage/programmatic/search_strategies_example.py
+++ b/examples/api_usage/programmatic/search_strategies_example.py
@@ -33,7 +33,7 @@ This strategy:
# Configure settings for programmatic mode
settings = create_settings_snapshot(
- {
+ overrides={
"programmatic_mode": True,
"search.tool": "wikipedia", # Using Wikipedia for demonstration
}
@@ -91,7 +91,7 @@ This strategy:
# Configure settings
settings = create_settings_snapshot(
- {
+ overrides={
"programmatic_mode": True,
"search.tool": "wikipedia",
}
@@ -147,7 +147,7 @@ def compare_strategies():
)
settings = create_settings_snapshot(
- {
+ overrides={
"programmatic_mode": True,
"search.tool": "wikipedia",
}
diff --git a/examples/api_usage/programmatic/simple_programmatic_example.py b/examples/api_usage/programmatic/simple_programmatic_example.py
index 68a081777c..d8c9d17b35 100755
--- a/examples/api_usage/programmatic/simple_programmatic_example.py
+++ b/examples/api_usage/programmatic/simple_programmatic_example.py
@@ -5,7 +5,11 @@ Simple Programmatic API Example for Local Deep Research
Quick example showing how to use the LDR Python API directly.
"""
-from local_deep_research.api import detailed_research, quick_summary
+from local_deep_research.api import (
+ detailed_research,
+ quick_summary,
+ generate_report,
+)
from local_deep_research.api.settings_utils import (
create_settings_snapshot,
)
@@ -62,24 +66,18 @@ print(
)
# Example 4: Generate and Save a Report
-print("\n=== Generate Report (Optional - Uncomment to run) ===")
+print("\n=== Generate Report ===")
print("Note: Report generation can take several minutes")
-# TODO: generate_report() currently requires authentication to work properly.
-# This will be fixed in a separate PR to enable programmatic report generation.
-# See: https://github.com/[org]/[repo]/issues/[number] for tracking
-
-# Uncomment the following to generate a full report (after auth fix):
-"""
-from local_deep_research.api import generate_report
-
+# Generate a comprehensive report
report = generate_report(
query="Future of artificial intelligence",
output_file="ai_future_report.md", # Save directly to file
searches_per_section=2,
iterations=1,
- settings_snapshot=settings_snapshot # Will work after auth fix
+ settings_snapshot=settings_snapshot, # Now works with programmatic mode!
)
print(f"Report saved to: {report.get('file_path', 'ai_future_report.md')}")
print(f"Report length: {len(report['content'])} characters")
-"""
+print("Report preview (first 300 chars):")
+print(report["content"][:300] + "...")
diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.py
index a3968185fd..d23593e203 100644
--- a/src/local_deep_research/api/research_functions.py
+++ b/src/local_deep_research/api/research_functions.py
@@ -290,6 +290,12 @@ def generate_report(
searches_per_section: int = 2,
retrievers: Optional[Dict[str, Any]] = None,
llms: Optional[Dict[str, Any]] = None,
+ provider: Optional[str] = None,
+ api_key: Optional[str] = None,
+ temperature: Optional[float] = None,
+ max_search_results: Optional[int] = None,
+ settings: Optional[Dict[str, Any]] = None,
+ settings_override: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> Dict[str, Any]:
"""
@@ -303,14 +309,56 @@ def generate_report(
section in the report.
retrievers: Optional dictionary of {name: retriever} pairs to use as search engines
llms: Optional dictionary of {name: llm} pairs to use as language models
+ provider: LLM provider to use (e.g., 'openai', 'anthropic'). For programmatic API only.
+ api_key: API key for the provider. For programmatic API only.
+ temperature: LLM temperature (0.0-1.0). For programmatic API only.
+ max_search_results: Maximum number of search results to return. For programmatic API only.
+ settings: Base settings dict to use instead of defaults. For programmatic API only.
+ settings_override: Dictionary of settings to override. For programmatic API only.
+ **kwargs: Additional configuration for the search system.
Returns:
Dictionary containing the research report with keys:
- 'content': The full report content in markdown format
- 'metadata': Report metadata including generated timestamp and query
+ - 'file_path': Path to saved file (if output_file was provided)
+
+ Examples:
+ # Simple usage with settings snapshot
+ from local_deep_research.api.settings_utils import create_settings_snapshot
+ settings = create_settings_snapshot({"programmatic_mode": True})
+ result = generate_report("AI research", settings_snapshot=settings)
+
+ # Save to file
+ result = generate_report(
+ "AI research",
+ output_file="report.md",
+ settings_snapshot=settings
+ )
"""
logger.info("Generating comprehensive research report for query: %s", query)
+ # Only create settings snapshot if not already provided (programmatic API)
+ if "settings_snapshot" not in kwargs:
+ # Build kwargs for create_settings_snapshot from explicit parameters
+ snapshot_kwargs = {}
+ if provider is not None:
+ snapshot_kwargs["provider"] = provider
+ if api_key is not None:
+ snapshot_kwargs["api_key"] = api_key
+ if temperature is not None:
+ snapshot_kwargs["temperature"] = temperature
+ if max_search_results is not None:
+ snapshot_kwargs["max_search_results"] = max_search_results
+
+ # Create settings snapshot for programmatic use
+ kwargs["settings_snapshot"] = create_settings_snapshot(
+ base_settings=settings,
+ overrides=settings_override,
+ **snapshot_kwargs,
+ )
+ logger.debug("Created settings snapshot for programmatic API")
+
# Register retrievers if provided
if retrievers:
from ..web_search_engines.retriever_registry import retriever_registry
diff --git a/src/local_deep_research/report_generator.py b/src/local_deep_research/report_generator.py
index d11ef08d6b..4c291a07da 100644
--- a/src/local_deep_research/report_generator.py
+++ b/src/local_deep_research/report_generator.py
@@ -33,14 +33,21 @@ class IntegratedReportGenerator:
section in the report.
search_system: Custom search system to use, otherwise just uses
the default.
- llm: Custom LLM to use, otherwise just uses the default.
+ llm: Custom LLM to use. Required if search_system is not provided.
"""
- self.model = llm or get_llm()
- # Use provided search_system or create a new one
- self.search_system = search_system or AdvancedSearchSystem(
- llm=self.model
- )
+ # If search_system is provided, use its LLM; otherwise use the provided LLM
+ if search_system:
+ self.search_system = search_system
+ self.model = llm or search_system.model
+ elif llm:
+ self.model = llm
+ self.search_system = AdvancedSearchSystem(llm=self.model)
+ else:
+ # Fallback for backwards compatibility - will only work with auth
+ self.model = get_llm()
+ self.search_system = AdvancedSearchSystem(llm=self.model)
+
self.searches_per_section = (
searches_per_section # Control search depth per section
)