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.

refactor: extract hardcoded values into named constants (#2032)

LearningCircuit77c37b66097d
diff --git a/src/local_deep_research/api/client.py b/src/local_deep_research/api/client.py
index e3bbea1715..4bbcc68abf 100644
--- a/src/local_deep_research/api/client.py
+++ b/src/local_deep_research/api/client.py
@@ -57,6 +57,8 @@ Example usage:
import time
from typing import Any
+
+from ..constants import ResearchStatus
from loguru import logger
from local_deep_research.benchmarks.comparison.results import Benchmark_results
from local_deep_research.security import SafeSession
@@ -281,7 +283,7 @@ class LDRClient:
if status_response.status_code == 200:
status = status_response.json()
- if status.get("status") == "completed":
+ if status.get("status") == ResearchStatus.COMPLETED:
# Get final results
results_response = self.session.get(
f"{self.base_url}/research/api/research/{research_id}/result"
@@ -291,7 +293,7 @@ class LDRClient:
else:
raise RuntimeError("Failed to get results")
- elif status.get("status") == "failed":
+ elif status.get("status") == ResearchStatus.FAILED:
error_msg = status.get("error", "Unknown error")
raise RuntimeError(f"Research failed: {error_msg}")
diff --git a/src/local_deep_research/constants.py b/src/local_deep_research/constants.py
index 3cbb129714..4819c5cef4 100644
--- a/src/local_deep_research/constants.py
+++ b/src/local_deep_research/constants.py
@@ -1,5 +1,7 @@
"""Project-wide constants for Local Deep Research."""
+from enum import StrEnum
+
from .__version__ import __version__
# Honest, identifying User-Agent for APIs that prefer/require identification
@@ -16,3 +18,30 @@ BROWSER_USER_AGENT = (
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/120.0.0.0 Safari/537.36"
)
+
+
+# --- Research status values ---
+class ResearchStatus(StrEnum):
+ """Status values for research records.
+
+ Uses StrEnum so values compare equal to plain strings,
+ e.g. ``ResearchStatus.COMPLETED == "completed"`` is True.
+ """
+
+ COMPLETED = "completed"
+ SUSPENDED = "suspended"
+ FAILED = "failed"
+ IN_PROGRESS = "in_progress"
+ PENDING = "pending"
+ ERROR = "error"
+ QUEUED = "queued"
+ CANCELLED = "cancelled"
+
+
+# --- Rate limiting defaults ---
+RATE_LIMIT_WINDOW_SECONDS = 60
+DEFAULT_RATE_LIMIT = 60 # requests per window
+
+# --- Snippet / truncation lengths ---
+SNIPPET_LENGTH_SHORT = 250
+SNIPPET_LENGTH_LONG = 500
diff --git a/src/local_deep_research/database/models/research.py b/src/local_deep_research/database/models/research.py
index d33de29eba..11bf54a348 100644
--- a/src/local_deep_research/database/models/research.py
+++ b/src/local_deep_research/database/models/research.py
@@ -18,6 +18,7 @@ from sqlalchemy import (
from sqlalchemy.orm import relationship
from sqlalchemy_utc import UtcDateTime, utcnow
+from ...constants import ResearchStatus
from .base import Base
@@ -175,17 +176,6 @@ class ResearchMode(enum.Enum):
DETAILED = "detailed"
-class ResearchStatus(enum.Enum):
- """Status of research operations."""
-
- PENDING = "pending"
- IN_PROGRESS = "in_progress"
- COMPLETED = "completed"
- FAILED = "failed"
- CANCELLED = "cancelled"
- SUSPENDED = "suspended"
-
-
class ResearchResource(Base):
"""Resources associated with research projects."""
diff --git a/src/local_deep_research/followup_research/routes.py b/src/local_deep_research/followup_research/routes.py
index 3966b0fbb2..233b972629 100644
--- a/src/local_deep_research/followup_research/routes.py
+++ b/src/local_deep_research/followup_research/routes.py
@@ -5,6 +5,7 @@ Flask routes for follow-up research functionality.
from flask import Blueprint, request, jsonify, session, g
from loguru import logger
+from ..constants import ResearchStatus
from .service import FollowUpResearchService
from .models import FollowUpRequest
from ..web.auth.decorators import login_required
@@ -214,7 +215,7 @@ def start_followup():
id=research_id,
query=research_params["query"],
mode="quick", # Use 'quick' not 'quick_summary'
- status="in_progress",
+ status=ResearchStatus.IN_PROGRESS,
created_at=created_at,
progress_log=[{"time": created_at, "progress": 0}],
research_meta=research_meta,
diff --git a/src/local_deep_research/news/api.py b/src/local_deep_research/news/api.py
index e29ded4204..1d90128503 100644
--- a/src/local_deep_research/news/api.py
+++ b/src/local_deep_research/news/api.py
@@ -9,6 +9,7 @@ from loguru import logger
import re
import json
+from ..constants import ResearchStatus
from .recommender.topic_based import TopicBasedRecommender
from .exceptions import (
InvalidLimitException,
@@ -132,7 +133,7 @@ def get_news_feed(
with get_user_db_session(user_id) as db_session:
# Build query using ORM
query = db_session.query(ResearchHistory).filter(
- ResearchHistory.status == "completed"
+ ResearchHistory.status == ResearchStatus.COMPLETED
)
# Filter by subscription if provided
@@ -304,7 +305,10 @@ def get_news_feed(
continue
# Skip items that are still in progress or suspended
- if row["status"] in ["in_progress", "suspended"]:
+ if row["status"] in (
+ ResearchStatus.IN_PROGRESS,
+ ResearchStatus.SUSPENDED,
+ ):
logger.debug(
f"Skipping incomplete item: {row['id']} (status: {row['status']})"
)
diff --git a/src/local_deep_research/news/subscription_manager/scheduler.py b/src/local_deep_research/news/subscription_manager/scheduler.py
index 7a5cfe4ecd..d6364089f1 100644
--- a/src/local_deep_research/news/subscription_manager/scheduler.py
+++ b/src/local_deep_research/news/subscription_manager/scheduler.py
@@ -15,6 +15,7 @@ from local_deep_research.settings.logger import log_settings
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.base import JobLookupError
+from ...constants import ResearchStatus
# RAG indexing imports
from ...research_library.services.library_rag_service import LibraryRAGService
@@ -658,7 +659,7 @@ class NewsScheduler:
f"[DOC_SCHEDULER] Querying for completed research since {last_run}"
)
query = db.query(ResearchHistory).filter(
- ResearchHistory.status == "completed",
+ ResearchHistory.status == ResearchStatus.COMPLETED,
ResearchHistory.completed_at.is_not(
None
), # Ensure completed_at is not null
diff --git a/src/local_deep_research/web/api.py b/src/local_deep_research/web/api.py
index bf2affa794..618ebfaeee 100644
--- a/src/local_deep_research/web/api.py
+++ b/src/local_deep_research/web/api.py
@@ -11,6 +11,7 @@ from flask import Blueprint, jsonify, request, Response
from loguru import logger
from ..api.research_functions import analyze_documents
+from ..constants import DEFAULT_RATE_LIMIT, RATE_LIMIT_WINDOW_SECONDS
from ..database.session_context import get_user_db_session
from ..utilities.db_utils import get_settings_manager
@@ -41,7 +42,7 @@ def api_access_control(f):
# Check if API is enabled
api_enabled = True # Default to enabled
- rate_limit = 60 # Default 60 requests per minute
+ rate_limit = DEFAULT_RATE_LIMIT
# Only try to get settings if there's an authenticated user
if username:
@@ -69,11 +70,11 @@ def api_access_control(f):
if client_ip not in rate_limit_data:
rate_limit_data[client_ip] = []
- # Remove timestamps older than 1 minute
+ # Remove timestamps older than the rate limit window
rate_limit_data[client_ip] = [
ts
for ts in rate_limit_data[client_ip]
- if current_time - ts < 60
+ if current_time - ts < RATE_LIMIT_WINDOW_SECONDS
]
# Check if rate limit is exceeded
@@ -81,7 +82,7 @@ def api_access_control(f):
return (
jsonify(
{
- "error": f"Rate limit exceeded. Maximum {rate_limit} requests per minute allowed."
+ "error": f"Rate limit exceeded. Maximum {rate_limit} requests per {RATE_LIMIT_WINDOW_SECONDS} seconds allowed."
}
),
429,
diff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.py
index 4b032460a7..716f1b2caa 100644
--- a/src/local_deep_research/web/queue/processor_v2.py
+++ b/src/local_deep_research/web/queue/processor_v2.py
@@ -10,6 +10,7 @@ from typing import Any, Dict, Optional, Set
from loguru import logger
+from ...constants import ResearchStatus
from ...database.encrypted_db import db_manager
from ...database.models import (
QueuedResearch,
@@ -152,7 +153,7 @@ class QueueProcessorV2:
db_session.query(UserActiveResearch)
.filter_by(
username=username,
- status="in_progress",
+ status=ResearchStatus.IN_PROGRESS,
)
.count()
)
@@ -224,7 +225,7 @@ class QueueProcessorV2:
active_record = UserActiveResearch(
username=username,
research_id=research_id,
- status="in_progress",
+ status=ResearchStatus.IN_PROGRESS,
thread_id="pending",
settings_snapshot=settings_snapshot,
)
@@ -326,7 +327,9 @@ class QueueProcessorV2:
# It accepts optional password parameter and returns a context manager
with get_user_db_session(username, user_password) as session:
queue_service = UserQueueService(session)
- queue_service.update_task_status(research_id, "completed")
+ queue_service.update_task_status(
+ research_id, ResearchStatus.COMPLETED
+ )
logger.info(
f"Research {research_id} completed for user {username}"
)
@@ -369,7 +372,9 @@ class QueueProcessorV2:
with get_user_db_session(username, user_password) as session:
queue_service = UserQueueService(session)
queue_service.update_task_status(
- research_id, "failed", error_message=error_message
+ research_id,
+ ResearchStatus.FAILED,
+ error_message=error_message,
)
logger.info(
f"Research {research_id} failed for user {username}: "
@@ -566,7 +571,7 @@ class QueueProcessorV2:
# Update task status
queue_service.update_task_status(
queued_research.research_id,
- "failed",
+ ResearchStatus.FAILED,
error_message="Failed to start research",
)
@@ -590,14 +595,14 @@ class QueueProcessorV2:
f"Research {queued_research.research_id} not found"
)
- research.status = "in_progress"
+ research.status = ResearchStatus.IN_PROGRESS
db_session.commit()
# Create active research record
active_record = UserActiveResearch(
username=username,
research_id=queued_research.research_id,
- status="in_progress",
+ status=ResearchStatus.IN_PROGRESS,
thread_id="pending",
settings_snapshot=queued_research.settings_snapshot,
)
diff --git a/src/local_deep_research/web/routes/api_routes.py b/src/local_deep_research/web/routes/api_routes.py
index 002cae9ea8..43a66ecdd2 100644
--- a/src/local_deep_research/web/routes/api_routes.py
+++ b/src/local_deep_research/web/routes/api_routes.py
@@ -8,6 +8,7 @@ from flask import (
from loguru import logger
from datetime import datetime, UTC
+from ...constants import ResearchStatus
from ...database.models import ResearchHistory
from ...database.session_context import get_user_db_session
from ...utilities.url_utils import normalize_url
@@ -96,7 +97,7 @@ def api_start_research():
research = ResearchHistory(
query=query,
mode=mode,
- status="in_progress",
+ status=ResearchStatus.IN_PROGRESS,
created_at=created_at,
progress_log=[{"time": created_at, "progress": 0}],
research_meta=research_settings,
diff --git a/src/local_deep_research/web/routes/history_routes.py b/src/local_deep_research/web/routes/history_routes.py
index 9f77b9e69e..ca6d155416 100644
--- a/src/local_deep_research/web/routes/history_routes.py
+++ b/src/local_deep_research/web/routes/history_routes.py
@@ -4,6 +4,7 @@ import traceback
from flask import Blueprint, jsonify, make_response, session
from loguru import logger
+from ...constants import ResearchStatus
from ...database.models import ResearchHistory
from ...database.models.library import Document as Document
from ...database.session_context import get_user_db_session
@@ -199,7 +200,7 @@ def get_research_status(research_id):
if research_id in active_research:
result["progress"] = active_research[research_id]["progress"]
result["log"] = active_research[research_id]["log"]
- elif result.get("status") == "completed":
+ elif result.get("status") == ResearchStatus.COMPLETED:
result["progress"] = 100
try:
result["log"] = json.loads(result.get("progress_log", "[]"))
@@ -292,7 +293,8 @@ def get_research_details(research_id):
"status": research.status,
"strategy": strategy_name,
"progress": active_research.get(research_id, {}).get(
- "progress", 100 if research.status == "completed" else 0
+ "progress",
+ 100 if research.status == ResearchStatus.COMPLETED else 0,
),
"created_at": research.created_at,
"completed_at": research.completed_at,
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index fa8e96a26d..955e0632f0 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -20,6 +20,7 @@ from ...settings.logger import log_settings
from sqlalchemy import func
# Security imports
+from ...constants import ResearchStatus
from ...security import FileUploadValidator, upload_rate_limit
from ...config.paths import get_config_directory
@@ -293,7 +294,7 @@ def start_research():
# Count active researches for this user
active_count = (
g.db_session.query(UserActiveResearch)
- .filter_by(username=username, status="in_progress")
+ .filter_by(username=username, status=ResearchStatus.IN_PROGRESS)
.count()
)
@@ -435,7 +436,11 @@ def start_research():
if hasattr(g, "db_session") and g.db_session:
db_session = g.db_session
# Determine initial status based on whether we need to queue
- initial_status = "queued" if should_queue else "in_progress"
+ initial_status = (
+ ResearchStatus.QUEUED
+ if should_queue
+ else ResearchStatus.IN_PROGRESS
+ )
research = ResearchHistory(
id=research_id, # Set UUID as primary key
@@ -504,7 +509,7 @@ def start_research():
# Return queued status
return jsonify(
{
- "status": "queued",
+ "status": ResearchStatus.QUEUED,
"research_id": research_id,
"queue_position": max_position + 1,
"message": f"Your research has been queued. Position in queue: {max_position + 1}",
@@ -518,7 +523,7 @@ def start_research():
active_record = UserActiveResearch(
username=username,
research_id=research_id,
- status="in_progress",
+ status=ResearchStatus.IN_PROGRESS,
thread_id=str(threading.current_thread().ident),
settings_snapshot=research_settings,
)
@@ -535,7 +540,9 @@ def start_research():
recheck_session = db_session
final_count = (
recheck_session.query(UserActiveResearch)
- .filter_by(username=username, status="in_progress")
+ .filter_by(
+ username=username, status=ResearchStatus.IN_PROGRESS
+ )
.count()
)
logger.info(
@@ -570,7 +577,7 @@ def start_research():
db_session.add(queued_record)
# Update research status to queued
- research.status = "queued"
+ research.status = ResearchStatus.QUEUED
db_session.commit()
# Notify queue processor for potential direct execution
@@ -600,7 +607,7 @@ def start_research():
return jsonify(
{
- "status": "queued",
+ "status": ResearchStatus.QUEUED,
"research_id": research_id,
"queue_position": max_position + 1,
"message": f"Your research has been queued due to concurrent limit. Position in queue: {max_position + 1}",
@@ -731,7 +738,11 @@ def terminate_research(research_id):
status = research.status
# If it's already completed or suspended, return success
- if status in ["completed", "suspended", "error"]:
+ if status in (
+ ResearchStatus.COMPLETED,
+ ResearchStatus.SUSPENDED,
+ ResearchStatus.ERROR,
+ ):
return jsonify(
{
"status": "success",
@@ -742,7 +753,7 @@ def terminate_research(research_id):
# Check if it's in the active_research dict
if research_id not in active_research:
# Update the status in the database
- research.status = "suspended"
+ research.status = ResearchStatus.SUSPENDED
db_session.commit()
return jsonify(
{"status": "success", "message": "Research terminated"}
@@ -784,13 +795,13 @@ def terminate_research(research_id):
current_log.append(log_entry)
research.progress_log = current_log
- research.status = "suspended"
+ research.status = ResearchStatus.SUSPENDED
db_session.commit()
# Emit a socket event for the termination request
try:
event_data = {
- "status": "suspended", # Changed from 'terminating' to 'suspended'
+ "status": ResearchStatus.SUSPENDED,
"message": "Research was suspended by user request",
}
@@ -841,7 +852,10 @@ def delete_research(research_id):
report_path = research.report_path
# Don't allow deleting research in progress
- if status == "in_progress" and research_id in active_research:
+ if (
+ status == ResearchStatus.IN_PROGRESS
+ and research_id in active_research
+ ):
return (
jsonify(
{
diff --git a/src/local_deep_research/web/routes/research_routes_orm.py b/src/local_deep_research/web/routes/research_routes_orm.py
index b5aabf09bb..3f53699fd9 100644
--- a/src/local_deep_research/web/routes/research_routes_orm.py
+++ b/src/local_deep_research/web/routes/research_routes_orm.py
@@ -15,6 +15,7 @@ from flask import (
from loguru import logger
from ...config.paths import get_research_outputs_directory
+from ...constants import ResearchStatus
from ...database.models import ResearchHistory
from ...database.session_context import get_user_db_session
from ..auth.decorators import login_required
@@ -107,7 +108,7 @@ def start_research():
# If the research doesn't exist in DB or is not in_progress, it's stale
if (
not research
- or research.status != "in_progress"
+ or research.status != ResearchStatus.IN_PROGRESS
or (
not research_data.get("thread")
or not research_data.get("thread").is_alive()
@@ -137,7 +138,7 @@ def start_research():
research = ResearchHistory(
query=query,
mode=mode,
- status="in_progress",
+ status=ResearchStatus.IN_PROGRESS,
created_at=created_at,
progress_log=[{"time": created_at, "progress": 0}],
research_meta=research_settings,
@@ -171,7 +172,7 @@ def terminate_research(research_id):
), 404
# If it's not in progress, return an error
- if research.status != "in_progress":
+ if research.status != ResearchStatus.IN_PROGRESS:
return (
jsonify(
{
@@ -185,7 +186,7 @@ def terminate_research(research_id):
# Check if it's in the active_research dict
if research_id not in active_research:
# Update the status in the database
- research.status = "suspended"
+ research.status = ResearchStatus.SUSPENDED
db_session.commit()
return jsonify(
{"status": "success", "message": "Research terminated"}
@@ -223,7 +224,7 @@ def terminate_research(research_id):
current_log.append(log_entry)
research.progress_log = current_log
- research.status = "terminated"
+ research.status = ResearchStatus.SUSPENDED
db_session.commit()
logger.log("MILESTONE", f"Research ended: {termination_message}")
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 959dd5008c..0db881ec24 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -12,6 +12,7 @@ from ...config.llm_config import get_llm
# Output directory for research results
from ...config.paths import get_research_outputs_directory
from ...config.search_config import get_search
+from ...constants import ResearchStatus
from ...database.models import ResearchHistory, ResearchStrategy
from ...database.session_context import get_user_db_session
from ...error_handling.report_generator import ErrorReportGenerator
@@ -230,7 +231,7 @@ def start_research_process(
active_research[research_id] = {
"thread": thread,
"progress": 0,
- "status": "in_progress",
+ "status": ResearchStatus.IN_PROGRESS,
"log": [],
"settings": kwargs, # Store settings for reference
}
@@ -994,7 +995,7 @@ def run_research_process(
research.created_at, completed_at
)
- research.status = "completed"
+ research.status = ResearchStatus.COMPLETED
research.completed_at = completed_at
research.duration_seconds = duration_seconds
# Note: report_content is saved by CachedResearchService
@@ -1257,7 +1258,7 @@ def run_research_process(
research.created_at, completed_at
)
- research.status = "completed"
+ research.status = ResearchStatus.COMPLETED
research.completed_at = completed_at
research.duration_seconds = duration_seconds
# Note: report_content is saved by CachedResearchService
@@ -1515,13 +1516,13 @@ def run_research_process(
# If termination was requested, mark as suspended instead of failed
status = (
- "suspended"
+ ResearchStatus.SUSPENDED
if (termination_flags.get(research_id))
- else "failed"
+ else ResearchStatus.FAILED
)
message = (
"Research was terminated by user"
- if status == "suspended"
+ if status == ResearchStatus.SUSPENDED
else user_friendly_error
)
@@ -1601,7 +1602,7 @@ def cleanup_research_resources(
time.sleep(5)
# Get the current status from the database to determine the final status message
- current_status = "completed" # Default
+ current_status = ResearchStatus.COMPLETED # Default
# NOTE: Queue processor already handles database updates from the main thread
# The notify_research_completed() method is called at the end of this function
@@ -1641,7 +1642,10 @@ def cleanup_research_resources(
# Send a final message to any remaining subscribers with explicit status
if socket_subscriptions.get(research_id):
# Use the proper status message based on database status
- if current_status == "suspended" or current_status == "failed":
+ if current_status in (
+ ResearchStatus.SUSPENDED,
+ ResearchStatus.FAILED,
+ ):
final_message = {
"status": current_status,
"message": f"Research was {current_status}",
@@ -1649,7 +1653,7 @@ def cleanup_research_resources(
}
else:
final_message = {
- "status": "completed",
+ "status": ResearchStatus.COMPLETED,
"message": "Research process has ended and resources have been cleaned up",
"progress": 100,
}
@@ -1694,7 +1698,7 @@ def handle_termination(
queue_processor.queue_error_update(
username=username,
research_id=research_id,
- status="suspended",
+ status=ResearchStatus.SUSPENDED,
error_message="Research was terminated by user",
metadata={"terminated_at": completed_at},
completed_at=completed_at,
@@ -1770,14 +1774,18 @@ def cancel_research(research_id, username=None):
return False
# Check if already completed or suspended
- if research.status in ["completed", "suspended", "error"]:
+ if research.status in (
+ ResearchStatus.COMPLETED,
+ ResearchStatus.SUSPENDED,
+ ResearchStatus.ERROR,
+ ):
logger.info(
f"Research {research_id} already in terminal state: {research.status}"
)
return True # Consider this a success since it's already stopped
# If it exists but isn't in active_research, still update status
- research.status = "suspended"
+ research.status = ResearchStatus.SUSPENDED
db_session.commit()
logger.info(
f"Successfully suspended research {research_id}"
diff --git a/src/local_deep_research/web/services/socket_service.py b/src/local_deep_research/web/services/socket_service.py
index 812b472f64..c8441769de 100644
--- a/src/local_deep_research/web/services/socket_service.py
+++ b/src/local_deep_research/web/services/socket_service.py
@@ -5,6 +5,7 @@ from flask import Flask, request
from flask_socketio import SocketIO
from loguru import logger
+from ...constants import ResearchStatus
from ..routes.globals import get_globals
@@ -239,7 +240,7 @@ class SocketIOService:
"message": latest_log.get(
"message", "Processing..."
),
- "status": "in_progress",
+ "status": ResearchStatus.IN_PROGRESS,
"log_entry": latest_log,
},
room=request.sid,
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
index 070ebc68e7..b3ba830001 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
@@ -8,6 +8,7 @@ from ...advanced_search_system.filters.journal_reputation_filter import (
JournalReputationFilter,
)
from ...config import search_config
+from ...constants import SNIPPET_LENGTH_SHORT
from ..rate_limiting import RateLimitError
from ..search_engine_base import BaseSearchEngine
@@ -151,8 +152,8 @@ class ArXivSearchEngine(BaseSearchEngine):
"title": paper.title,
"link": paper.entry_id, # arXiv URL
"snippet": (
- paper.summary[:250] + "..."
- if len(paper.summary) > 250
+ paper.summary[:SNIPPET_LENGTH_SHORT] + "..."
+ if len(paper.summary) > SNIPPET_LENGTH_SHORT
else paper.summary
),
"authors": [
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_collection.py b/src/local_deep_research/web_search_engines/engines/search_engine_collection.py
index 261410ae89..409829eab3 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_collection.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_collection.py
@@ -8,6 +8,7 @@ from typing import List, Dict, Any, Optional
from loguru import logger
from .search_engine_library import LibraryRAGSearchEngine
+from ...constants import SNIPPET_LENGTH_LONG
from ...research_library.services.library_rag_service import LibraryRAGService
from ...database.models.library import RAGIndex, Document
from ...research_library.services.pdf_storage_manager import PDFStorageManager
@@ -207,8 +208,8 @@ class CollectionSearchEngine(LibraryRAGSearchEngine):
# Create snippet from content
snippet = (
- doc.page_content[:500] + "..."
- if len(doc.page_content) > 500
+ doc.page_content[:SNIPPET_LENGTH_LONG] + "..."
+ if len(doc.page_content) > SNIPPET_LENGTH_LONG
else doc.page_content
)
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py b/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py
index d195244daf..84feba5e30 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py
@@ -5,6 +5,7 @@ from elasticsearch import Elasticsearch
from langchain_core.language_models import BaseLLM
from ...config import search_config
+from ...constants import SNIPPET_LENGTH_SHORT
from ..search_engine_base import BaseSearchEngine
@@ -155,7 +156,9 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
if not snippet and "content" in source:
content = source.get("content", "")
snippet = (
- content[:250] + "..." if len(content) > 250 else content
+ content[:SNIPPET_LENGTH_SHORT] + "..."
+ if len(content) > SNIPPET_LENGTH_SHORT
+ else content
)
# Create preview object
@@ -343,7 +346,9 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
if not snippet and "content" in source:
content = source.get("content", "")
snippet = (
- content[:250] + "..." if len(content) > 250 else content
+ content[:SNIPPET_LENGTH_SHORT] + "..."
+ if len(content) > SNIPPET_LENGTH_SHORT
+ else content
)
# Create preview object
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_library.py b/src/local_deep_research/web_search_engines/engines/search_engine_library.py
index 4f5babc85c..fb753370d2 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_library.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_library.py
@@ -8,6 +8,7 @@ from typing import List, Dict, Any, Optional
from loguru import logger
from ..search_engine_base import BaseSearchEngine
+from ...constants import SNIPPET_LENGTH_LONG
from ...research_library.services.library_rag_service import LibraryRAGService
from ...research_library.services.library_service import LibraryService
from ...config.thread_settings import get_setting_from_snapshot
@@ -224,8 +225,8 @@ class LibraryRAGSearchEngine(BaseSearchEngine):
# Content is stored in page_content
snippet = (
- doc.page_content[:500] + "..."
- if len(doc.page_content) > 500
+ doc.page_content[:SNIPPET_LENGTH_LONG] + "..."
+ if len(doc.page_content) > SNIPPET_LENGTH_LONG
else doc.page_content
)
@@ -337,8 +338,8 @@ class LibraryRAGSearchEngine(BaseSearchEngine):
# Replace snippet with full content
item["content"] = document.text_content
item["snippet"] = (
- document.text_content[:500] + "..."
- if len(document.text_content) > 500
+ document.text_content[:SNIPPET_LENGTH_LONG] + "..."
+ if len(document.text_content) > SNIPPET_LENGTH_LONG
else document.text_content
)
logger.debug(
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py b/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py
index 448e8c8452..24c7be057e 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py
@@ -5,6 +5,7 @@ from typing import Any, Dict, List, Optional
from langchain_core.language_models import BaseLLM
from loguru import logger
+from ...constants import SNIPPET_LENGTH_LONG
from ...advanced_search_system.filters.journal_reputation_filter import (
JournalReputationFilter,
)
@@ -261,7 +262,11 @@ class NasaAdsSearchEngine(BaseSearchEngine):
# Get abstract or create snippet
abstract = doc.get("abstract", "")
- snippet = abstract[:500] if abstract else f"Academic paper: {title}"
+ snippet = (
+ abstract[:SNIPPET_LENGTH_LONG]
+ if abstract
+ else f"Academic paper: {title}"
+ )
# Get publication info
year = doc.get("year", "unknown")
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py b/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py
index b087f2e376..c0a5f876b5 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py
@@ -5,6 +5,7 @@ from typing import Any, Dict, List, Optional
from langchain_core.language_models import BaseLLM
from loguru import logger
+from ...constants import SNIPPET_LENGTH_LONG
from ...advanced_search_system.filters.journal_reputation_filter import (
JournalReputationFilter,
)
@@ -282,7 +283,11 @@ class OpenAlexSearchEngine(BaseSearchEngine):
else:
logger.debug("No abstract_inverted_index found")
- snippet = abstract[:500] if abstract else f"Academic paper: {title}"
+ snippet = (
+ abstract[:SNIPPET_LENGTH_LONG]
+ if abstract
+ else f"Academic paper: {title}"
+ )
logger.debug(f"Created snippet: {snippet[:100]}...")
# Get publication info
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py
index 57dab00fea..33677dde5c 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py
@@ -7,6 +7,7 @@ from langchain_core.language_models import BaseLLM
from loguru import logger
from ...config import search_config
+from ...constants import SNIPPET_LENGTH_LONG
from ...security.safe_requests import safe_get
from ..rate_limiting import RateLimitError
from ..search_engine_base import BaseSearchEngine
@@ -1598,8 +1599,8 @@ The default assumption should be that medical and scientific queries want RECENT
# Build comprehensive snippet with title and abstract
title = result.get("title", "")
abstract_text = (
- abstracts[pmid][:500]
- if len(abstracts[pmid]) > 500
+ abstracts[pmid][:SNIPPET_LENGTH_LONG]
+ if len(abstracts[pmid]) > SNIPPET_LENGTH_LONG
else abstracts[pmid]
)
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_retriever.py b/src/local_deep_research/web_search_engines/engines/search_engine_retriever.py
index 1b0fbc514d..84f943e9fb 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_retriever.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_retriever.py
@@ -8,6 +8,7 @@ from typing import Any, Dict, List
from langchain_core.retrievers import BaseRetriever, Document
from loguru import logger
+from ...constants import SNIPPET_LENGTH_LONG
from ..search_engine_base import BaseSearchEngine
@@ -95,7 +96,9 @@ class RetrieverSearchEngine(BaseSearchEngine):
"source",
metadata.get("url", f"retriever://{self.name}/doc_{index}"),
),
- "snippet": doc.page_content[:500] if doc.page_content else "",
+ "snippet": doc.page_content[:SNIPPET_LENGTH_LONG]
+ if doc.page_content
+ else "",
# Optional fields
"full_content": doc.page_content,
"author": metadata.get("author", ""),
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py b/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py
index 749df1bb06..06e1e9b5a9 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py
@@ -7,6 +7,7 @@ from loguru import logger
from requests.adapters import HTTPAdapter
from urllib3.util import Retry
+from ...constants import SNIPPET_LENGTH_SHORT
from ..rate_limiting import RateLimitError
from ..search_engine_base import BaseSearchEngine
from ...security import SafeSession
@@ -559,8 +560,8 @@ Format each query on a new line with no numbering or explanation. Keep each quer
snippet = ""
if abstract:
snippet = (
- abstract[:250] + "..."
- if len(abstract) > 250
+ abstract[:SNIPPET_LENGTH_SHORT] + "..."
+ if len(abstract) > SNIPPET_LENGTH_SHORT
else abstract
)
diff --git a/tests/core/test_constants.py b/tests/core/test_constants.py
index 789f4f5a8d..b8e109a48d 100644
--- a/tests/core/test_constants.py
+++ b/tests/core/test_constants.py
@@ -4,8 +4,13 @@ Tests for constants.py
Tests cover:
- USER_AGENT constant
- BROWSER_USER_AGENT constant
+- ResearchStatus StrEnum
+- Rate limiting constants
+- Snippet length constants
"""
+from enum import StrEnum
+
class TestUserAgent:
"""Tests for USER_AGENT constant."""
@@ -88,3 +93,146 @@ class TestVersionImport:
from local_deep_research.__version__ import __version__
assert len(__version__) > 0
+
+
+class TestResearchStatus:
+ """Tests for ResearchStatus StrEnum."""
+
+ def test_research_status_is_strenum(self):
+ """ResearchStatus is a StrEnum."""
+ from local_deep_research.constants import ResearchStatus
+
+ assert issubclass(ResearchStatus, StrEnum)
+
+ def test_completed_status(self):
+ """COMPLETED is 'completed'."""
+ from local_deep_research.constants import ResearchStatus
+
+ assert ResearchStatus.COMPLETED == "completed"
+
+ def test_suspended_status(self):
+ """SUSPENDED is 'suspended'."""
+ from local_deep_research.constants import ResearchStatus
+
+ assert ResearchStatus.SUSPENDED == "suspended"
+
+ def test_failed_status(self):
+ """FAILED is 'failed'."""
+ from local_deep_research.constants import ResearchStatus
+
+ assert ResearchStatus.FAILED == "failed"
+
+ def test_in_progress_status(self):
+ """IN_PROGRESS is 'in_progress'."""
+ from local_deep_research.constants import ResearchStatus
+
+ assert ResearchStatus.IN_PROGRESS == "in_progress"
+
+ def test_pending_status(self):
+ """PENDING is 'pending'."""
+ from local_deep_research.constants import ResearchStatus
+
+ assert ResearchStatus.PENDING == "pending"
+
+ def test_error_status(self):
+ """ERROR is 'error'."""
+ from local_deep_research.constants import ResearchStatus
+
+ assert ResearchStatus.ERROR == "error"
+
+ def test_queued_status(self):
+ """QUEUED is 'queued'."""
+ from local_deep_research.constants import ResearchStatus
+
+ assert ResearchStatus.QUEUED == "queued"
+
+ def test_cancelled_status(self):
+ """CANCELLED is 'cancelled'."""
+ from local_deep_research.constants import ResearchStatus
+
+ assert ResearchStatus.CANCELLED == "cancelled"
+
+ def test_string_comparison(self):
+ """StrEnum values compare equal to plain strings."""
+ from local_deep_research.constants import ResearchStatus
+
+ assert ResearchStatus.COMPLETED == "completed"
+ assert "completed" == ResearchStatus.COMPLETED
+ assert ResearchStatus.IN_PROGRESS != "completed"
+
+ def test_membership_check(self):
+ """StrEnum supports 'in' membership testing."""
+ from local_deep_research.constants import ResearchStatus
+
+ assert "completed" in ResearchStatus
+ assert "in_progress" in ResearchStatus
+ assert "nonexistent" not in ResearchStatus
+
+ def test_all_statuses_are_strings(self):
+ """All status values are strings."""
+ from local_deep_research.constants import ResearchStatus
+
+ for member in ResearchStatus:
+ assert isinstance(member, str)
+ assert isinstance(member.value, str)
+
+ def test_all_statuses_are_unique(self):
+ """All status values are distinct."""
+ from local_deep_research.constants import ResearchStatus
+
+ values = [member.value for member in ResearchStatus]
+ assert len(values) == len(set(values))
+
+ def test_importable_from_database_models(self):
+ """ResearchStatus is importable from database.models (re-export)."""
+ from local_deep_research.constants import ResearchStatus as RS1
+ from local_deep_research.database.models.research import (
+ ResearchStatus as RS2,
+ )
+
+ assert RS1 is RS2
+
+
+class TestRateLimitConstants:
+ """Tests for rate limit constants."""
+
+ def test_rate_limit_window_seconds(self):
+ """RATE_LIMIT_WINDOW_SECONDS is a positive integer."""
+ from local_deep_research.constants import RATE_LIMIT_WINDOW_SECONDS
+
+ assert isinstance(RATE_LIMIT_WINDOW_SECONDS, int)
+ assert RATE_LIMIT_WINDOW_SECONDS > 0
+
+ def test_default_rate_limit(self):
+ """DEFAULT_RATE_LIMIT is a positive integer."""
+ from local_deep_research.constants import DEFAULT_RATE_LIMIT
+
+ assert isinstance(DEFAULT_RATE_LIMIT, int)
+ assert DEFAULT_RATE_LIMIT > 0
+
+
+class TestSnippetLengthConstants:
+ """Tests for snippet length constants."""
+
+ def test_snippet_length_short(self):
+ """SNIPPET_LENGTH_SHORT is a positive integer."""
+ from local_deep_research.constants import SNIPPET_LENGTH_SHORT
+
+ assert isinstance(SNIPPET_LENGTH_SHORT, int)
+ assert SNIPPET_LENGTH_SHORT > 0
+
+ def test_snippet_length_long(self):
+ """SNIPPET_LENGTH_LONG is a positive integer."""
+ from local_deep_research.constants import SNIPPET_LENGTH_LONG
+
+ assert isinstance(SNIPPET_LENGTH_LONG, int)
+ assert SNIPPET_LENGTH_LONG > 0
+
+ def test_long_greater_than_short(self):
+ """SNIPPET_LENGTH_LONG > SNIPPET_LENGTH_SHORT."""
+ from local_deep_research.constants import (
+ SNIPPET_LENGTH_LONG,
+ SNIPPET_LENGTH_SHORT,
+ )
+
+ assert SNIPPET_LENGTH_LONG > SNIPPET_LENGTH_SHORT