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.

9.2 KB
Raw Blame
"""Shared helpers for executing news subscriptions.

These centralize logic that was previously copy-pasted across the three places
that run a subscription:

* ``run_subscription_now`` (manual "run now" button) and
  ``check_overdue_subscriptions`` (the overdue sweep) -- both start research
  in-process via ``flask_api._call_start_research_internal`` and share the
  request payload built here. (They previously issued a loopback HTTP POST to
  ``/research/api/start``, which always failed CSRF validation.)
* ``BackgroundJobScheduler`` -- triggers research programmatically, but shares
  the refresh-schedule arithmetic.

Keeping the payload shape and the schedule arithmetic in one place stops the
three call sites from drifting (which they previously had: differing metadata,
a forgotten search-engine field, and a refresh-time update that one path
skipped entirely).
"""

from datetime import datetime, timedelta, timezone
from typing import Any, Dict, Optional, Tuple


def resolve_subscription_model(
    model_provider: Any, model: Any
) -> Tuple[Optional[str], Optional[str]]:
    """Return the ``(provider, model)`` a saved subscription runs with.

    ``None`` in either place means "use the user's setting" (``llm.provider``
    / ``llm.model``). The scheduler and the run-now/overdue payload both
    resolve a saved row here, so every path runs it the same way.

    * An empty model is unset, and so is a provider that is not a built-in
      provider key. A kept provider is returned in lowercase canonical form.
    * Before #7860 the news page's "Create Subscription" saved the whole
      selection as the model and its first colon segment as the provider
      (lowercased on save). Such a row is recognised by the model's first
      segment naming the stored provider (compared ignoring case). The
      model field is free text, so the case of that segment is a heuristic
      for whether it was picked from the dropdown, whose options use the
      uppercase key, or typed:

      - exactly an uppercase built-in key: the ``KEY:`` prefix is stripped
        once and the provider kept, so
        ``("ollama", "OLLAMA:llama3.1:8b")`` -> ``("ollama", "llama3.1:8b")``;
      - anything else is taken as a model tag typed by hand, not a provider
        choice: the provider is unset and the model kept whole, so
        ``("qwen", "qwen:7b")`` -> ``(None, "qwen:7b")`` and
        ``("llama3.1", "llama3.1:8b")`` -> ``(None, "llama3.1:8b")``. A
        lowercase key is deliberately treated the same way, so
        ``("ollama", "ollama:llama3.1:8b")`` -> ``(None,
        "ollama:llama3.1:8b")``, so that a typed tag such as ``qwen:7b``
        stays a model name instead of being read as a provider prefix. That
        is how scheduled runs have run these rows so far.

    * Any other model is kept as saved: ``("ollama", "llama3.1:8b")`` and
      ``("openai", "OPENAI_ENDPOINT:org/model")`` are unchanged.
    """
    from ..llm.providers import discover_providers
    from ..llm.providers.base import normalize_provider

    if not isinstance(model, str) or not model.strip():
        model = None
    provider = model_provider.strip() if isinstance(model_provider, str) else ""
    keys = discover_providers()  # built-in keys, uppercase
    resolved = (
        normalize_provider(provider) if provider.upper() in keys else None
    )

    head, separator, rest = (model or "").partition(":")
    if provider and separator and head.lower() == provider.lower():
        # Saved by the old Create Subscription; ``head in keys`` is a
        # case-sensitive match against the uppercase keys.
        if resolved and head in keys:
            return resolved, rest if rest.strip() else None
        return None, model
    return resolved, model


