Revert "feat: rebuild news summarizer on local Ollama"

This reverts commit 58ff43bdee.
This commit is contained in:
Sirius DevOps 2026-08-28 19:49:51 -04:00
commit c10b617f1f
15 changed files with 339 additions and 336 deletions

View file

@ -57,6 +57,11 @@ KEY_REGISTRY: dict[str, dict] = {
"pattern": r"^[0-9a-fA-F]{32}$",
"example": "32-char hex string (e.g. 5f3c…9a02)",
},
"NOUS_API_KEY": {
"description": "Nous Portal API key — hourly news summarizer (inference-api.nousresearch.com).",
"pattern": r"^.{16,}$",
"example": "key from https://portal.nousresearch.com (API keys page)",
},
"TELEGRAM_TOKEN": {
"description": "Telegram bot token — push alert notifications to a channel.",
"pattern": r"^\d{8,10}:[0-9A-Za-z_-]{35}$",
@ -209,7 +214,7 @@ async def get_api_key(name: str) -> str | None:
"""Read a stored key value — used by ingest services, never by the API.
Returns the raw value (or None when unset) so producers can pass it to
external APIs (FIRMS, Telegram, …). Reads live from Postgres, so a
external APIs (FIRMS, Nous, Telegram, …). Reads live from Postgres, so a
key set via the dashboard is picked up on the next poll — no restart.
"""
await ensure_api_keys_table()

View file

@ -605,7 +605,7 @@ async def list_documents(
async def list_api_keys():
"""List known API keys with set/missing status — masked, never raw.
Registered keys (FIRMS_MAP_KEY, TELEGRAM_TOKEN)
Registered keys (FIRMS_MAP_KEY, NOUS_API_KEY, TELEGRAM_TOKEN)
are always included. Any extra stored keys are appended.
"""
return await list_keys()
@ -638,13 +638,13 @@ async def remove_api_key(name: str):
@app.get("/api/settings", response_model=SettingsOut)
async def get_settings():
"""Summarizer model + read-only Ollama URL."""
"""Summarizer model + read-only Nous base URL."""
return await get_app_settings()
@app.put("/api/settings", response_model=SettingsOut)
async def put_settings(payload: SettingsIn):
"""Persist SUMMARY_MODEL. ``llm_url`` is ignored even if sent."""
"""Persist SUMMARY_MODEL. ``nous_base_url`` is ignored even if sent."""
try:
return await set_summary_model(payload.summary_model)
except SettingsError as exc:
@ -1084,7 +1084,7 @@ async def camera_hls_segment(camera_id: UUID, u: str = Query(..., min_length=8))
# ── News pipeline (scraper + summarizer) ──────────────────────────────────
# Backing data for the frontend news panel. Written by the vendored
# news-scraper (hourly Scrapy crawl) and news-summarizer (hourly Ollama
# news-scraper (hourly Scrapy crawl) and news-summarizer (hourly Gemini
# map-reduce) services into the shared osint-db.
@app.get("/api/news", response_model=list[NewsArticleOut])
@ -1249,7 +1249,7 @@ async def list_news_map(
@app.get("/api/news/models", response_model=NewsModelsOut)
async def list_news_models():
"""Ollama model catalog for the summarizer selector. Never 502s."""
"""Nous model catalog for the summarizer selector. Never 502s."""
return await list_models()

View file

@ -316,7 +316,7 @@ class NewsModelsOut(BaseModel):
class SettingsIn(BaseModel):
"""Body for PUT /api/settings. ``llm_url`` is not writable."""
"""Body for PUT /api/settings. ``nous_base_url`` is not writable."""
summary_model: str = Field(..., min_length=1, max_length=128)
@ -332,10 +332,10 @@ class SettingsIn(BaseModel):
class SettingsOut(BaseModel):
"""Current summarizer settings. ``llm_url`` is read-only."""
"""Current summarizer settings. ``nous_base_url`` is read-only."""
summary_model: str
llm_url: str
nous_base_url: str
# ─── Aggregations ────────────────────────────────────────────────────────

View file

@ -17,10 +17,11 @@ from datetime import datetime, timezone
import httpx
from sqlalchemy import Column, DateTime, String, Table, Text, func, select, text
import keystore
from database import async_session, engine, metadata
DEFAULT_LLM_URL = "http://127.0.0.1:11434"
DEFAULT_SUMMARY_MODEL = "qwen3:30b-a3b"
DEFAULT_NOUS_BASE_URL = "https://inference-api.nousresearch.com/v1"
DEFAULT_SUMMARY_MODEL = "Hermes-4.3-36B"
SETTING_SUMMARY_MODEL = "SUMMARY_MODEL"
ALLOWED_SETTINGS = frozenset({SETTING_SUMMARY_MODEL})
MODELS_CACHE_TTL_S = 600.0
@ -28,7 +29,12 @@ MODELS_TIMEOUT_S = 8.0
DEFAULT_MODELS_USER_AGENT = "osint-dashboard-news-summarizer"
FALLBACK_MODELS = [
"qwen3:30b-a3b",
"Hermes-4.3-36B",
"Hermes-4-70B",
"google/gemini-2.5-flash",
"anthropic/claude-haiku-4.5",
"openai/gpt-4.1-mini",
"x-ai/grok-4",
]
app_settings = Table(
@ -71,14 +77,10 @@ async def ensure_app_settings_table() -> None:
_ensured = True
def llm_url() -> str:
"""Read-only Ollama origin (env, never writable from the UI)."""
raw = (os.getenv("LLM_URL") or "").strip().rstrip("/")
for suffix in ("/api/generate", "/api/chat", "/api", "/v1"):
if raw.endswith(suffix):
raw = raw[: -len(suffix)].rstrip("/")
break
return raw or DEFAULT_LLM_URL
def nous_base_url() -> str:
"""Read-only Nous inference base URL (env, never writable from the UI)."""
raw = (os.getenv("NOUS_BASE_URL") or "").strip().rstrip("/")
return raw or DEFAULT_NOUS_BASE_URL
def _validate_summary_model(value: str) -> str:
@ -89,7 +91,7 @@ def _validate_summary_model(value: str) -> str:
async def get_summary_model() -> str:
"""Stored SUMMARY_MODEL, else env, else qwen3:30b-a3b."""
"""Stored SUMMARY_MODEL, else env, else Hermes-4.3-36B."""
await ensure_app_settings_table()
async with async_session() as session:
row = (
@ -133,7 +135,7 @@ async def set_summary_model(value: str) -> dict:
async def get_app_settings() -> dict:
return {
"summary_model": await get_summary_model(),
"llm_url": llm_url(),
"nous_base_url": nous_base_url(),
}
@ -144,6 +146,18 @@ def _fallback_payload() -> dict:
}
async def _nous_api_key() -> str | None:
"""Keystore first, then env. Any lookup failure is treated as missing."""
try:
stored = await keystore.get_api_key("NOUS_API_KEY")
except Exception:
stored = None
if stored and str(stored).strip():
return str(stored).strip()
env = (os.getenv("NOUS_API_KEY") or "").strip()
return env or None
def _models_user_agent() -> str:
return os.getenv("OSINT_USER_AGENT") or DEFAULT_MODELS_USER_AGENT
@ -160,7 +174,7 @@ def _parse_models_payload(body: object) -> list[dict[str, str]]:
if isinstance(item, str) and item.strip():
out.append({"id": item.strip()})
elif isinstance(item, dict):
mid = item.get("id") or item.get("name") or item.get("model")
mid = item.get("id") or item.get("name")
if mid:
out.append({"id": str(mid)})
return out
@ -172,15 +186,23 @@ async def _http_get(url: str, *, headers: dict[str, str], timeout: float) -> htt
async def list_models() -> dict:
"""Live ``GET {llm_url}/api/tags``. Never 502 — fallback on failure."""
"""Live ``GET {base}/models`` when a key is present; otherwise curated fallback.
Never raises to the caller for missing key or upstream failure.
"""
global _models_cache
key = await _nous_api_key()
if not key:
return _fallback_payload()
now = time.monotonic()
hit = _models_cache
if hit and now - hit[0] < MODELS_CACHE_TTL_S:
return hit[1]
url = f"{llm_url()}/api/tags"
url = f"{nous_base_url()}/models"
headers = {
"Authorization": f"Bearer {key}",
"User-Agent": _models_user_agent(),
"Accept": "application/json",
}

View file

@ -840,7 +840,7 @@
<div class="ns-kicker">Executive Summary <span class="ns-badge" id="ns-badge">WAITING</span></div>
<div class="ns-time" id="ns-time">—</div>
<div class="ns-body" id="ns-body">
<div class="ns-empty">No executive summary yet — the Ollama summarizer is idle until a model is chosen in Settings and <code>LLM_URL</code> is reachable.</div>
<div class="ns-empty">No executive summary yet — the Nous summarizer is idle until <code>NOUS_API_KEY</code> is set on the Pi and a model is chosen in Settings.</div>
</div>
</div>
@ -968,7 +968,7 @@
<section class="view" id="view-keys" aria-label="API keys">
<div class="subview">
<h2><span class="tick">⚿</span> API Keys</h2>
<p class="sub">Keys used by ingest services (FIRMS, Telegram, AIS, …). Stored in Postgres, never shown again — only status + last 4 chars.</p>
<p class="sub">Keys used by ingest services (FIRMS, Nous Portal, Telegram, AIS, …). Stored in Postgres, never shown again — only status + last 4 chars.</p>
<div class="key-grid" id="keys-grid"></div>
</div>
</section>
@ -997,11 +997,11 @@
<p class="set-note" style="margin-bottom:0.9rem">Takes effect on the next hourly run (:05). No container restart.</p>
<div class="set-row">
<label>Provider</label>
<span>Local Ollama (LLM_URL)</span>
<span>Nous Portal (inference-api.nousresearch.com)</span>
</div>
<div class="set-row">
<label>API key</label>
<span>none — Ollama on the GPU host</span>
<span>set in API Keys as NOUS_API_KEY (never shown here)</span>
</div>
<div class="set-row">
<label for="set-summary-model">Model</label>
@ -1370,7 +1370,7 @@ function renderNewsSummary(summaries) {
const badgeEl = document.getElementById('ns-badge');
if (!bodyEl) return;
if (!summaries || !summaries.length) {
bodyEl.innerHTML = '<div class="ns-empty">No executive summary yet — the Ollama summarizer is idle until a model is chosen in Settings and <code>LLM_URL</code> is reachable.</div>';
bodyEl.innerHTML = '<div class="ns-empty">No executive summary yet — the Nous summarizer is idle until <code>NOUS_API_KEY</code> is set on the Pi and a model is chosen in Settings.</div>';
timeEl.textContent = '—';
badgeEl.textContent = 'WAITING';
return;
@ -1547,6 +1547,7 @@ function sentimentBadge(label) {
/* ═══════════════ API KEYS ═══════════════ */
const KEY_PATTERNS = {
'FIRMS_MAP_KEY': /^[0-9a-fA-F]{32}$/,
'NOUS_API_KEY': /^.{16,}$/,
'TELEGRAM_TOKEN': /^\d{8,10}:[0-9A-Za-z_-]{35}$/,
};
async function loadKeys() {