knowledge: PR-3 skim notices to the loop + bounded lead promotion
PR-1 made the skim SEE (surfaces + signals); PR-2 made it HARVEST
deterministically. PR-3 closes the loop (KNOWLEDGE.md §7):
- Skim notices: every knowledge answer's stats carry what the fetched
articles contained beyond the answer (table identities, infobox
quantities, link candidates, goal-filtered). The engine copies them
into payload['skim']; the machine renders them to the ROUTER context
('seen in passing (E1): ...') and to the run notes — later steps know
what exists and where it lives instead of re-searching blind. A notice
is a pointer, never evidence: it answers nothing by itself.
- Bounded lead promotion (Emili's 'deterministic + LLM fallback'):
quantity tables that match NO goal word are queued as leads (PR-2);
now ONE dspy call (SkimPromoteSignature) decides over the tables'
IDENTITY lines (caption/headers/rows/quantities — never the rows),
per fetched page with leads, only when leads exist. The LLM proposes;
fixed code disposes: a promoted table still passes the entity-overlap
check (a world discharge table is refused for Po/Adige/Tiber), the
named column must exist, and ingestion goes through the same
containment-checked _ingest_scalar_table as the deterministic path.
- Refactor: row ingestion extracted to _ingest_scalar_table (shared by
harvest + promotion); _entity_overlap_count shared; skim state
(_skim_notices/_skim_leads/_current_goal_question) reset per call.
- find_quantities: fix plain-digit quantities ('1540 m3/s', '1000 m3/s')
— the thousands-separator-only regex missed them, and caption+header
now join with a space ('m3/sRiver' broke the unit boundary).
Live smoke (real Wikipedia, scripted decision): goal terms without
'flow' queue both Italy tables as leads; the promoted 'Flow at the
mouth' table ingests all 27 rivers (Po 1540, Adige 235, Tiber 239
m3/s) containment-checked; promotion of the length table with a
'Flow' column name is refused (column does not exist).
Tests: 4 new (knowledge/tests/promote.py); suite 43/43 green.
This commit is contained in:
+191
-70
@@ -25,9 +25,10 @@ from .checks import check_candidate, quote_containment
|
||||
from .chunker import chunk_page
|
||||
from .skim import find_quantities, skim_article
|
||||
from .extract import (AnswerFromKG, ExtractSignature, SelectTableSignature,
|
||||
TranslateSignature, VerifyCountSignature, parse_facts)
|
||||
SkimPromoteSignature, TranslateSignature,
|
||||
VerifyCountSignature, parse_facts)
|
||||
from .store import KnowledgeStore, norm_name
|
||||
from .wiki import WikipediaClient, WikiPage, resolve_convert
|
||||
from .wiki import WikipediaClient, WikiPage, WikiTable, resolve_convert
|
||||
|
||||
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
|
||||
|
||||
@@ -62,8 +63,15 @@ class KnowledgeExpert:
|
||||
self.translate = dspy.Predict(TranslateSignature)
|
||||
self.select_table = dspy.Predict(SelectTableSignature)
|
||||
self.verify_count = dspy.Predict(VerifyCountSignature)
|
||||
self.skim_promote = dspy.Predict(SkimPromoteSignature)
|
||||
self._checked = 0
|
||||
self._merged = 0
|
||||
# skim notices accumulated this CALL (PR-3): what the fetched
|
||||
# articles contained beyond the current question's answer
|
||||
self._skim_notices: list[str] = []
|
||||
# ambiguous leads (quantity tables with no goal-vocabulary match)
|
||||
# pending the bounded promotion decision
|
||||
self._skim_leads: list[tuple[WikiPage, WikiTable]] = []
|
||||
|
||||
# ---- helpers -----------------------------------------------------------
|
||||
def _log(self, text: str, think: bool = False) -> None:
|
||||
@@ -139,6 +147,11 @@ class KnowledgeExpert:
|
||||
kws = self._keywords(question)
|
||||
goal_terms = self._keywords(parent_question) if parent_question else []
|
||||
self._current_goal_terms = goal_terms # the harvest reads these
|
||||
self._current_goal_question = parent_question or question
|
||||
# per-CALL skim state (PR-3): notices for the machine + ambiguous
|
||||
# leads pending the bounded promotion decision
|
||||
self._skim_notices: list[str] = []
|
||||
self._skim_leads: list[tuple[WikiPage, object]] = []
|
||||
ev_entities = [e for e in self._expected_entities(evidence or "")][:8]
|
||||
# SEEN-INDEX (PR-2): articles already fetched this RUN — consulted
|
||||
# before network search so a later question pays zero re-fetch
|
||||
@@ -260,6 +273,16 @@ class KnowledgeExpert:
|
||||
self._log(f"skim {page.title}: {len(sheet.tables)} tables, "
|
||||
f"{len(sheet.infobox_quantities)} infobox quantities, "
|
||||
f"{len(sheet.link_candidates)} link candidates", think=True)
|
||||
# PR-3 — the skim notice: goal-relevant surfaces seen in passing,
|
||||
# so later steps (router context, run notes) know what exists
|
||||
# and where it lives. Filtered to goal signals: the notice is a
|
||||
# pointer, not a dump.
|
||||
notice = sheet.notice()
|
||||
if notice:
|
||||
goal_signal = (any(gt in notice.casefold() for gt in goal_terms)
|
||||
or any(find_quantities(notice)))
|
||||
if goal_signal or not goal_terms:
|
||||
self._skim_notices.append(notice)
|
||||
if self.cfg.skim_link_queue:
|
||||
for link in sheet.link_candidates:
|
||||
if link not in self._link_queue:
|
||||
@@ -267,6 +290,10 @@ class KnowledgeExpert:
|
||||
# PR-2 — the opportunistic harvest: goal-relevant side-tables
|
||||
# seen in passing become typed edges (zero LLM, containment law)
|
||||
self._harvest_side_tables(page, sheet, question, evidence)
|
||||
# PR-3 — bounded promotion of ambiguous leads (one LLM call,
|
||||
# only when leads exist): promoted tables ingest through the
|
||||
# same containment-checked path as the deterministic harvest
|
||||
self._promote_leads(evidence, charge_llm)
|
||||
# LIST path: one SELECT TABLE call per article; on hit, ingest ALL
|
||||
# rows and answer by aggregation (no extract calls, no gate)
|
||||
if list_mode and page.tables:
|
||||
@@ -275,7 +302,8 @@ class KnowledgeExpert:
|
||||
self._log(f"early exit after {page.title}: list "
|
||||
f"({ans['list_count']} items)", think=True)
|
||||
return {**ans, "source": "knowledge_graph",
|
||||
"stats": {"pages": [p.title for p in pages]}}
|
||||
"stats": {**self._skim_stats(pages),
|
||||
"skim": self._skim_notices}}
|
||||
# refused by the guard: wrong article's list — keep gathering
|
||||
# EARLY EXIT: one article at a time; if the KG already answers,
|
||||
# stop spending calls (the gather exists to fill the gap, not to
|
||||
@@ -288,7 +316,8 @@ class KnowledgeExpert:
|
||||
if hit is not None:
|
||||
self._log(f"early exit after {page.title}: set {hit}", think=True)
|
||||
return {**self._serve_set(hit, question), "source": "knowledge_graph",
|
||||
"stats": {"pages": [p.title for p in pages]}}
|
||||
"stats": {**self._skim_stats(pages),
|
||||
"skim": self._skim_notices}}
|
||||
else:
|
||||
answer = self._answer_from_rows(
|
||||
question, self.store.probe(probe_seeds), charge_llm)
|
||||
@@ -296,7 +325,8 @@ class KnowledgeExpert:
|
||||
self._log(f"early exit after {page.title}: "
|
||||
f"{answer['value'][:60]}", think=True)
|
||||
return {**answer, "source": "knowledge_graph",
|
||||
"stats": {"pages": [p.title for p in pages]}}
|
||||
"stats": {**self._skim_stats(pages),
|
||||
"skim": self._skim_notices}}
|
||||
|
||||
# 5-7. remaining pages already processed inline via _process_page
|
||||
# (early exit); fall through to the final re-probe and answer.
|
||||
@@ -307,10 +337,16 @@ class KnowledgeExpert:
|
||||
answer = self._answer_from_rows(question, rows, charge_llm)
|
||||
src = "knowledge_graph" if answer["value"].upper() != "UNKNOWN" else "wikipedia_miss"
|
||||
return {**answer, "source": src,
|
||||
"stats": {"checked": self._checked, "merged": self._merged,
|
||||
"pages": [p.title for p in pages],
|
||||
"stats": {**self._skim_stats(pages),
|
||||
"checked": self._checked, "merged": self._merged,
|
||||
"skim": self._skim_notices,
|
||||
"elapsed_s": round(time.time() - t0, 1)}}
|
||||
|
||||
def _skim_stats(self, pages: list[WikiPage]) -> dict:
|
||||
"""stats shared by every return path: pages seen + link queue state."""
|
||||
return {"pages": [p.title for p in pages],
|
||||
"link_queue": len(self._link_queue)}
|
||||
|
||||
def _expected_entities(self, evidence: str) -> list[str]:
|
||||
"""Entities the parent's evidence already names — 'the three longest
|
||||
rivers' means the answer's members must be among them. Extracted
|
||||
@@ -498,33 +534,77 @@ class KnowledgeExpert:
|
||||
"coverage": coverage,
|
||||
}
|
||||
|
||||
def _ingest_scalar_table(self, page: WikiPage, t, ent_i: int,
|
||||
val_i: int) -> int:
|
||||
"""Shared row ingestion for the skim paths (harvest + promote):
|
||||
every row becomes a scalar edge — subject = entity cell, relation =
|
||||
value-column header, object = value + UNIT (the unit lives in the
|
||||
caption), quote = the verbatim stored row line, containment against
|
||||
the stored table text. Zero LLM; the verbatim law is kept."""
|
||||
cap_q = find_quantities(resolve_convert(t.caption or ""))
|
||||
unit = cap_q[0].split(" ", 1)[1] if cap_q else ""
|
||||
doc_id = self.store.add_document(
|
||||
url=page.url, title=page.title, fetched_at=page.fetched_at,
|
||||
sha256=hashlib.sha256(page.text.encode()).hexdigest())
|
||||
table_text = chr(10).join(t.text_lines())
|
||||
rel = t.header[val_i] if val_i < len(t.header) else "value"
|
||||
merged = 0
|
||||
for row in t.rows:
|
||||
subj = (row[ent_i] if ent_i < len(row) else "").strip()
|
||||
obj = (row[val_i] if val_i < len(row) else "").strip()
|
||||
if not subj or not obj or subj.casefold() in (
|
||||
"total", "totals", "sum", "average", "mean") or subj.isdigit():
|
||||
continue
|
||||
if " / " in subj:
|
||||
subj = subj.split(" / ")[0].strip()
|
||||
if unit and re.fullmatch(r"[\d,.]+", obj):
|
||||
obj = f"{obj} {unit}" # quantities carry values AND units
|
||||
row_line = " | ".join(row)
|
||||
ok, reason = check_candidate(
|
||||
{"subject": subj, "relation": rel, "object": obj,
|
||||
"quote": row_line}, table_text)
|
||||
if not ok:
|
||||
self._log(f"harvest row rejected ({reason}): {subj[:40]}")
|
||||
continue
|
||||
qid = self.store.add_quote(doc_id, row_line, page.url,
|
||||
page.fetched_at)
|
||||
self.store.add_edge(subj, rel, obj, qid)
|
||||
self._merged += 1
|
||||
merged += 1
|
||||
if merged:
|
||||
self._log(f"skim ingest: {merged} rows of table {t.idx} "
|
||||
f"({page.title}) as '{rel}' edges", think=True)
|
||||
return merged
|
||||
|
||||
def _entity_overlap_count(self, t, ent_i: int, expected: list[str]) -> \
|
||||
tuple[int, int]:
|
||||
"""(overlap, members) — how many of the table's entity-column members
|
||||
the parent's evidence names, and how many members there are."""
|
||||
members = [(r[ent_i] if ent_i < len(r) else "").strip() for r in t.rows]
|
||||
members = [m.split(" / ")[0].strip() for m in members if m]
|
||||
if not expected:
|
||||
return 0, len(members)
|
||||
en = {norm_name(e) for e in expected}
|
||||
return sum(1 for m in members if norm_name(m) in en), len(members)
|
||||
|
||||
def _harvest_side_tables(self, page: WikiPage, sheet, question: str,
|
||||
evidence: str) -> int:
|
||||
"""PR-2 — the opportunistic harvest: goal-relevant tables seen in
|
||||
passing are ingested as typed rows, zero LLM (KNOWLEDGE.md §7).
|
||||
|
||||
A table is harvested when its caption/header carries a GOAL term or
|
||||
quantity-unit signal AND its entity column overlaps the entities the
|
||||
parent's evidence names (the disjointness guard inverted: overlap =
|
||||
about our entities) — the Italy case: table 2 'Flow at the mouth'
|
||||
while the question asked for lengths. Rows become scalar edges:
|
||||
subject = entity-column cell, relation = value-column header,
|
||||
object = value cell (units survive via _clean_cell), quote = the
|
||||
full stored row line, containment against the stored table text.
|
||||
Deterministic detection; ambiguous tables are SKIPPED (recorded in
|
||||
the run log), never guessed — the LLM fallback is PR-3's bounded
|
||||
call, not this path."""
|
||||
A table is harvested when its caption/header carries a GOAL term AND
|
||||
its entity column overlaps the entities the parent's evidence names
|
||||
(the disjointness guard inverted: overlap = about our entities) —
|
||||
the Italy case: table 2 'Flow at the mouth' while the question asked
|
||||
for lengths. Rows become scalar edges via _ingest_scalar_table
|
||||
(verbatim quote, containment, unit from the caption). Deterministic
|
||||
detection; quantity tables with no goal-vocabulary match are queued
|
||||
as leads for PR-3's bounded promotion, never guessed here."""
|
||||
if not self.cfg.skim_harvest:
|
||||
return 0
|
||||
expected = self._expected_entities(evidence or "")
|
||||
goal_terms = self._current_goal_terms or []
|
||||
|
||||
def ent_overlap(members: list[str]) -> int:
|
||||
if not expected:
|
||||
return 0
|
||||
en = {norm_name(e) for e in expected}
|
||||
return sum(1 for m in members if norm_name(m) in en)
|
||||
|
||||
harvested = 0
|
||||
for t in page.tables:
|
||||
if harvested >= self.cfg.skim_harvest_max_tables:
|
||||
@@ -535,16 +615,17 @@ class KnowledgeExpert:
|
||||
or gt in " ".join(t.header).casefold())
|
||||
for gt in goal_terms)
|
||||
qty_signal = bool(find_quantities(
|
||||
resolve_convert(t.caption or "") + " ".join(t.header[:1])))
|
||||
resolve_convert(t.caption or "") + " " + " ".join(t.header[:1])))
|
||||
if not goal_hit:
|
||||
if qty_signal:
|
||||
# a quantity table we cannot tie to the goal vocabulary:
|
||||
# RECORDED as a lead, never ingested on the unit pattern
|
||||
# alone — the bounded LLM promotion is PR-3's call, and
|
||||
# the seen-index lets a later question come back for it
|
||||
# RECORDED as a lead for the bounded promotion (PR-3),
|
||||
# never ingested on the unit pattern alone — and the
|
||||
# seen-index lets a later question come back for it
|
||||
self._skim_leads.append((page, t))
|
||||
self._log(f"skim harvest: table {t.idx} of {page.title}: "
|
||||
f"quantity signal without a goal term — recorded "
|
||||
f"as lead, not ingested", think=True)
|
||||
f"quantity signal without a goal term — queued "
|
||||
f"as lead", think=True)
|
||||
continue
|
||||
# entity column: first column whose header is a name-like column
|
||||
# (River, Country, Name, ...) or column 0; value column: the
|
||||
@@ -567,54 +648,94 @@ class KnowledgeExpert:
|
||||
self._log(f"skim harvest: table {t.idx} of {page.title}: no "
|
||||
f"value column — recorded, not ingested", think=True)
|
||||
continue
|
||||
members = [(r[ent_i] if ent_i < len(r) else "").strip() for r in t.rows]
|
||||
members = [m.split(" / ")[0].strip() for m in members if m]
|
||||
overlap = ent_overlap(members) if expected else 0
|
||||
if expected and overlap == 0 and len(members) >= 2:
|
||||
overlap, nm = self._entity_overlap_count(t, ent_i, expected)
|
||||
if expected and overlap == 0 and nm >= 2:
|
||||
# not about our entities — a world table is not our answer
|
||||
self._log(f"skim harvest: table {t.idx} of {page.title}: "
|
||||
f"{overlap}/{len(members)} entity overlap — skipped",
|
||||
f"{overlap}/{nm} entity overlap — skipped",
|
||||
think=True)
|
||||
continue
|
||||
# ingest rows as scalar edges (verbatim law kept). The unit lives
|
||||
# in the caption ('above 50 m3/s'), not in the cells — attach it
|
||||
# to the VALUE (the typed fact); the quote stays the verbatim row
|
||||
cap_q = find_quantities(resolve_convert(t.caption or ""))
|
||||
unit = cap_q[0].split(" ", 1)[1] if cap_q else ""
|
||||
doc_id = self.store.add_document(
|
||||
url=page.url, title=page.title, fetched_at=page.fetched_at,
|
||||
sha256=hashlib.sha256(page.text.encode()).hexdigest())
|
||||
table_text = chr(10).join(t.text_lines())
|
||||
rel = t.header[val_i] if val_i < len(t.header) else "value"
|
||||
merged = 0
|
||||
for row in t.rows:
|
||||
subj = (row[ent_i] if ent_i < len(row) else "").strip()
|
||||
obj = (row[val_i] if val_i < len(row) else "").strip()
|
||||
if not subj or not obj or subj.casefold() in (
|
||||
"total", "totals", "sum", "average", "mean") or subj.isdigit():
|
||||
continue
|
||||
if " / " in subj:
|
||||
subj = subj.split(" / ")[0].strip()
|
||||
if unit and re.fullmatch(r"[\d,.]+", obj):
|
||||
obj = f"{obj} {unit}" # quantities carry values AND units
|
||||
row_line = " | ".join(row)
|
||||
ok, reason = check_candidate(
|
||||
{"subject": subj, "relation": rel, "object": obj,
|
||||
"quote": row_line}, table_text)
|
||||
if not ok:
|
||||
self._log(f"harvest row rejected ({reason}): {subj[:40]}")
|
||||
continue
|
||||
qid = self.store.add_quote(doc_id, row_line, page.url,
|
||||
page.fetched_at)
|
||||
self.store.add_edge(subj, rel, obj, qid)
|
||||
self._merged += 1
|
||||
merged += 1
|
||||
merged = self._ingest_scalar_table(page, t, ent_i, val_i)
|
||||
if merged:
|
||||
self._log(f"skim harvest: {merged} rows of table {t.idx} "
|
||||
f"({page.title}) ingested as '{rel}' edges", think=True)
|
||||
harvested += 1
|
||||
return harvested
|
||||
|
||||
def _promote_leads(self, evidence: str, charge_llm) -> int:
|
||||
"""PR-3 — the bounded promotion of ambiguous leads: quantity tables
|
||||
with no goal-vocabulary match, decided by ONE LLM call per fetched
|
||||
page that has leads (≤ max_articles per knowledge call, only when
|
||||
leads exist — most pages have none). The call sees the tables'
|
||||
IDENTITY (caption/headers/row count/quantity signals — never the
|
||||
rows). The law split stands: the LLM proposes (which table is about
|
||||
the goal), fixed code disposes — a promoted table still passes the
|
||||
entity-overlap check and ingests through the same containment-checked
|
||||
path as the deterministic harvest. Runs inside the fetch loop, BEFORE
|
||||
the early-exit checks: leads die with the call otherwise (a later
|
||||
question only re-harvests pages its own search surfaces again)."""
|
||||
if not self._skim_leads:
|
||||
return 0
|
||||
if not self.cfg.skim_harvest:
|
||||
self._skim_leads = []
|
||||
return 0
|
||||
expected = self._expected_entities(evidence or "")
|
||||
# group by page; each lead gets a GLOBAL line id (two pages can both
|
||||
# have a 'table 1' — the idx alone would collide in the lookup)
|
||||
leads: list[tuple[WikiPage, object]] = self._skim_leads
|
||||
rendered = []
|
||||
lookup: dict[int, tuple[WikiPage, object]] = {}
|
||||
for lid, (page, t) in enumerate(leads, start=1):
|
||||
cap = resolve_convert(t.caption or "") or "(no caption)"
|
||||
qtys = find_quantities("\n".join(t.text_lines()))[:3]
|
||||
rendered.append(
|
||||
f"{lid} | {cap} | header: {', '.join(t.header[:6])} | "
|
||||
f"rows: {t.total_rows} | quantities: {', '.join(qtys) or 'none'}")
|
||||
lookup[lid] = (page, t)
|
||||
if not rendered:
|
||||
return 0
|
||||
if charge_llm:
|
||||
charge_llm()
|
||||
pred = self.skim_promote(
|
||||
goal=self._current_goal_question,
|
||||
entities=", ".join(expected[:8]),
|
||||
tables="\n".join(rendered))
|
||||
promoted = 0
|
||||
for line in (pred.decision or "").strip().splitlines():
|
||||
m = re.match(r"\s*(\d+)\s*:\s*(YES|NO)\s*(.*)$", line.strip(),
|
||||
flags=re.I)
|
||||
if not m:
|
||||
continue
|
||||
idx, verdict, col = int(m.group(1)), m.group(2).upper(), m.group(3).strip()
|
||||
got = lookup.get(idx)
|
||||
if verdict != "YES" or got is None:
|
||||
continue
|
||||
page, t = got
|
||||
ent_i = next((i for i, h in enumerate(t.header)
|
||||
if h.casefold() in ("river", "country", "name", "state",
|
||||
"city", "entity", "member")),
|
||||
0)
|
||||
val_i = next((i for i, h in enumerate(t.header)
|
||||
if col and col.casefold() in h.casefold()), None)
|
||||
if val_i is None:
|
||||
val_i = next((i for i, h in enumerate(t.header)
|
||||
if i != ent_i and (find_quantities(h)
|
||||
or "flow" in h.casefold()
|
||||
or "discharge" in h.casefold())), None)
|
||||
if val_i is None:
|
||||
continue
|
||||
overlap, nm = self._entity_overlap_count(t, ent_i, expected)
|
||||
if expected and overlap == 0 and nm >= 2:
|
||||
self._log(f"skim promote: table {idx} ({page.title}): LLM said "
|
||||
f"YES but {overlap}/{nm} entity overlap — refused",
|
||||
think=True)
|
||||
continue
|
||||
merged = self._ingest_scalar_table(page, t, ent_i, val_i)
|
||||
if merged:
|
||||
self._log(f"skim promote: {merged} rows of table {idx} "
|
||||
f"({page.title}) ingested (LLM-proposed)", think=True)
|
||||
promoted += 1
|
||||
self._skim_leads = [] # consumed: bounded, never re-asked
|
||||
return promoted
|
||||
|
||||
def _process_page(self, page: WikiPage, question: str, kws: list[str],
|
||||
charge_llm, goal_terms: list[str] | None = None) -> int:
|
||||
"""Chunk -> gate -> RANK (skim) -> extract -> check -> merge for ONE
|
||||
|
||||
Reference in New Issue
Block a user