def build_subscription_request_data(
    *,
    query_template: str,
    current_date: str,
    triggered_by: str,
    subscription_id: Any,
    model_provider: Optional[str] = None,
    model: Optional[str] = None,
    search_strategy: Optional[str] = None,
    search_engine: Optional[str] = None,
    custom_endpoint: Optional[str] = None,
    title: Optional[str] = None,
    mode: str = "quick",
) -> Dict[str, Any]:
    """Build the ``/research/api/start`` payload for a subscription run.

    Replaces the ``YYYY-MM-DD`` placeholder in ``query_template`` with
    ``current_date`` (the user's timezone-local date) and assembles the news
    metadata block. Shared by the manual run-now route and the overdue sweep so
    their payloads cannot diverge.

    ``model_provider``/``model`` are resolved with
    ``resolve_subscription_model`` (as the scheduler does) and sent even when
    unset (``None``): an unset provider/model is intentional and makes the
    backend fall back to the user's ``llm.provider`` / ``llm.model`` settings
    (see ``web/routers/research.py::_extract_research_params``). Hardcoding a
    provider here would override the user's configured default for
    subscriptions created without an explicit model.
    """
    query = query_template.replace("YYYY-MM-DD", current_date)
    model_provider, model = resolve_subscription_model(model_provider, model)

    request_data: Dict[str, Any] = {
        "query": query,
        "mode": mode,
        "model_provider": model_provider,
        "model": model,
        "strategy": search_strategy or "news_aggregation",
        "metadata": {
            "is_news_search": True,
            "search_type": "news_analysis",
            "display_in": "news_feed",
            "subscription_id": str(subscription_id),
            "triggered_by": triggered_by,
            # Original query keeps the placeholder; processed_query/news_date
            # record what was actually run.
            "original_query": query_template,
            "processed_query": query,
            "news_date": current_date,
            "title": title or None,
        },
    }

    # Optional fields are only included when set, matching the research API's
    # "absent means use default" contract.
    if search_engine:
        request_data["search_engine"] = search_engine
    if custom_endpoint:
        request_data["custom_endpoint"] = custom_endpoint

    return request_data


def advance_refresh_schedule(
    subscription, now: Optional[datetime] = None
) -> None:
    """Advance a subscription's refresh timestamps after a successful run.

    Sets ``last_refresh`` to ``now`` and ``next_refresh`` one
    ``refresh_interval_minutes`` later. Shared by the manual run, the overdue
    sweep, and the scheduler so the arithmetic -- and remembering to advance
    the schedule at all -- lives in one place.

    Raises ``NewsAPIException`` (``INVALID_REFRESH_INTERVAL``) before
    touching either timestamp when the saved interval is not runnable (see
    ``is_runnable_refresh_interval``). That is the saved-row bound, not the
    narrower cap on newly written values, so a long interval saved by an
    older version still advances.
    """
    from .constants import validate_runnable_refresh_interval

    validate_runnable_refresh_interval(subscription.refresh_interval_minutes)
    if now is None:
        now = datetime.now(timezone.utc)
    subscription.last_refresh = now
    subscription.next_refresh = now + timedelta(
        minutes=subscription.refresh_interval_minutes
    )


def advance_refresh_schedule_by_id(db_session, subscription_id) -> bool:
    """Load a subscription by id and advance its refresh schedule.

    Convenience wrapper for callers that only have an id and an open session
    (e.g. the research service's post-completion update, which runs once for
    the quick path and once for the detailed path). Returns True if the
    subscription was found and advanced. Does not commit -- the caller owns
    the transaction.
    """
    from ..database.models.news import NewsSubscription

    subscription = (
        db_session.query(NewsSubscription)
        .filter(NewsSubscription.id == str(subscription_id))
        .first()
    )
    if not subscription:
        return False
    advance_refresh_schedule(subscription, datetime.now(timezone.utc))
    return True


def mark_subscription_due_by_id(db_session, subscription_id) -> bool:
    """Reset a subscription to "due" after a FAILED run.

    ``run_subscription_now`` (and the overdue sweep) advance ``next_refresh``
    at spawn time so the scheduler will not double-run a subscription whose
    research is still in flight. If that research then FAILS, the success-only
    completion advance never fires, leaving ``next_refresh`` pushed a full
    interval into the future and the subscription silently skipped until then.
    The research failure handler calls this to reset ``next_refresh`` to now so
    the scheduler picks the subscription up again on its next cycle -- matching
    the pre-consolidation behavior where a failed manual run left the
    subscription due. ``last_refresh`` is intentionally left untouched (it
    records the last *successful* refresh). Returns True if the subscription
    was found. Does not commit -- the caller owns the transaction.
    """
    from ..database.models.news import NewsSubscription

    subscription = (
        db_session.query(NewsSubscription)
        .filter(NewsSubscription.id == str(subscription_id))
        .first()
    )
    if not subscription:
        return False
    subscription.next_refresh = datetime.now(timezone.utc)
    return True