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: Update API routes and research service for improved functionality

hashedviking69cd50b99a24
diff --git a/src/local_deep_research/web/routes/api_routes.py b/src/local_deep_research/web/routes/api_routes.py
new file mode 100644
index 0000000000..249b6e91fb
--- /dev/null
+++ b/src/local_deep_research/web/routes/api_routes.py
@@ -0,0 +1,211 @@
+import os
+import json
+from flask import Blueprint, jsonify, request, current_app, send_from_directory
+from ..services.research_service import start_research, get_research_status, cancel_research
+from ..services.resource_service import get_resources_for_research
+from ..models.research import Research
+from ..models.task import Task
+from ..models.database import get_db
+import requests
+import importlib
+from pathlib import Path
+import logging
+
+# Create blueprint
+api_bp = Blueprint('api', __name__)
+logger = logging.getLogger(__name__)
+
+# API Routes
+@api_bp.route('/start', methods=['POST'])
+def api_start_research():
+ """
+ Start a new research process
+ """
+ data = request.json
+ query = data.get('query', '')
+ mode = data.get('mode', 'quick')
+
+ if not query:
+ return jsonify({
+ 'status': 'error',
+ 'message': 'Query is required'
+ }), 400
+
+ try:
+ # Start research process and get ID
+ research_id = start_research(query, mode)
+
+ return jsonify({
+ 'status': 'success',
+ 'message': 'Research started successfully',
+ 'research_id': research_id
+ })
+ except Exception as e:
+ return jsonify({
+ 'status': 'error',
+ 'message': str(e)
+ }), 500
+
+@api_bp.route('/status/<int:research_id>', methods=['GET'])
+def api_research_status(research_id):
+ """
+ Get the status of a research process
+ """
+ try:
+ status = get_research_status(research_id)
+ return jsonify(status)
+ except Exception as e:
+ return jsonify({
+ 'status': 'error',
+ 'message': str(e)
+ }), 500
+
+@api_bp.route('/terminate/<int:research_id>', methods=['POST'])
+def api_terminate_research(research_id):
+ """
+ Terminate a research process
+ """
+ try:
+ result = cancel_research(research_id)
+ return jsonify({
+ 'status': 'success',
+ 'message': 'Research terminated',
+ 'result': result
+ })
+ except Exception as e:
+ return jsonify({
+ 'status': 'error',
+ 'message': str(e)
+ }), 500
+
+@api_bp.route('/resources/<int:research_id>', methods=['GET'])
+def api_get_resources(research_id):
+ """
+ Get resources for a specific research
+ """
+ try:
+ resources = get_resources_for_research(research_id)
+ return jsonify({
+ 'status': 'success',
+ 'resources': resources
+ })
+ except Exception as e:
+ return jsonify({
+ 'status': 'error',
+ 'message': str(e)
+ }), 500
+
+@api_bp.route('/check/ollama_status', methods=['GET'])
+def check_ollama_status():
+ """
+ Check if Ollama API is running
+ """
+ try:
+ # Get Ollama URL from config
+ llm_config = current_app.config.get('LLM_CONFIG', {})
+ provider = llm_config.get('provider', 'ollama')
+
+ if provider.lower() != 'ollama':
+ return jsonify({
+ 'running': True,
+ 'message': f'Using provider: {provider}, not Ollama'
+ })
+
+ # Get Ollama API URL
+ ollama_base_url = llm_config.get('ollama_base_url', 'http://localhost:11434')
+
+ # Check if Ollama is running
+ response = requests.get(f"{ollama_base_url}/api/tags", timeout=3)
+
+ if response.status_code == 200:
+ return jsonify({
+ 'running': True,
+ 'message': 'Ollama service is running'
+ })
+ else:
+ return jsonify({
+ 'running': False,
+ 'message': f'Ollama service returned status code: {response.status_code}'
+ })
+ except requests.exceptions.ConnectionError:
+ return jsonify({
+ 'running': False,
+ 'message': 'Ollama service is not running or not accessible'
+ })
+ except Exception as e:
+ logger.error(f"Error checking Ollama status: {str(e)}")
+ return jsonify({
+ 'running': False,
+ 'message': f'Error checking Ollama: {str(e)}'
+ })
+
+@api_bp.route('/check/ollama_model', methods=['GET'])
+def check_ollama_model():
+ """
+ Check if the configured Ollama model is available
+ """
+ try:
+ # Get Ollama configuration
+ llm_config = current_app.config.get('LLM_CONFIG', {})
+ provider = llm_config.get('provider', 'ollama')
+
+ if provider.lower() != 'ollama':
+ return jsonify({
+ 'available': True,
+ 'message': f'Using provider: {provider}, not Ollama'
+ })
+
+ # Get model name and Ollama API URL
+ model_name = llm_config.get('model', 'gemma3:12b')
+ ollama_base_url = llm_config.get('ollama_base_url', 'http://localhost:11434')
+
+ # Check if the model is available
+ response = requests.get(f"{ollama_base_url}/api/tags", timeout=5)
+
+ if response.status_code != 200:
+ return jsonify({
+ 'available': False,
+ 'model': model_name,
+ 'message': 'Could not access Ollama service'
+ })
+
+ models = response.json().get('models', [])
+ model_exists = any(m.get('name') == model_name for m in models)
+
+ if model_exists:
+ return jsonify({
+ 'available': True,
+ 'model': model_name,
+ 'message': f'Model {model_name} is available'
+ })
+ else:
+ return jsonify({
+ 'available': False,
+ 'model': model_name,
+ 'message': f'Model {model_name} is not available'
+ })
+ except Exception as e:
+ logger.error(f"Error checking Ollama model: {str(e)}")
+ return jsonify({
+ 'available': False,
+ 'model': llm_config.get('model', 'gemma3:12b'),
+ 'message': f'Error checking model: {str(e)}'
+ })
+
+# Helper route to get system configuration
+@api_bp.route('/config', methods=['GET'])
+def api_get_config():
+ """
+ Get public system configuration
+ """
+ # Only return public configuration
+ public_config = {
+ 'version': current_app.config.get('VERSION', '0.1.0'),
+ 'llm_provider': current_app.config.get('LLM_CONFIG', {}).get('provider', 'ollama'),
+ 'search_tool': current_app.config.get('SEARCH_CONFIG', {}).get('search_tool', 'auto'),
+ 'features': {
+ 'notifications': current_app.config.get('ENABLE_NOTIFICATIONS', False)
+ }
+ }
+
+ return jsonify(public_config)
\ No newline at end of file
diff --git a/src/local_deep_research/web/routes/history_routes.py b/src/local_deep_research/web/routes/history_routes.py
index aa55c9994d..f6189beb29 100644
--- a/src/local_deep_research/web/routes/history_routes.py
+++ b/src/local_deep_research/web/routes/history_routes.py
@@ -120,7 +120,7 @@ def get_history():
)
return response
-@history_bp.route("/research/<int:research_id>")
+@history_bp.route("/status/<int:research_id>")
def get_research_status(research_id):
conn = get_db_connection()
conn.row_factory = lambda cursor, row: {
@@ -158,7 +158,7 @@ def get_research_status(research_id):
return jsonify(result)
-@history_bp.route("/research/<int:research_id>/details")
+@history_bp.route("/details/<int:research_id>")
def get_research_details(research_id):
"""Get detailed progress log for a specific research"""
conn = get_db_connection()
@@ -230,17 +230,34 @@ def get_report(research_id):
try:
with open(result["report_path"], "r", encoding="utf-8") as f:
content = f.read()
- return jsonify(
- {
- "status": "success",
- "content": content,
- "metadata": json.loads(result.get("metadata", "{}")),
- }
- )
+
+ # Create an enhanced metadata dictionary with database fields
+ enhanced_metadata = {
+ "query": result.get("query", "Unknown query"),
+ "mode": result.get("mode", "quick"),
+ "created_at": result.get("created_at"),
+ "completed_at": result.get("completed_at"),
+ "duration": result.get("duration_seconds")
+ }
+
+ # Also include any stored metadata
+ stored_metadata = json.loads(result.get("metadata", "{}"))
+ if stored_metadata and isinstance(stored_metadata, dict):
+ enhanced_metadata.update(stored_metadata)
+
+ return jsonify({
+ "status": "success",
+ "content": content,
+ "query": result.get("query"),
+ "mode": result.get("mode"),
+ "created_at": result.get("created_at"),
+ "completed_at": result.get("completed_at"),
+ "metadata": enhanced_metadata
+ })
except Exception as e:
return jsonify({"status": "error", "message": str(e)}), 500
-@history_bp.route("/research/<int:research_id>/markdown")
+@history_bp.route("/markdown/<int:research_id>")
def get_markdown(research_id):
"""Get markdown export for a specific research"""
conn = get_db_connection()
@@ -267,7 +284,7 @@ def get_markdown(research_id):
except Exception as e:
return jsonify({"status": "error", "message": str(e)}), 500
-@history_bp.route("/research/<int:research_id>/logs")
+@history_bp.route("/logs/<int:research_id>")
def get_research_logs(research_id):
"""Get logs for a specific research ID"""
# First check if the research exists
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index b49408090e..1da7337c0f 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -186,7 +186,7 @@ def start_research():
return jsonify({"status": "success", "research_id": research_id})
-@research_bp.route("/api/research/<int:research_id>/terminate", methods=["POST"])
+@research_bp.route("/api/terminate/<int:research_id>", methods=["POST"])
def terminate_research(research_id):
"""Terminate an in-progress research process"""
@@ -289,7 +289,7 @@ def terminate_research(research_id):
return jsonify({"status": "success", "message": "Research termination requested"})
-@research_bp.route("/api/research/<int:research_id>/delete", methods=["DELETE"])
+@research_bp.route("/api/delete/<int:research_id>", methods=["DELETE"])
def delete_research(research_id):
"""Delete a research record"""
from ..models.database import get_db_connection
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index fd65dec8a3..29eafde49c 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -598,4 +598,52 @@ def handle_termination(research_id, active_research, termination_flags):
conn.close()
# Clean up resources
- cleanup_research_resources(research_id, active_research, termination_flags)
\ No newline at end of file
+ cleanup_research_resources(research_id, active_research, termination_flags)
+
+def cancel_research(research_id):
+ """
+ Cancel/terminate a research process
+
+ Args:
+ research_id: The ID of the research to cancel
+
+ Returns:
+ bool: True if the research was found and cancelled, False otherwise
+ """
+ # Import globals from research routes
+ from ..routes.research_routes import get_globals
+ globals_dict = get_globals()
+ active_research = globals_dict['active_research']
+ termination_flags = globals_dict['termination_flags']
+
+ # Set termination flag
+ termination_flags[research_id] = True
+
+ # Check if the research is active
+ if research_id in active_research:
+ # Call handle_termination to update database
+ handle_termination(research_id, active_research, termination_flags)
+ return True
+ else:
+ # Update database directly if not found in active_research
+ from ..models.database import get_db_connection
+ conn = get_db_connection()
+ cursor = conn.cursor()
+
+ # First check if the research exists
+ cursor.execute("SELECT status FROM research_history WHERE id = ?", (research_id,))
+ result = cursor.fetchone()
+
+ if not result:
+ conn.close()
+ return False
+
+ # If it exists but isn't in active_research, still update status
+ cursor.execute(
+ "UPDATE research_history SET status = ? WHERE id = ?",
+ ("suspended", research_id)
+ )
+ conn.commit()
+ conn.close()
+
+ return True
\ No newline at end of file