osint-dashboard/news/summerizer/nous_client.py
backend 625c935c80 fix(summarizer): fail loudly on a rejected model id; parallel map phase
The analyst produced no briefs for nine days because SUMMARY_MODEL had been
retired: every chat completion returned 404, nous_client.chat() swallowed it
into "", and the map phase "succeeded" with zero blocks.

- nous_client.chat(): log status_code + a 500-char body slice for every
  non-200. 400/404/422 now raise NousAPIError (bad model id / payload cannot
  succeed on a retry); 429/5xx are retried with backoff inside the call;
  401/other keep the old empty-return contract.
- Startup validation: one GET /models per process; if SUMMARY_MODEL is absent
  the run logs an ERROR with the configured id plus near matches and returns
  rc=2 before issuing any chat call. Fails open (warning) when /models itself
  is unreachable.
- Map phase: ThreadPoolExecutor fan-out capped by SUMMARY_MAP_CONCURRENCY
  (default 16). Grading still runs in batch order on the main thread; reduce
  stays serial; the 60 s per-call timeout is unchanged.
- summarize_news() now returns an exit code and __main__ sys.exit()s it:
  zero parsed map blocks, an empty reduce, or an unpersisted brief all exit
  non-zero. The scheduler logs rc at ERROR when it is not 0.
- Map calls start at 8192 completion tokens (they escalate to 16384): ~60% of
  real batches overflowed 4096 and were regenerated at 8192, doubling their
  wall time for no benefit.

Measured on the real backlog: NEWS_RECAP=1 NEWS_SUMMARIZE_FORCE=1
python summarizer.py over 2984 articles / 746 batches finished in 951 s
(15m51s), rc=0, 746/746 batches non-empty, 0 warnings.

Prompts, BATCH_SIZE=4, grading/rubric behaviour and the DB schema are
untouched (article_summaries.kind stays interval / daily_recap).
2026-12-04 23:34:54 -05:00

273 lines
9.9 KiB
Python

