feat(summarizer): score articles in the map phase, brief only the important ones
The map prompt now grades every article 0-100 against an explicit rubric as the first line of its block; the summarizer parses Score:, falls back to the Importance: label when the line is missing, ranks blocks best-first and passes only score >= SUMMARY_MIN_SCORE (capped at SUMMARY_TOP_N) to the reduce phase. - new pure helpers in intel.py: parse_map_scores(), select_graded(), join_blocks() - reduce prompts drop the 'fill the brief with minor incidents and crime' filler instructions and the 'fill ticker with medium then low' clause - new article_scores table (ensure_tables + alembic 012) persists every grade with selected/summary_id/model so thresholds can be tuned from data - SUMMARY_MIN_SCORE (60), SUMMARY_TOP_N (12), SUMMARY_FALLBACK_TOP (3) env knobs
This commit is contained in:
parent
84ea0a17b1
commit
853e87b7c5
8 changed files with 775 additions and 37 deletions
|
|
@ -31,7 +31,7 @@ from zoneinfo import ZoneInfo
|
|||
|
||||
import psycopg2
|
||||
|
||||
from intel import parse_reduce_json, select_map, select_ticker
|
||||
from intel import join_blocks, parse_map_scores, parse_reduce_json, select_graded, select_map, select_ticker
|
||||
from nous_client import chat
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
|
|
@ -50,6 +50,30 @@ DEFAULT_NOUS_BASE_URL = "https://inference-api.nousresearch.com/v1"
|
|||
DEFAULT_SUMMARY_MODEL = "Hermes-4.3-36B"
|
||||
BATCH_SIZE = int(os.getenv("BATCH_SIZE", "50"))
|
||||
|
||||
# Map-phase grading knobs (operator sets them in the cluster ConfigMap).
|
||||
DEFAULT_SUMMARY_MIN_SCORE = 60
|
||||
DEFAULT_SUMMARY_TOP_N = 12
|
||||
DEFAULT_SUMMARY_FALLBACK_TOP = 3
|
||||
|
||||
|
||||
def _env_int(name: str, default: int) -> int:
|
||||
raw = (os.getenv(name) or "").strip()
|
||||
if not raw:
|
||||
return default
|
||||
try:
|
||||
return int(raw)
|
||||
except ValueError:
|
||||
logger.warning("Invalid %s=%r — using default %s", name, raw, default)
|
||||
return default
|
||||
|
||||
|
||||
def selection_config() -> tuple[int, int, int]:
|
||||
"""(min_score, top_n, fallback_top) from env, read per run."""
|
||||
min_score = max(0, min(100, _env_int("SUMMARY_MIN_SCORE", DEFAULT_SUMMARY_MIN_SCORE)))
|
||||
top_n = max(0, _env_int("SUMMARY_TOP_N", DEFAULT_SUMMARY_TOP_N))
|
||||
fallback_top = max(0, _env_int("SUMMARY_FALLBACK_TOP", DEFAULT_SUMMARY_FALLBACK_TOP))
|
||||
return min_score, top_n, fallback_top
|
||||
|
||||
|
||||
def _summary_window_minutes() -> int:
|
||||
hours = (os.getenv("SUMMARY_WINDOW_HOURS") or "").strip()
|
||||
|
|
@ -94,30 +118,40 @@ FUTURES_TICKERS = {
|
|||
MAP_PROMPT_DEFAULT = """\
|
||||
You are a precise, factual OSINT news processor. Your ONLY source of information is the articles provided below. Do NOT add external knowledge, assumptions, training data, or invented facts.
|
||||
|
||||
Focus on breaking important news (geopolitical, military/conflict, security, disasters, major political developments). Ignore futures prices, commodity tape, ticker chatter, and routine market moves unless they themselves are the breaking event. If the batch has no critical/high stories, still extract minor incidents and crime reports.
|
||||
Focus on breaking important news (geopolitical, military/conflict, security, disasters, major political developments). Ignore futures prices, commodity tape, ticker chatter, and routine market moves unless they themselves are the breaking event. Extract every article; the Score below decides what reaches the operator brief.
|
||||
|
||||
Write every field in English. Translate if the article is not English.
|
||||
|
||||
Grade every article with this rubric before writing anything else in its block:
|
||||
|
||||
- 90–100 — breaking geopolitical/military/security event or major disaster, immediate consequence
|
||||
- 70–89 — significant national/international politics, conflict, security, infrastructure or disaster news
|
||||
- 40–69 — notable regional/economic/tech/health story with real consequences
|
||||
- 10–39 — routine, minor or single-incident crime; local interest
|
||||
- 0–9 — noise: sport, celebrity, entertainment, market/commodity tape, promotional or event-calendar/schedule listings
|
||||
|
||||
For EACH article in the batch:
|
||||
1. Extract 2-4 key factual bullet points (who, what, when, where, numbers, quotes — stay very close to the text).
|
||||
2. Location: country/city/region or Unknown. If you can estimate coordinates, emit them as numbers; otherwise omit.
|
||||
3. Entities: list the key people, organizations, or governments mentioned (comma-separated, only names present in the text), else "None".
|
||||
4. Category: pick one — politics, military/conflict, economy, technology, environment/disaster, health, crime, society, sport, other.
|
||||
5. OSINT signal: if the article describes a breaking event with geopolitical, security, military, or disaster significance, say so in one short sentence. Otherwise write: "No notable OSINT signal."
|
||||
6. Importance: critical (breaking geopolitical/military/disaster with immediate impact), high, medium, low, none.
|
||||
1. Score: the integer 0-100 from the rubric above, first line of the block.
|
||||
2. Extract 2-4 key factual bullet points (who, what, when, where, numbers, quotes — stay very close to the text).
|
||||
3. Location: country/city/region or Unknown. If you can estimate coordinates, emit them as numbers; otherwise omit.
|
||||
4. Entities: list the key people, organizations, or governments mentioned (comma-separated, only names present in the text), else "None".
|
||||
5. Category: pick one — politics, military/conflict, economy, technology, environment/disaster, health, crime, society, sport, other.
|
||||
6. OSINT signal: if the article describes a breaking event with geopolitical, security, military, or disaster significance, say so in one short sentence. Otherwise write: "No notable OSINT signal."
|
||||
7. Importance: critical (breaking geopolitical/military/disaster with immediate impact), high, medium, low, none. Keep it consistent with the Score.
|
||||
|
||||
If several articles cover the same story, add one short batch-level note at the end: "Batch theme: [one sentence]".
|
||||
|
||||
Output format — strictly one block per article:
|
||||
Output format — strictly one block per article, Score and Importance first:
|
||||
|
||||
Article 1:
|
||||
- Score: <0-100>
|
||||
- Importance: critical|high|medium|low|none
|
||||
- Fact bullet 1
|
||||
- Fact bullet 2
|
||||
- Location: ...
|
||||
- Entities: ...
|
||||
- Category: ...
|
||||
- OSINT signal: ...
|
||||
- Importance: ...
|
||||
- Lat: ...
|
||||
- Lon: ...
|
||||
|
||||
|
|
@ -133,9 +167,11 @@ You are writing an English operator HUD brief from the article facts in DATA bel
|
|||
|
||||
Always write a real summary_en that recaps the most important stories present in DATA. Rank geopolitics, military/conflict, security, disasters, and major political developments first. Ignore futures prices, commodity tape, ticker chatter, and routine market data — do not treat price ticks as news.
|
||||
|
||||
Lead with critical and high breaking events. If DATA has no critical/high stories, fill the brief with minor incidents and crime reports rather than writing an empty or unfinished brief. Never truncate mid-sentence; finish every sentence. If you run out of room, drop the lowest-priority item instead of cutting a line short.
|
||||
DATA is pre-filtered by score and ordered best-first. Lead with the highest-scoring breaking stories and rank them honestly by importance — never promote an item above its score. Never truncate mid-sentence; finish every sentence. If you run out of room, drop the lowest-priority item instead of cutting a line short.
|
||||
|
||||
ticker: prefer critical and high. If nothing is critical or high, fill ticker with medium then low incidents and crime so the HUD is not blank.
|
||||
If DATA is empty, return exactly {"summary_en": "No significant developments in this window.", "ticker": [], "map_items": []}.
|
||||
|
||||
ticker: only stories present in DATA, highest score first.
|
||||
|
||||
map_items may be empty if no located critical/high event is explicit in the data.
|
||||
|
||||
|
|
@ -160,9 +196,11 @@ You are writing a daily recap of the last 24 hours of news for an OSINT operator
|
|||
|
||||
Always write a real summary_en daily recap of the most important stories in DATA. Rank geopolitics, military/conflict, security, disasters, and major political developments first. Ignore futures prices, commodity tape, ticker chatter, and routine market data — do not treat price ticks as news.
|
||||
|
||||
Lead with critical and high breaking events. If DATA has no critical/high stories, fill the recap with minor incidents and crime reports rather than writing an empty or unfinished recap. Never truncate mid-sentence; finish every sentence.
|
||||
DATA is pre-filtered by score and ordered best-first. Lead with the highest-scoring breaking stories of the day and rank them honestly by importance — never promote an item above its score. Never truncate mid-sentence; finish every sentence.
|
||||
|
||||
ticker: prefer critical and high. If nothing is critical or high, fill ticker with medium then low incidents and crime so the HUD is not blank.
|
||||
If DATA is empty, return exactly {"summary_en": "No significant developments in this window.", "ticker": [], "map_items": []}.
|
||||
|
||||
ticker: only stories present in DATA, highest score first.
|
||||
|
||||
Demand a single JSON object (no markdown fences) with this exact shape:
|
||||
|
||||
|
|
@ -326,6 +364,18 @@ def ensure_tables() -> None:
|
|||
CREATE INDEX IF NOT EXISTS ix_news_items_map_bbox
|
||||
ON news_items (lon, lat)
|
||||
WHERE kind = 'map' AND lat IS NOT NULL AND lon IS NOT NULL;
|
||||
CREATE TABLE IF NOT EXISTS article_scores (
|
||||
article_id INTEGER NOT NULL,
|
||||
summary_id INTEGER,
|
||||
score INTEGER NOT NULL,
|
||||
category TEXT,
|
||||
selected BOOLEAN NOT NULL,
|
||||
model TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
PRIMARY KEY (article_id, created_at)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_article_scores_summary
|
||||
ON article_scores (summary_id);
|
||||
"""
|
||||
try:
|
||||
conn = psycopg2.connect(**DB_CONFIG)
|
||||
|
|
@ -342,7 +392,7 @@ def get_recent_news(window_minutes: int | None = None) -> list[dict]:
|
|||
"""Fetch articles from the look-back window (content > 100 chars)."""
|
||||
mins = window_minutes if window_minutes is not None else effective_window_minutes()
|
||||
query = """
|
||||
SELECT title, content, url, domain
|
||||
SELECT id, title, content, url, domain
|
||||
FROM articles
|
||||
WHERE timestamp > NOW() - make_interval(mins => %s)
|
||||
AND content IS NOT NULL AND length(content) > 100
|
||||
|
|
@ -356,7 +406,7 @@ def get_recent_news(window_minutes: int | None = None) -> list[dict]:
|
|||
cur.close()
|
||||
conn.close()
|
||||
return [
|
||||
{"title": r[0], "content": r[1], "url": r[2], "domain": r[3]}
|
||||
{"id": r[0], "title": r[1], "content": r[2], "url": r[3], "domain": r[4]}
|
||||
for r in rows
|
||||
]
|
||||
except Exception as exc: # noqa: BLE001
|
||||
|
|
@ -412,14 +462,14 @@ def _already_recapped_today() -> bool:
|
|||
|
||||
def save_batch(
|
||||
summary_en: str, model: str, ticker: list, map_items: list, *, kind: str = "interval"
|
||||
) -> None:
|
||||
"""Insert the master brief plus flagged ticker/map rows."""
|
||||
) -> int | None:
|
||||
"""Insert the master brief plus flagged ticker/map rows. Returns the new summary id."""
|
||||
ticker_rows = select_ticker(ticker or [])
|
||||
map_rows = select_map(map_items or [])
|
||||
text = (summary_en or "").strip()
|
||||
if len(text) < 10 and not ticker_rows and not map_rows:
|
||||
logger.info("Summary too short or empty. Skipping save.")
|
||||
return
|
||||
return None
|
||||
insert_item = """
|
||||
INSERT INTO news_items (
|
||||
summary_id, kind, headline, importance, location_name,
|
||||
|
|
@ -473,8 +523,54 @@ def save_batch(
|
|||
)
|
||||
cur.close()
|
||||
conn.close()
|
||||
return summary_id
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.error("Error saving batch to DB: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def persist_article_scores(
|
||||
graded: list[dict], *, summary_id: int | None, model: str
|
||||
) -> None:
|
||||
"""Insert one article_scores row per graded article (selected true/false).
|
||||
|
||||
Best-effort: a failure here is logged and never aborts the run.
|
||||
"""
|
||||
rows = []
|
||||
for block in graded or []:
|
||||
article_id = block.get("article_id")
|
||||
if article_id is None:
|
||||
continue
|
||||
rows.append(
|
||||
(
|
||||
article_id,
|
||||
summary_id,
|
||||
int(block.get("score") or 0),
|
||||
block.get("category"),
|
||||
bool(block.get("selected")),
|
||||
model,
|
||||
)
|
||||
)
|
||||
if not rows:
|
||||
return
|
||||
try:
|
||||
conn = psycopg2.connect(**DB_CONFIG)
|
||||
cur = conn.cursor()
|
||||
cur.executemany(
|
||||
"INSERT INTO article_scores "
|
||||
"(article_id, summary_id, score, category, selected, model) "
|
||||
"VALUES (%s, %s, %s, %s, %s, %s)",
|
||||
rows,
|
||||
)
|
||||
conn.commit()
|
||||
cur.close()
|
||||
conn.close()
|
||||
logger.info(
|
||||
"article_scores persisted rows=%d selected=%d summary_id=%s",
|
||||
len(rows), sum(1 for r in rows if r[4]), summary_id,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.error("Error persisting article_scores (run continues): %s", exc)
|
||||
|
||||
|
||||
# ── Orchestration ──────────────────────────────────────────────────────────
|
||||
|
|
@ -533,34 +629,69 @@ def summarize_news() -> None:
|
|||
logger.info("No new articles found in the last %s min.", window)
|
||||
return
|
||||
|
||||
min_score, top_n, fallback_top = selection_config()
|
||||
logger.info(
|
||||
"Processing %d articles with %s (batch_size=%d, recap=%s, window_min=%s)...",
|
||||
"Processing %d articles with %s (batch_size=%d, recap=%s, window_min=%s, "
|
||||
"min_score=%d, top_n=%d, fallback_top=%d)...",
|
||||
len(articles), model, BATCH_SIZE, recap, window,
|
||||
min_score, top_n, fallback_top,
|
||||
)
|
||||
|
||||
partial_summaries: list[str] = []
|
||||
graded: list[dict] = []
|
||||
for i in range(0, len(articles), BATCH_SIZE):
|
||||
batch = articles[i : i + BATCH_SIZE]
|
||||
batch_index = i // BATCH_SIZE
|
||||
logger.info(
|
||||
"map batch %d/%d (%d articles)",
|
||||
i // BATCH_SIZE + 1, -(-len(articles) // BATCH_SIZE), len(batch),
|
||||
batch_index + 1, -(-len(articles) // BATCH_SIZE), len(batch),
|
||||
)
|
||||
summary = call_llm(
|
||||
response = call_llm(
|
||||
build_map_prompt(batch),
|
||||
api_key=api_key,
|
||||
model=model,
|
||||
base_url=base_url,
|
||||
json_mode=False,
|
||||
)
|
||||
if summary:
|
||||
partial_summaries.append(summary)
|
||||
if not response:
|
||||
continue
|
||||
blocks, stats = parse_map_scores(
|
||||
response, articles=articles, batch_index=batch_index, batch_size=BATCH_SIZE
|
||||
)
|
||||
logger.info(
|
||||
"map batch %d graded %d/%d (score fallback=%d, unattributed=%d)",
|
||||
batch_index + 1, stats["graded"], len(batch),
|
||||
stats["fallback"], stats["unattributed"],
|
||||
)
|
||||
graded.extend(blocks)
|
||||
|
||||
final_input = "\n\n".join(partial_summaries)
|
||||
if not final_input.strip():
|
||||
logger.warning("No partial summaries produced — nothing to reduce.")
|
||||
if not graded:
|
||||
logger.warning("No article blocks parsed from the map phase — nothing to reduce.")
|
||||
return
|
||||
|
||||
logger.info("reduce phase over %d partial summaries", len(partial_summaries))
|
||||
selected, used_fallback = select_graded(
|
||||
graded, min_score=min_score, top_n=top_n, fallback_top=fallback_top
|
||||
)
|
||||
selected_positions = {block["position"] for block in selected}
|
||||
for block in graded:
|
||||
block["selected"] = block["position"] in selected_positions
|
||||
if used_fallback:
|
||||
logger.warning(
|
||||
"No article cleared SUMMARY_MIN_SCORE=%d — fallback to top %d "
|
||||
"(max score %d)",
|
||||
min_score, len(selected), max(b["score"] for b in graded),
|
||||
)
|
||||
logger.info(
|
||||
"selected %d/%d graded articles for reduce (scores=%s)",
|
||||
len(selected), len(graded), [b["score"] for b in selected],
|
||||
)
|
||||
|
||||
final_input = join_blocks(selected)
|
||||
if not final_input.strip():
|
||||
logger.warning(
|
||||
"Selection is empty (min_score=%d, fallback_top=%d) — reduce gets empty DATA.",
|
||||
min_score, fallback_top,
|
||||
)
|
||||
|
||||
master_raw = call_llm(
|
||||
build_master_prompt(final_input, recap=recap),
|
||||
api_key=api_key,
|
||||
|
|
@ -572,13 +703,14 @@ def summarize_news() -> None:
|
|||
logger.warning("Reduce phase returned empty — nothing to persist.")
|
||||
return
|
||||
parsed = parse_reduce_json(master_raw)
|
||||
save_batch(
|
||||
summary_id = save_batch(
|
||||
parsed["summary_en"],
|
||||
model,
|
||||
parsed["ticker"],
|
||||
parsed["map_items"],
|
||||
kind="daily_recap" if recap else "interval",
|
||||
)
|
||||
persist_article_scores(graded, summary_id=summary_id, model=model)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
|||
Loading…
Reference in a new issue