~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
refactor: remove curl examples and improve HTTP API examples organization
LearningCircuitbdcb934cbebb
diff --git a/.github/workflows/api-tests.yml b/.github/workflows/api-tests.ymlindex 02627a2ab2..819cd953fb 100644--- a/.github/workflows/api-tests.yml+++ b/.github/workflows/api-tests.yml@@ -6,6 +6,7 @@ on:- 'src/local_deep_research/api/**'- 'src/local_deep_research/web/routes/**'- 'tests/api_tests/**'+ - 'examples/api_usage/http/**'pull_request:types: [opened, synchronize, reopened]workflow_dispatch:@@ -51,9 +52,12 @@ jobs:run: |# Install in development mode to ensure all modules are availablepdm sync -d+ # Install additional dependencies for HTTP examples+ pdm add beautifulsoup4# Verify the package is installed correctlypdm run python -c "import local_deep_research; print('Package imported:', local_deep_research.__file__)"pdm run python -c "import local_deep_research.memory_cache; print('Memory cache module imported successfully')"+ pdm run python -c "import bs4; print('BeautifulSoup imported successfully')"- name: Start server for API unit testsrun: |@@ -193,6 +197,17 @@ jobs:# Run API testscd tests/api_tests && pdm run python test_rest_api.py+ # Run HTTP API Examples Tests+ echo "=== Testing HTTP API Examples ==="+ export LDR_USE_FALLBACK_LLM=true+ export PYTHONPATH=$PWD/src:$PYTHONPATH++ cd tests/api_tests && pdm run python test_http_examples.py || {+ echo "❌ HTTP API Examples tests failed"+ exit 1+ }+ echo "🎉 All HTTP API Examples tests passed!"+# Clean upkill $SERVER_PID || truediff --git a/examples/api_usage/http/README.md b/examples/api_usage/http/README.mdindex d4e7d11d38..651a4c4516 100644--- a/examples/api_usage/http/README.md+++ b/examples/api_usage/http/README.md@@ -26,7 +26,7 @@ python simple_working_example.py## 📁 Available Examples-### 🎯 `simple_working_example.py` - BEST FOR STARTING+### 🎯 `simple_working_example.py` - **RECOMMENDED START**- ✅ **Works completely out of the box**- ✅ **Automatic user creation** (no manual setup needed)- ✅ **Correct API endpoints** and authentication@@ -35,7 +35,11 @@ python simple_working_example.py**Perfect for:** First-time users, testing if API works, quick demos-### 📚 `simple_http_example.py` - LEARNING GUIDE+## 📚 Advanced Examples (`advanced/` folder)++More comprehensive examples for learning and advanced use cases:++### 📚 `advanced/simple_http_example.py` - **COMPREHENSIVE GUIDE**- ✅ **Automatic user creation**- 📊 **Multiple API examples** (research, settings, history)- 🔍 **Progress monitoring** with status updates@@ -43,7 +47,7 @@ python simple_working_example.py**Perfect for:** Learning different API endpoints, understanding the full API surface-### 🚀 `http_api_examples.py` - ADVANCED CLIENT+### 🚀 `advanced/http_api_examples.py` - **ADVANCED CLIENT**- 🔧 **Reusable client class** for integration- 📈 **Advanced features** (batch processing, polling)- 🎛️ **Comprehensive patterns** for production use@@ -51,12 +55,6 @@ python simple_working_example.py**Perfect for:** Building applications, production integration, advanced use cases-### 🛠️ `curl_examples.sh` - SHELL/CURL EXAMPLES-- 🔧 **Command-line examples** using curl-- 📝 **Shell script format** for automation-- 🔤 **Pure HTTP requests** (no Python needed)--**Perfect for:** Testing from command line, integration with other tools## ⚙️ Configuration@@ -175,31 +173,26 @@ ollama pull mistral- ✅ Proper CSRF token handling- ✅ Result URL generation-### simple_http_example.py+### advanced/simple_http_example.py- ✅ All of the above PLUS:- ✅ Settings management- ✅ Research history- ✅ Progress polling- ✅ Multiple research examples-### http_api_examples.py+### advanced/http_api_examples.py- ✅ All of the above PLUS:- ✅ Batch processing- ✅ Advanced polling strategies- ✅ Error handling patterns- ✅ Production-ready client class-### curl_examples.sh-- ✅ Pure HTTP requests-- ✅ Command-line integration-- ✅ No dependencies needed## 🎯 Recommended Usage Path1. **Start with `simple_working_example.py`** - Verify everything works-2. **Try `simple_http_example.py`** - Learn the API surface-3. **Use `http_api_examples.py`** - Build your application-4. **Reference `curl_examples.sh`** - For command-line integration+2. **Try `advanced/simple_http_example.py`** - Learn the API surface+3. **Use `advanced/http_api_examples.py`** - Build your application## 🔗 Related Documentationdiff --git a/examples/api_usage/http/advanced/README.md b/examples/api_usage/http/advanced/README.mdnew file mode 100644index 0000000000..cf8d7df3cf--- /dev/null+++ b/examples/api_usage/http/advanced/README.md@@ -0,0 +1,67 @@+# Advanced HTTP API Examples++This folder contains more comprehensive HTTP API examples for learning advanced features and production use cases.++## 📁 Available Examples++### 📚 `simple_http_example.py` - **COMPREHENSIVE GUIDE**+- ✅ **Automatic user creation**+- 📊 **Multiple API examples** (research, settings, history)+- 🔍 **Progress monitoring** with status updates+- ⏱️ **Runtime:** 3-15 minutes (more comprehensive testing)++**Perfect for:** Learning different API endpoints, understanding the full API surface++### 🚀 `http_api_examples.py` - **ADVANCED CLIENT**+- 🔧 **Reusable client class** for integration+- 📈 **Advanced features** (batch processing, polling)+- 🎛️ **Comprehensive patterns** for production use+- ⏱️ **Runtime:** 5-30 minutes (extensive testing)++**Perfect for:** Building applications, production integration, advanced use cases++## 🚀 Quick Start++### 1. Run the Comprehensive Example+```bash+cd advanced+python simple_http_example.py+```++### 2. Try the Advanced Client+```bash+cd advanced+python http_api_examples.py+```++## ⚠️ Important Notes++- **Longer Runtime**: These examples take longer than the basic example+- **More Features**: They demonstrate additional API endpoints and patterns+- **Learning Focused**: Designed to help you understand the full API surface+- **Production Ready**: Advanced examples include patterns for production use++## 📚 What These Examples Demonstrate++### simple_http_example.py+- ✅ All basic functionality from the main example+- ✅ Settings management (get/update configuration)+- ✅ Research history access+- ✅ Progress polling and monitoring+- ✅ Multiple research scenarios+- ✅ Error handling patterns++### http_api_examples.py+- ✅ All functionality from simple_http_example.py+- ✅ Reusable client class for application integration+- ✅ Batch processing capabilities+- ✅ Advanced polling strategies+- ✅ Production-ready error handling+- ✅ Comprehensive API coverage+- ✅ Settings management patterns++## 🔗 Related Documentation++- [Main HTTP Examples](../README.md)+- [Basic Working Example](../simple_working_example.py)+- [API Documentation](../../../README.md)diff --git a/examples/api_usage/http/http_api_examples.py b/examples/api_usage/http/advanced/http_api_examples.pysimilarity index 76%rename from examples/api_usage/http/http_api_examples.pyrename to examples/api_usage/http/advanced/http_api_examples.pyindex 44422b68ed..25b9d04c08 100755--- a/examples/api_usage/http/http_api_examples.py+++ b/examples/api_usage/http/advanced/http_api_examples.py@@ -7,18 +7,55 @@ Includes examples for research, settings management, and batch operations.Requirements:- LDR v1.0+ (with authentication features)-- User account created through web interface- LDR server running: python -m local_deep_research.web.app+- Beautiful Soup: pip install beautifulsoup4++This example works COMPLETELY out of the box - no manual setup required!"""import timefrom typing import Any, Dict, Listimport requests+from pathlib import Path+import sys+from bs4 import BeautifulSoup++# Add the src directory to Python path for programmatic user creation+sys.path.insert(0, str(Path(__file__).parent.parent.parent.parent / "src"))++from local_deep_research.database.encrypted_db import DatabaseManager+from local_deep_research.database.models import User+from local_deep_research.database.auth_db import get_auth_db_session# ConfigurationBASE_URL = "http://localhost:5000"-USERNAME = "your_username" # Change this!-PASSWORD = "your_password" # Change this!+++def create_test_user():+ """Create a test user programmatically - works out of the box!"""+ username = f"testuser_{int(time.time())}"+ password = "testpassword123"++ print(f"Creating test user: {username}")++ try:+ # Create user in auth database+ auth_db = get_auth_db_session()+ new_user = User(username=username)+ auth_db.add(new_user)+ auth_db.commit()+ auth_db.close()++ # Create encrypted database for user+ db_manager = DatabaseManager()+ db_manager.create_user_database(username, password)++ print(f"✅ User created successfully: {username}")+ return username, password++ except Exception as e:+ print(f"❌ Failed to create user: {e}")+ return None, Noneclass LDRClient:@@ -32,18 +69,44 @@ class LDRClient:def login(self, username: str, password: str) -> bool:"""Authenticate with the LDR server."""- response = self.session.post(- f"{self.base_url}/auth/login",- json={"username": username, "password": password},- )+ try:+ # Get login page and CSRF token+ login_page = self.session.get(f"{self.base_url}/auth/login")+ if login_page.status_code != 200:+ return False++ 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:+ return False++ # Submit login form+ login_response = self.session.post(+ f"{self.base_url}/auth/login",+ data={+ "username": username,+ "password": password,+ "csrf_token": login_csrf,+ },+ allow_redirects=False,+ )++ if login_response.status_code not in [200, 302]:+ return False- if response.status_code == 200:self.username = username- # Get CSRF token++ # Get API CSRF token for API callscsrf_response = self.session.get(f"{self.base_url}/auth/csrf-token")- self.csrf_token = csrf_response.json()["csrf_token"]+ if csrf_response.status_code == 200:+ self.csrf_token = csrf_response.json().get("csrf_token")+return True- return False++ except Exception:+ return Falsedef logout(self) -> None:"""Logout from the server."""@@ -345,27 +408,43 @@ def example_research_history(client: LDRClient) -> None:def main():"""Run all examples."""print("=== LDR HTTP API v1.0 Examples ===")+ print(+ "🎯 This example works completely out of the box - no manual setup required!"+ )- # Create client- client = LDRClient(BASE_URL)+ # First, check if server is running+ try:+ response = requests.get(f"{BASE_URL}/auth/check", timeout=5)+ if response.status_code in [+ 200,+ 401,+ ]: # 401 is expected when not authenticated+ print("✅ Server is running")+ else:+ print(f"❌ Server returned status code: {response.status_code}")+ print("Make sure the server is running:")+ print(" python -m local_deep_research.web.app")+ return+ except requests.exceptions.ConnectionError:+ print("❌ Cannot connect to LDR server!")+ print("Make sure the server is running:")+ print(" python -m local_deep_research.web.app")+ return- # Check if we need to update credentials- if USERNAME == "your_username":- print(- "\n⚠️ WARNING: Please update USERNAME and PASSWORD in this script!"- )- print("Steps:")- print("1. Start server: python -m local_deep_research.web.app")- print("2. Open: http://localhost:5000")- print("3. Register an account")- print("4. Update USERNAME and PASSWORD in this script")+ # Create test user automatically+ username, password = create_test_user()+ if not username:+ print("❌ Failed to create test user")return+ # Create client+ client = LDRClient(BASE_URL)+try:- # Login- print(f"\nLogging in as: {USERNAME}")- if not client.login(USERNAME, PASSWORD):- print("❌ Login failed! Please check your credentials.")+ # Login with the created user+ print(f"\nLogging in as: {username}")+ if not client.login(username, password):+ print("❌ Login failed!")returnprint("✅ Login successful")@@ -382,6 +461,13 @@ def main():example_batch_research(client)example_research_history(client)+ print("\n✅ All examples completed successfully!")+ print(f"🔑 Created user: {username}")+ print("📝 You can now use this user for manual testing:")+ print(f" Username: {username}")+ print(f" Password: {password}")+ print(f" Login URL: {BASE_URL}/auth/login")+except requests.exceptions.ConnectionError:print("\n❌ Cannot connect to LDR server!")print("Make sure the server is running:")diff --git a/examples/api_usage/http/simple_http_example.py b/examples/api_usage/http/advanced/simple_http_example.pysimilarity index 100%rename from examples/api_usage/http/simple_http_example.pyrename to examples/api_usage/http/advanced/simple_http_example.pydiff --git a/examples/api_usage/http/curl_examples.sh b/examples/api_usage/http/curl_examples.shdeleted file mode 100755index e314c868fe..0000000000--- a/examples/api_usage/http/curl_examples.sh+++ /dev/null@@ -1,42 +0,0 @@-#!/bin/bash-# HTTP API Examples using curl-# Make sure LDR server is running: python -m src.local_deep_research.web.app--API_URL="http://localhost:5000/api/v1"--echo "=== Health Check ==="-curl -s "$API_URL/health" | jq .--echo -e "\n=== Quick Summary ==="-curl -s -X POST "$API_URL/quick_summary" \- -H "Content-Type: application/json" \- -d '{- "query": "What is quantum computing?",- "search_tool": "wikipedia",- "iterations": 1- }' | jq '.summary' | head -c 500--echo -e "\n\n=== Get Available Search Engines ==="-curl -s "$API_URL/search_engines" | jq 'keys'--echo -e "\n=== Detailed Research ==="-curl -s -X POST "$API_URL/detailed_research" \- -H "Content-Type: application/json" \- -d '{- "query": "Future of electric vehicles",- "iterations": 2,- "questions_per_iteration": 3,- "search_strategy": "source_based"- }' | jq '{- research_id: .research_id,- summary_length: (.summary | length),- sources_count: (.sources | length),- metadata: .metadata- }'--echo -e "\n=== Generate Report (Long Running) ==="-echo "Note: This can take several minutes. Uncomment to run:"-echo "# curl -X POST \"$API_URL/generate_report\" \\"-echo "# -H \"Content-Type: application/json\" \\"-echo "# -d '{\"query\": \"AI impact on education\"}' \\"-echo "# -o \"ai_education_report.json\""diff --git a/tests/api_tests/test_http_examples.py b/tests/api_tests/test_http_examples.pynew file mode 100644index 0000000000..9320e63531--- /dev/null+++ b/tests/api_tests/test_http_examples.py@@ -0,0 +1,144 @@+#!/usr/bin/env python3+"""+CI Test for HTTP API Examples++This script tests the HTTP API examples to ensure they work correctly in CI.+It runs the examples with proper error handling and timeouts.++Requirements:+- LDR server running with fallback LLM+- Beautiful Soup installed+"""++import sys+import os+import subprocess+import time+import requests+from pathlib import Path++# Add src directory to Python path+sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))+++def check_server_health(base_url="http://localhost:5000", timeout=30):+ """Check if the LDR server is running and healthy."""+ print(f"Checking server health at {base_url}...")++ start_time = time.time()+ while time.time() - start_time < timeout:+ try:+ response = requests.get(f"{base_url}/auth/check", timeout=5)+ if response.status_code in [+ 200,+ 401,+ ]: # 401 is expected when not authenticated+ print("✅ Server is healthy")+ return True+ except requests.exceptions.ConnectionError:+ pass++ print(+ f"Waiting for server... ({int(time.time() - start_time)}/{timeout}s)"+ )+ time.sleep(1)++ print("❌ Server health check failed")+ return False+++def run_example(example_path, timeout=300):+ """Run a single HTTP example with timeout."""+ print(f"\n=== Testing {example_path.name} ===")++ try:+ # Run the example with timeout+ result = subprocess.run(+ [sys.executable, str(example_path)],+ capture_output=True,+ text=True,+ timeout=timeout,+ env={**os.environ, "LDR_USE_FALLBACK_LLM": "true"},+ )++ print(f"Exit code: {result.returncode}")+ if result.stdout:+ print(f"STDOUT:\n{result.stdout}")+ if result.stderr:+ print(f"STDERR:\n{result.stderr}")++ # Check for success indicators+ success_indicators = [+ "✅ User created successfully",+ "🎉 SUCCESS! API is working correctly",+ "✅ Login successful",+ "Research started successfully!",+ ]++ if result.returncode == 0 and any(+ indicator in result.stdout for indicator in success_indicators+ ):+ print(f"✅ {example_path.name} passed")+ return True+ else:+ print(f"❌ {example_path.name} failed")+ return False++ except subprocess.TimeoutExpired:+ print(f"❌ {example_path.name} timed out after {timeout} seconds")+ return False+ except Exception as e:+ print(f"❌ {example_path.name} failed with exception: {e}")+ return False+++def main():+ """Run all HTTP API examples tests."""+ print("=== HTTP API Examples CI Test ===")++ # Check server health first+ if not check_server_health():+ sys.exit(1)++ # Define examples to test+ examples_dir = (+ Path(__file__).parent.parent.parent / "examples" / "api_usage" / "http"+ )+ advanced_dir = examples_dir / "advanced"+ examples_to_test = [+ "simple_working_example.py",+ advanced_dir / "http_api_examples.py",+ # Note: We skip simple_http_example.py in CI as it takes too long+ ]++ results = {}++ for example_name in examples_to_test:+ example_path = examples_dir / example_name+ if not example_path.exists():+ print(f"⚠️ Example {example_name} not found, skipping")+ continue++ results[example_name] = run_example(example_path)++ # Summary+ print("\n=== Test Summary ===")+ passed = sum(results.values())+ total = len(results)++ for example, success in results.items():+ status = "✅ PASS" if success else "❌ FAIL"+ print(f"{status} {example}")++ print(f"\nTotal: {passed}/{total} examples passed")++ if passed == total:+ print("🎉 All HTTP API examples tests passed!")+ return 0+ else:+ print("❌ Some HTTP API examples tests failed!")+ return 1+++if __name__ == "__main__":+ sys.exit(main())