"""HTTP client for the Nous inference chat completions API.
Every non-200 is logged with its status code and a slice of the body. A
non-retryable rejection (400/404/422 — e.g. a retired model id) raises
``NousAPIError`` so a misconfigured run aborts loudly instead of quietly
mapping zero batches for days. 429/5xx are retried inside the call.
"""
from __future__ import annotations
import difflib
import logging
import os
import time
import httpx
logger = logging.getLogger("news.nous_client")
_DEFAULT_UA = "osint-dashboard-news-summarizer"
_DEFAULT_BASE = "https://inference-api.nousresearch.com/v1"
_JSON_SYSTEM = (
"You are an OSINT executive briefer. Reply with a single complete JSON object. "
"Never truncate mid-sentence. If you run out of room, drop the lowest-priority item."
)
# How much of an error body to log.
BODY_LOG_CHARS = 500
# Requests that can never succeed on a retry: a retired model id (404), a
# malformed payload (400) or a rejected schema (422). Swallowing these is how
# the summarizer idled for nine days with an empty brief.
HARD_ERROR_STATUS = frozenset({400, 404, 422})
# Transient: retried with backoff inside the single call.
RETRY_STATUS = frozenset({429, 500, 502, 503, 504})
MAX_ATTEMPTS = 3
MAX_TOKENS_CEILING = 16384
# A map call over four full articles routinely needs more than 4096 completion
# tokens on the live model, and the old code then regenerated the whole answer
# with 8192 — two calls' worth of latency for one batch. Start text calls at
# the budget they escalate to anyway; the ceiling escalation below still
# covers genuinely truncated answers.
MAX_TOKENS_TEXT = 8192
MAX_TOKENS_JSON = 8192
class NousAPIError(RuntimeError):
"""A non-retryable non-200 from the Nous API (bad model id, bad payload...)."""
def __init__(self, status_code: int, body: str, url: str = "") -> None:
self.status_code = status_code
self.body = body
self.url = url
super().__init__(f"Nous API {status_code} from {url}: {body[:BODY_LOG_CHARS]}")
def _resolve_base(base_url: str | None) -> str:
return (base_url or os.environ.get("NOUS_BASE_URL", _DEFAULT_BASE)).rstrip("/")
def _headers(api_key: str) -> dict:
return {
"Authorization": f"Bearer {api_key}",
"User-Agent": os.environ.get("OSINT_USER_AGENT") or _DEFAULT_UA,
}
def _body_text(resp) -> str:
"""Best-effort response body as text (httpx exposes .text)."""
try:
text = resp.text
except Exception: # noqa: BLE001 — a dead response must not mask the status
return ""
return text if isinstance(text, str) else ""
def _retry_backoff(attempt: int) -> float:
"""Seconds to sleep before retry ``attempt`` (1-based); env-tunable for tests."""
try:
base = float(os.environ.get("NOUS_RETRY_BACKOFF_S", "2"))
except ValueError:
base = 2.0
return max(0.0, base) * (2 ** (attempt - 1))
def _sleep_before_retry(attempt: int) -> None:
delay = _retry_backoff(attempt)
if delay:
time.sleep(delay)
def chat(prompt, *, api_key, model, base_url, json_mode=False) -> str:
"""POST one chat completion.
Returns the message content, or ``""`` for retryable/exhausted failures.
Raises ``NousAPIError`` when the API rejects the request itself
(400/404/422) — the caller must treat that as fatal for the run.
"""
resolved = _resolve_base(base_url)
url = f"{resolved}/chat/completions"
headers = _headers(api_key)
max_tokens = MAX_TOKENS_JSON if json_mode else MAX_TOKENS_TEXT
timeout = 120.0 if json_mode else 60.0
messages = [{"role": "user", "content": prompt}]
if json_mode:
messages = [
{"role": "system", "content": _JSON_SYSTEM},
{"role": "user", "content": prompt},
]
payload = {
"model": model,
"messages": messages,
"temperature": 0.2,
"max_tokens": max_tokens,
}
if json_mode:
payload["response_format"] = {"type": "json_object"}
for attempt in range(1, MAX_ATTEMPTS + 1):
try:
with httpx.Client(timeout=timeout) as client:
resp = client.post(url, headers=headers, json=payload)
except httpx.HTTPError as exc:
logger.warning(
"Nous chat transport error model=%s attempt=%d/%d: %r",
model, attempt, MAX_ATTEMPTS, exc,
)
if attempt < MAX_ATTEMPTS:
_sleep_before_retry(attempt)
continue
return ""
if resp.status_code != 200:
body = _body_text(resp)[:BODY_LOG_CHARS]
if resp.status_code in HARD_ERROR_STATUS:
logger.error(
"Nous chat rejected the request model=%s status=%s url=%s "
"attempt=%d/%d body=%s — not retryable, aborting run",
model, resp.status_code, url, attempt, MAX_ATTEMPTS, body,
)
raise NousAPIError(resp.status_code, _body_text(resp), url)
logger.warning(
"Nous chat non-200 model=%s status=%s url=%s attempt=%d/%d body=%s",
model, resp.status_code, url, attempt, MAX_ATTEMPTS, body,
)
if resp.status_code in RETRY_STATUS and attempt < MAX_ATTEMPTS:
_sleep_before_retry(attempt)
continue
return ""
try:
data = resp.json()
except ValueError:
logger.warning(
"Nous chat returned non-JSON model=%s status=200 attempt=%d/%d body=%s",
model, attempt, MAX_ATTEMPTS, _body_text(resp)[:BODY_LOG_CHARS],
)
if attempt < MAX_ATTEMPTS:
_sleep_before_retry(attempt)
continue
return ""
choices = (data.get("choices") if isinstance(data, dict) else None) or [{}]
choice = choices[0] or {}
content = (choice.get("message") or {}).get("content") or ""
if (
choice.get("finish_reason") == "length"
and payload["max_tokens"] < MAX_TOKENS_CEILING
):
payload["max_tokens"] = min(payload["max_tokens"] * 2, MAX_TOKENS_CEILING)
logger.warning(
"Nous chat hit max_tokens model=%s — retrying with max_tokens=%d",
model, payload["max_tokens"],
)
continue
return content
return ""
# ── Startup model validation ───────────────────────────────────────────────
# One GET /models per (base_url, model) per process: a retired SUMMARY_MODEL
# must disable the run before 745 batch calls hammer the API.
_MODEL_AVAILABLE: dict[tuple[str, str], bool] = {}
def list_models(*, api_key: str, base_url: str | None = None, timeout: float = 30.0) -> list[str]:
"""GET {base_url}/models and return the offered model ids.
Raises ``NousAPIError`` on a non-200 so the caller decides whether to fail
open (skip validation) or abort.
"""
resolved = _resolve_base(base_url)
url = f"{resolved}/models"
with httpx.Client(timeout=timeout) as client:
resp = client.get(url, headers=_headers(api_key))
if resp.status_code != 200:
body = _body_text(resp)[:BODY_LOG_CHARS]
logger.error("Nous /models returned status=%s url=%s body=%s", resp.status_code, url, body)
raise NousAPIError(resp.status_code, _body_text(resp), url)
try:
data = resp.json()
except ValueError as exc:
raise NousAPIError(
resp.status_code,
f"non-JSON /models body: {_body_text(resp)[:BODY_LOG_CHARS]}",
url,
) from exc
items = data
if isinstance(data, dict):
items = data.get("data") or data.get("models") or []
ids: list[str] = []
for item in items or []:
if isinstance(item, dict):
mid = item.get("id") or item.get("name") or item.get("model")
else:
mid = item
if isinstance(mid, str) and mid:
ids.append(mid)
return ids
def _near_matches(model: str, ids: list[str], n: int = 3) -> list[str]:
"""A couple of ids that look like what the operator probably meant."""
matches = difflib.get_close_matches(model, ids, n=n, cutoff=0.45)
org, sep, tail = model.partition("/")
stem = tail.split(":", 1)[0].split("-", 1)[0] if sep else ""
extra = [
mid
for mid in ids
if mid not in matches
and ((sep and mid.split("/", 1)[0] == org) or (stem and stem.lower() in mid.lower()))
]
return (matches + extra)[:n]
def model_available(*, api_key: str, base_url: str | None = None, model: str) -> bool:
"""True when ``model`` is offered by the portal; cached once per process.
Fails open (True, with a warning) when /models itself is unreachable: a
flaky listing endpoint must not disable the pipeline, and ``chat()`` now
raises on a genuinely rejected model id anyway.
"""
resolved = _resolve_base(base_url)
key = (resolved, model)
if key in _MODEL_AVAILABLE:
return _MODEL_AVAILABLE[key]
try:
ids = list_models(api_key=api_key, base_url=resolved)
except (NousAPIError, httpx.HTTPError) as exc:
logger.warning(
"Could not validate SUMMARY_MODEL=%s against %s/models (%s) — "
"continuing without startup validation",
model, resolved, exc,
)
return True
available = model in ids
if not available:
near = _near_matches(model, ids)
logger.error(
"SUMMARY_MODEL=%r is not offered by %s (%d models listed). "
"Near matches: %s. Runs are skipped until the model exists.",
model, resolved, len(ids), ", ".join(near) if near else "none",
)
_MODEL_AVAILABLE[key] = available
return available
def reset_model_cache() -> None:
"""Drop the per-process /models memo (tests, or a long-lived scheduler)."""
_MODEL_AVAILABLE.clear()