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: Correct API endpoint and authentication in examples and documentation

LearningCircuitccd809dbe386
diff --git a/examples/api_usage/README.md b/examples/api_usage/README.md
index 0e1774b7da..57e2fa9704 100644
--- a/examples/api_usage/README.md
+++ b/examples/api_usage/README.md
@@ -17,6 +17,7 @@ Since LDR v2.0, all API access requires authentication due to per-user encrypted
- `retriever_usage_example.py` - Using LangChain retrievers with LDR
- **`http/`** - HTTP REST API usage (requires running server)
+ - `working_api_example.py` - ✅ **WORKING EXAMPLE** - Tested and ready to use
- `simple_http_example.py` - Quick start example (needs updating for auth)
- `http_api_examples.py` - Comprehensive examples including batch processing
@@ -56,10 +57,21 @@ import requests
# Create session for cookie persistence
session = requests.Session()
-# Login
+# Login - get CSRF token first
+login_page = session.get("http://localhost:5000/auth/login")
+from bs4 import BeautifulSoup
+soup = BeautifulSoup(login_page.text, 'html.parser')
+csrf_input = soup.find('input', {'name': 'csrf_token'})
+login_csrf = csrf_input.get('value')
+
+# Login with form data
session.post(
"http://localhost:5000/auth/login",
- json={"username": "your_username", "password": "your_password"}
+ data={
+ "username": "your_username",
+ "password": "your_password",
+ "csrf_token": login_csrf
+ }
)
# Get CSRF token
@@ -67,9 +79,9 @@ csrf_token = session.get("http://localhost:5000/auth/csrf-token").json()["csrf_t
# Make API request
response = session.post(
- "http://localhost:5000/research/api/start",
+ "http://localhost:5000/api/start_research",
json={"query": "What is quantum computing?"},
- headers={"X-CSRF-Token": csrf_token}
+ headers={"X-CSRF-Token": csrf_token, "Content-Type": "application/json"}
)
print(response.json())
```
diff --git a/examples/api_usage/http/simple_http_example.py b/examples/api_usage/http/simple_http_example.py
index 2ecc6848c1..cf4a4dca53 100755
--- a/examples/api_usage/http/simple_http_example.py
+++ b/examples/api_usage/http/simple_http_example.py
@@ -1,14 +1,15 @@
#!/usr/bin/env python3
"""
-Simple HTTP API Example for Local Deep Research v1.0+
+Simple HTTP API Example for Local Deep Research v2.0+
This example shows how to use the LDR API with authentication.
-Requires LDR v1.0+ with authentication features.
+Requires LDR v2.0+ with authentication features.
"""
import requests
import time
import sys
+from bs4 import BeautifulSoup
# Configuration
API_URL = "http://localhost:5000"
@@ -25,12 +26,29 @@ def main():
# Step 1: Login
print("\n1. Authenticating...")
+
+ # Get login page and CSRF token
+ login_page = session.get(f"{API_URL}/auth/login")
+ soup = BeautifulSoup(login_page.text, "html.parser")
+ csrf_input = soup.find("input", {"name": "csrf_token"})
+ login_csrf = csrf_input.get("value")
+
+ if not login_csrf:
+ print("❌ Could not get CSRF token from login page")
+ sys.exit(1)
+
+ # Login with form data (not JSON)
login_response = session.post(
f"{API_URL}/auth/login",
- json={"username": USERNAME, "password": PASSWORD},
+ data={
+ "username": USERNAME,
+ "password": PASSWORD,
+ "csrf_token": login_csrf,
+ },
+ allow_redirects=False,
)
- if login_response.status_code != 200:
+ if login_response.status_code not in [200, 302]:
print(f"❌ Login failed: {login_response.text}")
print("\nPlease ensure:")
print("- The server is running: python -m local_deep_research.web.app")
@@ -57,9 +75,9 @@ def main():
"questions_per_iteration": 2,
}
- # Start research
+ # Start research - CORRECT ENDPOINT
start_response = session.post(
- f"{API_URL}/research/api/start", json=research_request, headers=headers
+ f"{API_URL}/api/start_research", json=research_request, headers=headers
)
if start_response.status_code != 200:
diff --git a/examples/api_usage/http/working_api_example.py b/examples/api_usage/http/working_api_example.py
new file mode 100644
index 0000000000..363f64502c
--- /dev/null
+++ b/examples/api_usage/http/working_api_example.py
@@ -0,0 +1,305 @@
+#!/usr/bin/env python3
+"""
+Working HTTP API Example for Local Deep Research v2.0+
+
+This is a tested, working example that demonstrates proper API usage.
+It handles authentication correctly and uses the right endpoints.
+
+Requirements:
+- LDR v2.0+ (with authentication features)
+- User account created through web interface at http://localhost:5000/auth/register
+- LDR server running: python -m local_deep_research.web.app
+- Beautiful Soup: pip install beautifulsoup4
+"""
+
+import time
+import sys
+from typing import Optional, Dict, Any
+import requests
+from bs4 import BeautifulSoup
+
+
+class LDRClient:
+ """Working client for interacting with LDR API v2.0+ with proper authentication"""
+
+ def __init__(self, base_url: str = "http://localhost:5000"):
+ self.base_url = base_url
+ self.session = requests.Session()
+ self.csrf_token = None
+ self.username = None
+
+ def login(self, username: str, password: str) -> bool:
+ """
+ Authenticate with the LDR server.
+ Returns True if successful, False otherwise.
+ """
+ try:
+ # Step 1: Get login page and extract CSRF token
+ print("📄 Getting login page...")
+ login_page = self.session.get(f"{self.base_url}/auth/login")
+
+ if login_page.status_code != 200:
+ print(f"❌ Failed to get login page: {login_page.status_code}")
+ return False
+
+ # Extract CSRF token from the login form
+ soup = BeautifulSoup(login_page.text, "html.parser")
+ csrf_input = soup.find("input", {"name": "csrf_token"})
+ login_csrf = csrf_input.get("value") if csrf_input else None
+
+ if not login_csrf:
+ print("❌ No CSRF token found in login page")
+ return False
+
+ # Step 2: Submit login form with CSRF token
+ print(f"🔐 Logging in as {username}...")
+ login_response = self.session.post(
+ f"{self.base_url}/auth/login",
+ data={
+ "username": username,
+ "password": password,
+ "csrf_token": login_csrf,
+ },
+ allow_redirects=False, # Don't follow redirects to see response clearly
+ )
+
+ if login_response.status_code not in [200, 302]:
+ print(f"❌ Login failed: {login_response.status_code}")
+ print(f"Response: {login_response.text[:200]}")
+ return False
+
+ self.username = username
+ print("✅ Login successful")
+
+ # Step 3: Get API CSRF token
+ print("🔑 Getting API CSRF token...")
+ csrf_response = self.session.get(f"{self.base_url}/auth/csrf-token")
+
+ if csrf_response.status_code != 200:
+ print(
+ f"❌ Failed to get CSRF token: {csrf_response.status_code}"
+ )
+ return False
+
+ csrf_data = csrf_response.json()
+ self.csrf_token = csrf_data.get("csrf_token")
+
+ if not self.csrf_token:
+ print("❌ No CSRF token in API response")
+ return False
+
+ print("✅ Authentication complete")
+ return True
+
+ except Exception as e:
+ print(f"❌ Login error: {e}")
+ return False
+
+ def start_research(self, query: str, **kwargs) -> Optional[Dict[str, Any]]:
+ """
+ Start a new research query.
+
+ Args:
+ query: The research question
+ **kwargs: Additional parameters (model, search_engines, etc.)
+
+ Returns:
+ Dict with research_id and status, or None if failed
+ """
+ if not self.csrf_token:
+ print("❌ Not authenticated - call login() first")
+ return None
+
+ # Default parameters
+ research_request = {
+ "query": query,
+ "model": kwargs.get("model", "gpt-4o-mini"),
+ "search_engines": kwargs.get("search_engines", ["searxng"]),
+ "iterations": kwargs.get("iterations", 3),
+ "questions_per_iteration": kwargs.get("questions_per_iteration", 3),
+ }
+
+ # Add any additional parameters
+ for key, value in kwargs.items():
+ if key not in research_request:
+ research_request[key] = value
+
+ headers = {
+ "X-CSRF-Token": self.csrf_token,
+ "Content-Type": "application/json",
+ }
+
+ try:
+ print(f"🔍 Starting research: {query[:50]}...")
+
+ # Use the CORRECT endpoint!
+ response = self.session.post(
+ f"{self.base_url}/api/start_research", # ✅ CORRECT ENDPOINT
+ json=research_request,
+ headers=headers,
+ )
+
+ if response.status_code != 200:
+ print(f"❌ Failed to start research: {response.status_code}")
+ print(f"Response: {response.text[:300]}")
+ return None
+
+ data = response.json()
+ status = data.get("status")
+
+ if status == "success":
+ print("✅ Research started successfully!")
+ return data
+ elif status == "queued":
+ print(
+ f"⏳ Research queued (position: {data.get('queue_position', 'unknown')})"
+ )
+ return data
+ else:
+ print(f"❌ Research returned status: {status}")
+ return None
+
+ except Exception as e:
+ print(f"❌ Error starting research: {e}")
+ return None
+
+ def get_research_status(self, research_id: str) -> Optional[Dict[str, Any]]:
+ """Get the status of a research query."""
+ try:
+ response = self.session.get(
+ f"{self.base_url}/api/research/{research_id}/status"
+ )
+
+ if response.status_code != 200:
+ print(f"❌ Failed to get status: {response.status_code}")
+ return None
+
+ return response.json()
+
+ except Exception as e:
+ print(f"❌ Error getting status: {e}")
+ return None
+
+ def wait_for_completion(
+ self, research_id: str, timeout: int = 300
+ ) -> Optional[Dict[str, Any]]:
+ """
+ Wait for research to complete.
+
+ Args:
+ research_id: The research ID to wait for
+ timeout: Maximum time to wait in seconds
+
+ Returns:
+ Final status data or None if timed out
+ """
+ start_time = time.time()
+
+ while time.time() - start_time < timeout:
+ status = self.get_research_status(research_id)
+ if not status:
+ time.sleep(2)
+ continue
+
+ status_code = status.get("status")
+ progress = status.get("progress", 0)
+
+ if status_code == "completed":
+ print("✅ Research completed!")
+ return status
+ elif status_code == "failed":
+ print("❌ Research failed")
+ return status
+ elif status_code in ["in_progress", "queued"]:
+ print(f"⏳ Status: {status_code} (Progress: {progress}%)")
+ time.sleep(3)
+ else:
+ print(f"❓ Unknown status: {status_code}")
+ time.sleep(3)
+
+ print(f"⏰ Timeout after {timeout} seconds")
+ return None
+
+ def get_research_report(self, research_id: str) -> Optional[Dict[str, Any]]:
+ """Get the final research report."""
+ try:
+ response = self.session.get(
+ f"{self.base_url}/api/research/{research_id}/report"
+ )
+
+ if response.status_code != 200:
+ print(f"❌ Failed to get report: {response.status_code}")
+ return None
+
+ return response.json()
+
+ except Exception as e:
+ print(f"❌ Error getting report: {e}")
+ return None
+
+
+def main():
+ """Demonstration of the LDR API usage."""
+ print("=== Local Deep Research API Example ===\n")
+
+ # Configuration - UPDATE THESE
+ USERNAME = "your_username" # ⚠️ Change this!
+ PASSWORD = "your_password" # ⚠️ Change this!
+
+ if USERNAME == "your_username" or PASSWORD == "your_password":
+ print("⚠️ Please update USERNAME and PASSWORD in this script!")
+ print(" 1. Start the server: python -m local_deep_research.web.app")
+ print(" 2. Visit http://localhost:5000/auth/register")
+ print(" 3. Create an account and update the credentials below\n")
+
+ # Create client and login
+ client = LDRClient()
+
+ if not client.login(USERNAME, PASSWORD):
+ print(
+ "\n❌ Login failed. Please check your credentials and that the server is running."
+ )
+ print("💡 Create an account at: http://localhost:5000/auth/register")
+ sys.exit(1)
+
+ # Example 1: Quick research
+ print("\n=== Example 1: Quick Research ===")
+ result = client.start_research(
+ "What is quantum computing?",
+ search_engines=["wikipedia"], # Fast for demo
+ iterations=1,
+ questions_per_iteration=2,
+ )
+
+ if result:
+ research_id = result.get("research_id")
+ print(f"📋 Research ID: {research_id}")
+
+ # Wait for completion
+ final_status = client.wait_for_completion(research_id, timeout=120)
+
+ if final_status and final_status.get("status") == "completed":
+ # Get the report
+ report = client.get_research_report(research_id)
+ if report:
+ content = report.get("content", "")
+ print(f"\n📝 Summary: {content[:300]}...")
+
+ # Example 2: Another query
+ print("\n=== Example 2: Different Query ===")
+ result2 = client.start_research(
+ "What are the benefits of renewable energy?",
+ model="gpt-4o-mini",
+ search_engines=["searxng"],
+ )
+
+ if result2:
+ print(f"📋 Research ID: {result2.get('research_id')}")
+ print("📝 Check the web interface at http://localhost:5000 for results")
+
+ print("\n✅ Examples completed!")
+ print("🌐 View all results at: http://localhost:5000/history")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/api_tests/test_research_api_debug.py b/tests/api_tests/test_research_api_debug.py
new file mode 100644
index 0000000000..7c7a0b874e
--- /dev/null
+++ b/tests/api_tests/test_research_api_debug.py
@@ -0,0 +1,380 @@
+#!/usr/bin/env python3
+"""
+Debug test for Research API endpoints.
+
+This test specifically helps debug issues with starting research via the API.
+It can be run standalone to diagnose authentication, CSRF, and endpoint issues.
+"""
+
+import json
+import requests
+from bs4 import BeautifulSoup
+import sys
+import time
+
+
+class ResearchAPIDebugTest:
+ """Debug test suite for research API endpoints."""
+
+ def __init__(self, base_url="http://localhost:5000"):
+ self.base_url = base_url
+ self.session = requests.Session()
+ # Create unique username to avoid conflicts
+ timestamp = int(time.time() * 1000)
+ self.username = f"testuser_{timestamp}"
+ self.password = "testpassword123" # At least 8 characters
+
+ def run_all_tests(self):
+ """Run all debug tests."""
+ print("=== Research API Debug Test ===")
+ print(f"Base URL: {self.base_url}")
+ print()
+
+ # Test server connectivity
+ if not self.test_server_connectivity():
+ print("❌ Server is not running. Please start the server first.")
+ return False
+
+ # Test user registration if login fails
+ if not self.test_authentication_flow():
+ print("🔄 Authentication failed, trying to register user...")
+ if not self.test_user_registration():
+ print(
+ "❌ User registration failed. Cannot proceed with API tests."
+ )
+ return False
+
+ # Try authentication again after registration
+ if not self.test_authentication_flow():
+ print("❌ Authentication still failed after registration.")
+ return False
+
+ # Test CSRF token handling
+ if not self.test_csrf_tokens():
+ print("❌ CSRF token handling failed.")
+ return False
+
+ # Test research API endpoints
+ self.test_research_endpoints()
+
+ return True
+
+ def test_server_connectivity(self):
+ """Test if server is running."""
+ print("1. Testing server connectivity...")
+ try:
+ response = self.session.get(f"{self.base_url}/")
+ print(f" Status: {response.status_code}")
+ if response.status_code == 200:
+ print(" ✅ Server is running")
+ return True
+ else:
+ print(f" ❌ Server returned status {response.status_code}")
+ return False
+ except requests.exceptions.ConnectionError:
+ print(" ❌ Cannot connect to server")
+ return False
+ except Exception as e:
+ print(f" ❌ Error: {e}")
+ return False
+
+ def test_user_registration(self):
+ """Test user registration."""
+ print("\n2b. Testing user registration...")
+
+ try:
+ # Get registration page
+ register_page = self.session.get(f"{self.base_url}/auth/register")
+ print(f" Registration page status: {register_page.status_code}")
+
+ if register_page.status_code != 200:
+ print(
+ f" ❌ Failed to get registration page: {register_page.text[:200]}"
+ )
+ return False
+
+ # Extract CSRF token from registration page
+ soup = BeautifulSoup(register_page.text, "html.parser")
+ csrf_input = soup.find("input", {"name": "csrf_token"})
+ register_csrf = csrf_input.get("value") if csrf_input else None
+
+ if not register_csrf:
+ print(" ❌ No CSRF token found in registration page")
+ return False
+
+ print(f" Registration CSRF token: {register_csrf[:20]}...")
+
+ # Attempt registration
+ register_response = self.session.post(
+ f"{self.base_url}/auth/register",
+ data={
+ "username": self.username,
+ "password": self.password,
+ "confirm_password": self.password, # Add confirmation field
+ "acknowledge": "true", # Must acknowledge password recovery warning
+ "csrf_token": register_csrf,
+ },
+ allow_redirects=False,
+ )
+
+ print(
+ f" Registration response status: {register_response.status_code}"
+ )
+
+ if register_response.status_code in [200, 302]:
+ print(" ✅ Registration successful")
+ return True
+ else:
+ print(
+ f" ❌ Registration failed: {register_response.text[:200]}"
+ )
+ return False
+
+ except Exception as e:
+ print(f" ❌ Registration error: {e}")
+ return False
+
+ def test_authentication_flow(self):
+ """Test login and authentication."""
+ print("\n2. Testing authentication flow...")
+
+ # Get login page (fresh page to ensure fresh CSRF token)
+ try:
+ login_page = self.session.get(f"{self.base_url}/auth/login")
+ print(f" Login page status: {login_page.status_code}")
+
+ if login_page.status_code != 200:
+ print(
+ f" ❌ Failed to get login page: {login_page.text[:200]}"
+ )
+ return False
+
+ # Extract CSRF token
+ soup = BeautifulSoup(login_page.text, "html.parser")
+ csrf_input = soup.find("input", {"name": "csrf_token"})
+ login_csrf = csrf_input.get("value") if csrf_input else None
+
+ if not login_csrf:
+ print(" ❌ No CSRF token found in login page")
+ return False
+
+ print(f" Login CSRF token: {login_csrf[:20]}...")
+
+ # Attempt login
+ login_response = self.session.post(
+ f"{self.base_url}/auth/login",
+ data={
+ "username": self.username,
+ "password": self.password,
+ "csrf_token": login_csrf,
+ },
+ allow_redirects=False, # Don't follow redirects to see response clearly
+ )
+
+ print(f" Login response status: {login_response.status_code}")
+
+ if login_response.status_code in [200, 302]:
+ print(" ✅ Login successful")
+ return True
+ else:
+ print(f" ❌ Login failed: {login_response.text[:200]}")
+ return False
+
+ except Exception as e:
+ print(f" ❌ Authentication error: {e}")
+ return False
+
+ def test_csrf_tokens(self):
+ """Test CSRF token generation and usage."""
+ print("\n3. Testing CSRF tokens...")
+
+ try:
+ # Get API CSRF token
+ csrf_response = self.session.get(f"{self.base_url}/auth/csrf-token")
+ print(f" CSRF token endpoint status: {csrf_response.status_code}")
+
+ if csrf_response.status_code != 200:
+ print(
+ f" ❌ Failed to get CSRF token: {csrf_response.text[:200]}"
+ )
+ return False
+
+ csrf_data = csrf_response.json()
+ csrf_token = csrf_data.get("csrf_token")
+
+ if not csrf_token:
+ print(" ❌ No CSRF token in response")
+ return False
+
+ print(f" API CSRF token: {csrf_token[:20]}...")
+ self.csrf_token = csrf_token
+ return True
+
+ except Exception as e:
+ print(f" ❌ CSRF token error: {e}")
+ return False
+
+ def test_research_endpoints(self):
+ """Test research API endpoints."""
+ print("\n4. Testing research API endpoints...")
+
+ if not hasattr(self, "csrf_token"):
+ print(" ❌ No CSRF token available")
+ return
+
+ # Prepare research request
+ research_request = {
+ "query": "What is machine learning?",
+ "model": "gpt-4o-mini", # Use a valid model name
+ "search_engines": ["searxng"],
+ }
+
+ headers = {
+ "X-CSRF-Token": self.csrf_token,
+ "Content-Type": "application/json",
+ }
+
+ # Test 1: Correct endpoint /api/start_research
+ print("\n 4a. Testing /api/start_research...")
+ self._test_endpoint("/api/start_research", research_request, headers)
+
+ # Test 2: Old endpoint /research/api/start
+ print("\n 4b. Testing /research/api/start...")
+ self._test_endpoint("/research/api/start", research_request, headers)
+
+ # Test 3: Alternative endpoint /research/api/start_research
+ print("\n 4c. Testing /research/api/start_research...")
+ self._test_endpoint(
+ "/research/api/start_research", research_request, headers
+ )
+
+ # Test 4: Check if user is properly authenticated for API
+ print("\n 4d. Testing auth status...")
+ self._test_auth_status()
+
+ def _test_endpoint(self, endpoint, research_request, headers):
+ """Test a specific research endpoint."""
+ try:
+ url = f"{self.base_url}{endpoint}"
+ response = self.session.post(
+ url, json=research_request, headers=headers
+ )
+
+ print(f" Endpoint: {endpoint}")
+ print(f" Status: {response.status_code}")
+ print(f" Response: {response.text[:300]}")
+
+ if response.status_code == 200:
+ try:
+ data = response.json()
+ if data.get("status") == "success":
+ research_id = data.get("research_id")
+ print(" ✅ Research started successfully!")
+ print(f" Research ID: {research_id}")
+
+ # Test research status
+ self._test_research_status(research_id)
+ elif data.get("status") == "queued":
+ print(" ✅ Research queued successfully!")
+ print(
+ f" Queue position: {data.get('queue_position')}"
+ )
+ else:
+ print(
+ f" ⚠️ Research returned: {data.get('status', 'unknown')}"
+ )
+ except json.JSONDecodeError:
+ print(" ⚠️ Response is not valid JSON")
+ elif response.status_code == 401:
+ print(" ❌ Authentication failed for this endpoint")
+ elif response.status_code == 403:
+ print(" ❌ Forbidden - CSRF token issue")
+ elif response.status_code == 404:
+ print(" ❌ Endpoint not found")
+ elif response.status_code == 500:
+ print(" ❌ Server error - check logs")
+ else:
+ print(" ⚠️ Unexpected status code")
+
+ except Exception as e:
+ print(f" ❌ Error testing endpoint: {e}")
+
+ def _test_research_status(self, research_id):
+ """Test getting research status."""
+ if not research_id:
+ return
+
+ try:
+ # Wait a moment for research to initialize
+ time.sleep(1)
+
+ status_url = f"{self.base_url}/api/research/{research_id}/status"
+ response = self.session.get(status_url)
+
+ print(f" Status check: {response.status_code}")
+ if response.status_code == 200:
+ data = response.json()
+ print(
+ f" Research status: {data.get('status', 'unknown')}"
+ )
+ print(f" Progress: {data.get('progress', 0)}%")
+ else:
+ print(f" Status check failed: {response.text[:100]}")
+
+ except Exception as e:
+ print(f" Error checking status: {e}")
+
+ def _test_auth_status(self):
+ """Test authentication status."""
+ try:
+ response = self.session.get(f"{self.base_url}/auth/check")
+ print(f" Auth check status: {response.status_code}")
+
+ if response.status_code == 200:
+ data = response.json()
+ print(
+ f" Authenticated: {data.get('authenticated', False)}"
+ )
+ print(f" Username: {data.get('username', 'None')}")
+ print(f" Session cookies: {len(self.session.cookies)}")
+ else:
+ print(f" Auth check failed: {response.text[:100]}")
+
+ except Exception as e:
+ print(f" Error checking auth: {e}")
+
+
+def main():
+ """Run the debug test."""
+ import argparse
+
+ parser = argparse.ArgumentParser(description="Debug Research API endpoints")
+ parser.add_argument(
+ "--url", default="http://localhost:5000", help="Base URL for the server"
+ )
+ parser.add_argument(
+ "--username", default="admin", help="Username for authentication"
+ )
+ parser.add_argument(
+ "--password", default="admin", help="Password for authentication"
+ )
+
+ args = parser.parse_args()
+
+ # Create and run test
+ test = ResearchAPIDebugTest(args.url)
+ test.username = args.username
+ test.password = args.password
+
+ success = test.run_all_tests()
+
+ if success:
+ print("\n✅ Debug tests completed successfully")
+ sys.exit(0)
+ else:
+ print("\n❌ Debug tests failed")
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()