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.

feat: Add simplified API client with automatic CSRF handling

LearningCircuitef32e88aefc7
diff --git a/README.md b/README.md
index bfd9ccaf67..a302bb3d73 100644
--- a/README.md
+++ b/README.md
@@ -226,21 +226,17 @@ python -m local_deep_research.web.app
### Python API
```python
-from local_deep_research.api import quick_summary
-from local_deep_research.settings import CachedSettingsManager
-from local_deep_research.database.session_context import get_user_db_session
-
-# Authentication required - use with user session
-with get_user_db_session(username="your_username", password="your_password") as session:
- settings_manager = CachedSettingsManager(session, "your_username")
- settings_snapshot = settings_manager.get_all_settings()
-
- # Simple usage with settings
- result = quick_summary(
- query="What are the latest advances in quantum computing?",
- settings_snapshot=settings_snapshot
- )
- print(result["summary"])
+from local_deep_research.api import LDRClient, quick_query
+
+# Option 1: Simplest - one line research
+summary = quick_query("username", "password", "What is quantum computing?")
+print(summary)
+
+# Option 2: Client for multiple operations
+client = LDRClient()
+client.login("username", "password")
+result = client.quick_research("What are the latest advances in quantum computing?")
+print(result["summary"])
```
### HTTP API
diff --git a/docs/api-quickstart.md b/docs/api-quickstart.md
index dcdc3686eb..5a50964951 100644
--- a/docs/api-quickstart.md
+++ b/docs/api-quickstart.md
@@ -4,6 +4,26 @@
Local Deep Research provides both HTTP REST API and programmatic Python API access. Since version 2.0, authentication is required for all API endpoints, and the system uses per-user encrypted databases.
+## Simplest Usage - Python Client
+
+The easiest way to use the API is with the built-in client that handles all authentication complexity:
+
+```python
+from local_deep_research.api import LDRClient, quick_query
+
+# One-liner for quick research
+summary = quick_query("username", "password", "What is DNA?")
+print(summary)
+
+# Or use the client for multiple operations
+client = LDRClient()
+client.login("username", "password")
+result = client.quick_research("What is machine learning?")
+print(result["summary"])
+```
+
+No need to worry about CSRF tokens, HTML parsing, or session management!
+
## Authentication
### Web UI Authentication
diff --git a/examples/api_usage/simple_client_example.py b/examples/api_usage/simple_client_example.py
new file mode 100644
index 0000000000..afa0742264
--- /dev/null
+++ b/examples/api_usage/simple_client_example.py
@@ -0,0 +1,131 @@
+#!/usr/bin/env python3
+"""
+Simple API Client Example - No more CSRF complexity!
+
+This shows how easy it is to use the LDR API with the new client.
+All the CSRF token handling is done automatically.
+"""
+
+from local_deep_research.api import LDRClient, quick_query
+
+# Configuration
+USERNAME = "your_username" # Change this!
+PASSWORD = "your_password" # Change this!
+
+
+def example_1_simple():
+ """Simplest possible usage - one line research."""
+ print("=== Example 1: One-liner ===")
+
+ # Just one line to get a research summary!
+ summary = quick_query(USERNAME, PASSWORD, "What is machine learning?")
+ print(f"Summary: {summary[:200]}...")
+
+
+def example_2_client():
+ """Using the client for multiple operations."""
+ print("\n=== Example 2: Client Usage ===")
+
+ # Create client
+ client = LDRClient()
+
+ # Login once
+ if not client.login(USERNAME, PASSWORD):
+ print("Login failed!")
+ return
+
+ # Now just use it - no more CSRF hassles!
+ try:
+ # Do research
+ result = client.quick_research("What are neural networks?")
+ print("Research complete!")
+ print(f"Summary: {result['summary'][:200]}...")
+ print(f"Sources found: {len(result.get('sources', []))}")
+
+ # Check settings
+ settings = client.get_settings()
+ print(
+ f"\nYou have {len(settings.get('settings', {}))} settings configured"
+ )
+
+ # Get history
+ history = client.get_history()
+ print(f"You have {len(history)} items in history")
+
+ finally:
+ client.logout()
+
+
+def example_3_context_manager():
+ """Using context manager for automatic cleanup."""
+ print("\n=== Example 3: Context Manager ===")
+
+ # Automatic login/logout with context manager
+ with LDRClient() as client:
+ if client.login(USERNAME, PASSWORD):
+ # Start research without waiting
+ result = client.quick_research(
+ "What is quantum computing?", wait_for_result=False
+ )
+ print(f"Research started with ID: {result['research_id']}")
+
+ # Do other things...
+ print("Doing other work while research runs...")
+
+ # Later, get the results
+ final_result = client.wait_for_research(result["research_id"])
+ print(f"Research complete: {final_result['summary'][:100]}...")
+
+
+def example_4_batch_research():
+ """Running multiple research queries efficiently."""
+ print("\n=== Example 4: Batch Research ===")
+
+ questions = [
+ "What is DNA?",
+ "How do vaccines work?",
+ "What causes earthquakes?",
+ ]
+
+ with LDRClient() as client:
+ if not client.login(USERNAME, PASSWORD):
+ print("Login failed!")
+ return
+
+ # Start all research tasks
+ research_ids = []
+ for question in questions:
+ result = client.quick_research(question, wait_for_result=False)
+ research_ids.append((question, result["research_id"]))
+ print(f"Started: {question}")
+
+ print("\nWaiting for all results...")
+
+ # Collect all results
+ for question, research_id in research_ids:
+ try:
+ result = client.wait_for_research(research_id, timeout=120)
+ print(f"\n{question}")
+ print(f"→ {result['summary'][:150]}...")
+ except Exception as e:
+ print(f"\n{question}")
+ print(f"→ Error: {e}")
+
+
+if __name__ == "__main__":
+ print("LDR Simple Client Examples")
+ print("=" * 50)
+ print("\nBefore: Complex CSRF handling, HTML parsing, manual polling...")
+ print("After: Just login() and quick_research()!")
+ print("\nMake sure:")
+ print("1. LDR server is running: python -m local_deep_research.web.app")
+ print("2. You've updated USERNAME and PASSWORD in this script")
+ print("=" * 50)
+
+ # Uncomment the examples you want to run:
+ # example_1_simple()
+ # example_2_client()
+ # example_3_context_manager()
+ # example_4_batch_research()
+
+ print("\nUncomment the examples in the script to run them!")
diff --git a/src/local_deep_research/api/__init__.py b/src/local_deep_research/api/__init__.py
index 37cee2150f..be488fe901 100644
--- a/src/local_deep_research/api/__init__.py
+++ b/src/local_deep_research/api/__init__.py
@@ -14,6 +14,10 @@ from .settings_utils import (
get_default_settings_snapshot,
extract_setting_value,
)
+from .client import (
+ LDRClient,
+ quick_query,
+)
from ..news import (
get_news_feed,
@@ -23,13 +27,19 @@ from ..news import (
)
__all__ = [
+ # Research functions
"analyze_documents",
"detailed_research",
"generate_report",
"quick_summary",
+ # Settings utilities
"create_settings_snapshot",
"get_default_settings_snapshot",
"extract_setting_value",
+ # HTTP Client
+ "LDRClient",
+ "quick_query",
+ # News functions
"get_news_feed",
"research_news_item",
"save_news_preferences",
diff --git a/src/local_deep_research/api/client.py b/src/local_deep_research/api/client.py
new file mode 100644
index 0000000000..68eb83c7a4
--- /dev/null
+++ b/src/local_deep_research/api/client.py
@@ -0,0 +1,353 @@
+"""
+HTTP Client for Local Deep Research API.
+Simplifies authentication and API access by handling CSRF tokens automatically.
+
+Why CSRF with login?
+--------------------
+CSRF tokens prevent cross-site request forgery attacks. Even though you're logged in,
+CSRF ensures requests come from YOUR code, not from malicious websites that might
+try to use your browser's active session cookies to make unauthorized requests.
+
+Example usage:
+-------------
+ from local_deep_research.api.client import LDRClient
+
+ # Simple usage
+ client = LDRClient()
+ client.login("username", "password")
+ result = client.quick_research("What is quantum computing?")
+ print(result["summary"])
+
+ # Or use the one-liner
+ from local_deep_research.api.client import quick_query
+ summary = quick_query("username", "password", "What is DNA?")
+"""
+
+import requests
+import time
+from typing import Optional, Dict, Any, List
+from loguru import logger
+
+
+class LDRClient:
+ """
+ HTTP client for LDR API access with automatic CSRF handling.
+
+ This client abstracts away the complexity of:
+ - Extracting CSRF tokens from HTML forms
+ - Managing session cookies
+ - Handling authentication flow
+ - Polling for research results
+ """
+
+ def __init__(self, base_url: str = "http://localhost:5000"):
+ """
+ Initialize the client.
+
+ Args:
+ base_url: URL of the LDR server (default: http://localhost:5000)
+ """
+ self.base_url = base_url
+ self.session = requests.Session()
+ self.csrf_token = None
+ self.logged_in = False
+ self.username = None
+
+ def login(self, username: str, password: str) -> bool:
+ """
+ Login to LDR server. Handles all CSRF complexity internally.
+
+ This method:
+ 1. Gets the login page to extract CSRF token from HTML form
+ 2. Submits login with form data (not JSON)
+ 3. Retrieves CSRF token for subsequent API calls
+
+ Args:
+ username: Your LDR username
+ password: Your LDR password
+
+ Returns:
+ True if login successful, False otherwise
+ """
+ try:
+ # Step 1: Get login page to extract CSRF token
+ # We need to parse HTML because Flask-WTF embeds CSRF in forms
+ login_page = self.session.get(f"{self.base_url}/auth/login")
+
+ # Simple CSRF extraction without BeautifulSoup dependency
+ # Look for: <input type="hidden" name="csrf_token" value="..."/>
+ import re
+
+ csrf_match = re.search(
+ r'<input[^>]*name="csrf_token"[^>]*value="([^"]*)"',
+ login_page.text,
+ )
+
+ if not csrf_match:
+ logger.error("Could not find CSRF token in login page")
+ return False
+
+ login_csrf = csrf_match.group(1)
+
+ # Step 2: Login with form data (NOT JSON!)
+ # Flask-WTF expects form-encoded data for login
+ response = self.session.post(
+ f"{self.base_url}/auth/login",
+ data={
+ "username": username,
+ "password": password,
+ "csrf_token": login_csrf,
+ },
+ allow_redirects=True,
+ )
+
+ if response.status_code not in [200, 302]:
+ logger.error(
+ f"Login failed with status: {response.status_code}"
+ )
+ return False
+
+ # Step 3: Get CSRF token for API requests
+ # This uses our new endpoint that returns JSON
+ csrf_response = self.session.get(f"{self.base_url}/auth/csrf-token")
+ if csrf_response.status_code == 200:
+ self.csrf_token = csrf_response.json()["csrf_token"]
+ self.logged_in = True
+ self.username = username
+ logger.info(f"Successfully logged in as {username}")
+ return True
+ else:
+ logger.warning("Logged in but could not get API CSRF token")
+ # Still logged in, just no CSRF for API calls
+ self.logged_in = True
+ self.username = username
+ return True
+
+ except Exception:
+ logger.exception("Login error")
+ return False
+
+ def _api_headers(self) -> Dict[str, str]:
+ """Get headers with CSRF token for API requests."""
+ if self.csrf_token:
+ return {"X-CSRF-Token": self.csrf_token}
+ return {}
+
+ def quick_research(
+ self,
+ query: str,
+ model: Optional[str] = None,
+ search_engines: Optional[List[str]] = None,
+ iterations: int = 2,
+ wait_for_result: bool = True,
+ timeout: int = 300,
+ ) -> Dict[str, Any]:
+ """
+ Perform research on a topic.
+
+ Args:
+ query: Research question
+ model: LLM model to use (optional, uses user's default if not specified)
+ search_engines: List of search engines (default: ["searxng"])
+ iterations: Number of research iterations (default: 2)
+ wait_for_result: If True, wait for completion. If False, return immediately with research_id
+ timeout: Maximum time to wait in seconds (default: 300)
+
+ Returns:
+ If wait_for_result=True: Dict with summary, sources, findings
+ If wait_for_result=False: Dict with research_id for polling manually
+
+ Raises:
+ RuntimeError: If not logged in or request fails
+ """
+ if not self.logged_in:
+ raise RuntimeError("Not logged in. Call login() first.")
+
+ # Default search engines
+ if search_engines is None:
+ search_engines = ["searxng"]
+
+ # Start research
+ response = self.session.post(
+ f"{self.base_url}/research/api/start",
+ json={
+ "query": query,
+ "model": model,
+ "search_engines": search_engines,
+ "iterations": iterations,
+ "questions_per_iteration": 3,
+ },
+ headers=self._api_headers(),
+ )
+
+ # Handle response
+ if response.status_code != 200:
+ # Try to extract error message
+ try:
+ error_data = response.json()
+ if isinstance(error_data, list) and len(error_data) > 0:
+ error_msg = error_data[0].get("message", "Unknown error")
+ else:
+ error_msg = str(error_data)
+ except:
+ error_msg = response.text[:200]
+ raise RuntimeError(f"Failed to start research: {error_msg}")
+
+ result = response.json()
+ research_id = result.get("research_id")
+
+ if not research_id:
+ raise RuntimeError("No research ID returned")
+
+ if not wait_for_result:
+ return {"research_id": research_id}
+
+ # Poll for results
+ return self.wait_for_research(research_id, timeout)
+
+ def wait_for_research(
+ self, research_id: str, timeout: int = 300
+ ) -> Dict[str, Any]:
+ """
+ Wait for research to complete and return results.
+
+ Args:
+ research_id: ID of the research to wait for
+ timeout: Maximum time to wait in seconds
+
+ Returns:
+ Dict with research results
+
+ Raises:
+ RuntimeError: If research fails or times out
+ """
+ start_time = time.time()
+
+ while time.time() - start_time < timeout:
+ status_response = self.session.get(
+ f"{self.base_url}/research/api/research/{research_id}/status"
+ )
+
+ if status_response.status_code == 200:
+ status = status_response.json()
+
+ if status.get("status") == "completed":
+ # Get final results
+ results_response = self.session.get(
+ f"{self.base_url}/research/api/research/{research_id}/result"
+ )
+ if results_response.status_code == 200:
+ return results_response.json()
+ else:
+ raise RuntimeError("Failed to get results")
+
+ elif status.get("status") == "failed":
+ error_msg = status.get("error", "Unknown error")
+ raise RuntimeError(f"Research failed: {error_msg}")
+
+ time.sleep(5)
+
+ raise RuntimeError(f"Research timed out after {timeout} seconds")
+
+ def get_settings(self) -> Dict[str, Any]:
+ """Get current user settings."""
+ if not self.logged_in:
+ raise RuntimeError("Not logged in. Call login() first.")
+
+ response = self.session.get(f"{self.base_url}/settings/api")
+ if response.status_code == 200:
+ return response.json()
+ else:
+ raise RuntimeError(
+ f"Failed to get settings: {response.status_code}"
+ )
+
+ def update_setting(self, key: str, value: Any) -> bool:
+ """
+ Update a setting.
+
+ Args:
+ key: Setting key (e.g., "llm.model")
+ value: New value for the setting
+
+ Returns:
+ True if successful
+ """
+ if not self.logged_in:
+ raise RuntimeError("Not logged in. Call login() first.")
+
+ response = self.session.put(
+ f"{self.base_url}/settings/api/{key}",
+ json={"value": value},
+ headers=self._api_headers(),
+ )
+ return response.status_code == 200
+
+ def get_history(self) -> List[Dict[str, Any]]:
+ """Get research history."""
+ if not self.logged_in:
+ raise RuntimeError("Not logged in. Call login() first.")
+
+ response = self.session.get(f"{self.base_url}/history/api")
+ if response.status_code == 200:
+ data = response.json()
+ # Handle different response formats
+ if isinstance(data, dict):
+ return data.get("history", data.get("items", []))
+ elif isinstance(data, list):
+ return data
+ return []
+ else:
+ raise RuntimeError(f"Failed to get history: {response.status_code}")
+
+ def logout(self):
+ """Logout and clear session."""
+ if self.logged_in:
+ self.session.post(
+ f"{self.base_url}/auth/logout", headers=self._api_headers()
+ )
+ self.session.close()
+ self.csrf_token = None
+ self.logged_in = False
+ self.username = None
+
+ def __enter__(self):
+ """Support context manager for auto-cleanup."""
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ """Auto logout when used as context manager."""
+ self.logout()
+
+
+# Convenience functions for simple use cases
+
+
+def quick_query(
+ username: str,
+ password: str,
+ query: str,
+ base_url: str = "http://localhost:5000",
+) -> str:
+ """
+ One-liner for quick research queries.
+
+ Example:
+ summary = quick_query("user", "pass", "What is DNA?")
+ print(summary)
+
+ Args:
+ username: LDR username
+ password: LDR password
+ query: Research question
+ base_url: Server URL
+
+ Returns:
+ Research summary as string
+ """
+ with LDRClient(base_url) as client:
+ if not client.login(username, password):
+ raise RuntimeError("Login failed")
+
+ result = client.quick_research(query)
+ return result.get("summary", "No summary available")