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.
807 lines
42 KiB
Python
807 lines
42 KiB
Python
"""The knowledge expert pipeline: KG-first, gather on gap, containment-checked.
|
|
|
|
Per question (one routed knowledge call):
|
|
1. TRANSLATE: question -> retrieval focus (keywords/entities) [LLM, cheap]
|
|
2. KG PROBE: lexical seed match + BFS depth-1 [engine]
|
|
3. gap? -> SEARCH en.wikipedia (official search) [engine]
|
|
4. FETCH top articles, CHUNK by sections [engine]
|
|
5. EXTRACT per chunk (map) with verbatim spans [LLM]
|
|
6. CHECK: containment in FULL text + well-formedness [engine]
|
|
7. MERGE into the store: corroboration / conflicts / supersession [engine]
|
|
8. ANSWER from KG rows (select + one LLM answer call) [LLM]
|
|
|
|
Laws: no quote, no edge; no edge, no answer. Every step logged via RunStreams.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import re
|
|
import time
|
|
from dataclasses import dataclass
|
|
|
|
import dspy
|
|
|
|
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,
|
|
SkimPromoteSignature, TranslateSignature,
|
|
VerifyCountSignature, parse_facts)
|
|
from .store import KnowledgeStore, norm_name
|
|
from .wiki import WikipediaClient, WikiPage, WikiTable, resolve_convert
|
|
|
|
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
|
|
|
|
|
|
@dataclass
|
|
class KnowledgeConfig:
|
|
kb_path: str = "knowledge_store/kg.sqlite"
|
|
max_articles: int = 3 # per knowledge call
|
|
max_search_results: int = 4 # candidates considered
|
|
max_chunks_extracted: int = 6 # per call (lexical gate decides which)
|
|
max_extract_retries: int = 2
|
|
chunk_chars_target: int = 32000
|
|
chunk_chars_cap: int = 48000
|
|
# skim harvest (PR-2): goal-relevant side-tables are ingested in passing
|
|
skim_harvest: bool = True # opportunistic typed ingestion, zero LLM
|
|
skim_harvest_max_tables: int = 2 # per article, beyond the LIST answer
|
|
skim_link_queue: bool = True # goal-region links join the fetch order
|
|
|
|
|
|
class KnowledgeExpert:
|
|
"""The machine's knowledge attendant — replaces stub:knowledge when wired."""
|
|
|
|
def __init__(self, config: KnowledgeConfig | None = None,
|
|
store: KnowledgeStore | None = None,
|
|
client: WikipediaClient | None = None, streams=None):
|
|
self.cfg = config or KnowledgeConfig()
|
|
self.store = store or KnowledgeStore(self.cfg.kb_path)
|
|
self.client = client or WikipediaClient()
|
|
self.streams = streams
|
|
self.extract = dspy.Predict(ExtractSignature)
|
|
self.answer = dspy.Predict(AnswerFromKG)
|
|
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:
|
|
if self.streams:
|
|
self.streams.state(text, think=think)
|
|
|
|
@staticmethod
|
|
def _keywords(question: str, k: int = 6) -> list[str]:
|
|
"""Deterministic lexical focus: content words of the question (draft)."""
|
|
stops = {"what", "which", "who", "when", "where", "is", "are", "was", "were",
|
|
"the", "of", "in", "on", "at", "a", "an", "and", "or", "to", "for",
|
|
"does", "do", "did", "by", "its", "it", "that", "this", "most", "second"}
|
|
words = [w.lower() for w in WORD_RE.findall(question)]
|
|
seen: list[str] = []
|
|
for w in words:
|
|
if w not in stops and len(w) > 2 and w not in seen:
|
|
seen.append(w)
|
|
return seen[:k]
|
|
|
|
def _set_gate_hit(self, probe_seeds: list[str], question: str) -> str | None:
|
|
"""The membership set (if any) this question may be served from.
|
|
|
|
Mention rows never answer enumerations — only a set does. And a set
|
|
belongs to ITS question: serving Q1's 'countries in Europe' set to
|
|
'which are EU members?' would be a confident wrong answer. The match
|
|
is stem-Jaccard >= 0.5 between the incoming question and the set's
|
|
ORIGIN question — near-repeats are served, different questions gather."""
|
|
from .store import stem
|
|
q_stems = {stem(w) for w in WORD_RE.findall(question.casefold())
|
|
if len(w) > 2}
|
|
for set_name, origin in self.store.set_origins():
|
|
o_stems = {stem(w) for w in WORD_RE.findall(origin.casefold())
|
|
if len(w) > 2}
|
|
if not q_stems or not o_stems:
|
|
continue
|
|
jac = len(q_stems & o_stems) / len(q_stems | o_stems)
|
|
if jac >= 0.5 and self.store.list_members(set_name):
|
|
return set_name
|
|
return None
|
|
|
|
def _serve_set(self, set_name: str, question: str) -> dict:
|
|
"""Answer an enumeration from a held membership set: the full member
|
|
list with provenance, coverage complete per source. Table order is
|
|
preserved when the ingest recorded ordinals (ranked tables rank)."""
|
|
ordered = self.store.list_is_ordered(set_name)
|
|
members = self.store.list_members(set_name, ordered=ordered)
|
|
quote, url = self.store.set_provenance(set_name)
|
|
self._log(f"kg set hit: {set_name} ({len(members)} members"
|
|
f"{', ranked' if ordered else ', unordered'})", think=True)
|
|
return {"value": str(len(members)), "list_items": members,
|
|
"list_count": len(members), "quote": quote, "url": url,
|
|
"confidence": "high",
|
|
"coverage": {"source": "knowledge_graph", "set": set_name,
|
|
"rows_ingested": len(members),
|
|
"rows_total": len(members),
|
|
"complete_per_source": True,
|
|
"ranked": ordered}}
|
|
|
|
# ---- the pipeline --------------------------------------------------------
|
|
def answer_question(self, question: str, parent_question: str = "",
|
|
evidence: str = "", charge_llm=None,
|
|
answer_type: str = "") -> dict:
|
|
"""Returns the answer dict {value, quote, url, source, confidence}.
|
|
|
|
`parent_question` + `evidence` are the machine's context: the original
|
|
goal and the rows this question depends on (design §4: instantiated
|
|
question + parent + referenced rows in). References like 'that state'
|
|
resolve against them."""
|
|
t0 = time.time()
|
|
context = (f"Original question: {parent_question}" if parent_question else "")
|
|
if evidence:
|
|
context += (chr(10) * 2 if context else "") + f"Evidence:\n{evidence}"
|
|
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
|
|
if not hasattr(self, "_seen_pages"):
|
|
self._seen_pages: dict[str, WikiPage] = {}
|
|
# LINK QUEUE (PR-2): goal-region links from skims, joining the fetch
|
|
# order as candidates (hops still live in the plan — the law stands)
|
|
if not hasattr(self, "_link_queue"):
|
|
self._link_queue: list[str] = []
|
|
# LIST activation (moved up: the set gate needs it before the probe)
|
|
list_mode = (str(answer_type or "").upper() == "LIST"
|
|
or self._is_enumeration(question))
|
|
self._log(f"knowledge: question={question[:80]!r} keywords={kws}", think=True)
|
|
|
|
# 2. KG probe first: question keywords + entities from the machine's
|
|
# context (evidence rows) — 'that state' probes as 'france'
|
|
probe_seeds = list(kws)
|
|
for line in (evidence or "").splitlines():
|
|
if ":" in line:
|
|
val = line.split(":", 1)[1].split("(answers")[0].strip()
|
|
if val and len(val.split()) <= 4:
|
|
probe_seeds.extend(val.split())
|
|
rows = self.store.probe(probe_seeds)
|
|
self._log(f"kg probe ({probe_seeds}): {len(rows)} rows", think=True)
|
|
# SET GATE (lists): mention rows never answer an enumeration — only a
|
|
# membership set does. With no set held, the probe result is not
|
|
# answerability evidence; the gather must run.
|
|
if list_mode:
|
|
kg_set = self._set_gate_hit(probe_seeds, question)
|
|
if kg_set:
|
|
return {**self._serve_set(kg_set, question),
|
|
"source": "knowledge_graph", "kg_rows": len(rows)}
|
|
self._log(f"set gate: {len(rows)} mention rows are not answerability "
|
|
f"for an enumeration; gather runs", think=True)
|
|
else:
|
|
answer = self._answer_from_rows(question, rows, charge_llm)
|
|
if answer["value"] and answer["value"].upper() != "UNKNOWN":
|
|
self._log(f"kg hit: {answer['value'][:60]}", think=True)
|
|
return {**answer, "source": "knowledge_graph", "kg_rows": len(rows)}
|
|
|
|
# 3-4. gap -> search + fetch. TRANSLATE (LLM) first: the question becomes
|
|
# entity-first Wikipedia queries — deterministic keywords alone surface
|
|
# list articles and miss demographics pages.
|
|
if charge_llm:
|
|
charge_llm()
|
|
pred = self.translate(question=question, context=context)
|
|
q_raw = (pred.queries or "").strip()
|
|
queries = [q.strip() for q in
|
|
next((ln.split(":", 1)[1] for ln in q_raw.splitlines()
|
|
if ln.strip().upper().startswith("QUERIES")), q_raw).split(",")
|
|
if q.strip()][:2]
|
|
if not queries:
|
|
queries = [" ".join(kws[:3])]
|
|
e_raw = (pred.entities or "").strip()
|
|
entity_terms = [t.strip() for t in
|
|
next((ln.split(":", 1)[1] for ln in e_raw.splitlines()
|
|
if ln.strip().upper().startswith("ENTITIES")), e_raw).split(",")
|
|
if t.strip()][:4]
|
|
self._log(f"translate -> queries {queries} entities {entity_terms}", think=True)
|
|
|
|
# search ALL queries first; merge + dedupe candidates; rank GLOBALLY
|
|
# by title relevance; then fetch one at a time with early exit
|
|
# (per-query quotas let generic articles eat the slots before the
|
|
# decisive article from a later query is even considered)
|
|
from .store import norm_name, stem
|
|
title_terms = {t for w in entity_terms + kws if len(w) > 2
|
|
for t in (norm_name(w), stem(w))}
|
|
|
|
def relevance(title: str) -> int:
|
|
tt = norm_name(title)
|
|
return sum(1 for t in title_terms if t and t in tt)
|
|
|
|
candidates: list[str] = []
|
|
seen_titles: set[str] = set()
|
|
per_query: list[list[str]] = []
|
|
for query in queries:
|
|
found = self.client.search(query, limit=self.cfg.max_search_results)
|
|
per_query.append(found)
|
|
self._log(f"wiki search ({query!r}): {found}", think=True)
|
|
for title in found:
|
|
if title not in seen_titles:
|
|
seen_titles.add(title)
|
|
candidates.append(title)
|
|
# hybrid order: each query's #1 is guaranteed a slot (the engine's own
|
|
# relevance catches entity pages whose title shares no words with the
|
|
# question — e.g. 'Loire' for 'longest river in France'); the rest are
|
|
# ranked by title relevance (which pulls list articles up when they
|
|
# are the right source)
|
|
ordered: list[str] = []
|
|
picked: set[str] = set()
|
|
for found in per_query:
|
|
if found and found[0] not in picked:
|
|
picked.add(found[0])
|
|
ordered.append(found[0])
|
|
for title in sorted((t for t in candidates if t not in picked),
|
|
key=relevance, reverse=True):
|
|
ordered.append(title)
|
|
self._log(f"fetch order: {ordered[: self.cfg.max_articles]}", think=True)
|
|
|
|
pages: list[WikiPage] = []
|
|
for title in ordered[: self.cfg.max_articles]:
|
|
if title in self._seen_pages:
|
|
page = self._seen_pages[title]
|
|
self._log(f"seen-index hit: {title} (already fetched this run)",
|
|
think=True)
|
|
else:
|
|
try:
|
|
page = self.client.fetch_rich(title)
|
|
except Exception as e: # noqa: BLE001 — network honesty: log and continue
|
|
self._log(f"fetch failed: {title}: {e}")
|
|
continue
|
|
self._seen_pages[title] = page
|
|
pages.append(page)
|
|
# SKIM (PR-1): the structural read, in passing — question AND goal
|
|
# oriented; surfaces + signals, zero LLM. The sheet drives chunk
|
|
# ranking in _process_page; PR-2's harvest runs on its signals.
|
|
sheet = skim_article(page, question_terms=kws, goal_terms=goal_terms,
|
|
evidence_entities=ev_entities)
|
|
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:
|
|
self._link_queue.append(link)
|
|
# 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:
|
|
ans = self._list_from_page(page, question, charge_llm)
|
|
if ans is not None and self._guard_ingest(ans, evidence):
|
|
self._log(f"early exit after {page.title}: list "
|
|
f"({ans['list_count']} items)", think=True)
|
|
return {**ans, "source": "knowledge_graph",
|
|
"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
|
|
# hoover every candidate). For enumerations the set gate applies
|
|
# here too: mention rows never answer a list question.
|
|
self._process_page(page, question, kws, charge_llm,
|
|
goal_terms=goal_terms)
|
|
if list_mode:
|
|
hit = self._set_gate_hit(probe_seeds, question)
|
|
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": {**self._skim_stats(pages),
|
|
"skim": self._skim_notices}}
|
|
else:
|
|
answer = self._answer_from_rows(
|
|
question, self.store.probe(probe_seeds), charge_llm)
|
|
if answer["value"] and answer["value"].upper() != "UNKNOWN":
|
|
self._log(f"early exit after {page.title}: "
|
|
f"{answer['value'][:60]}", think=True)
|
|
return {**answer, "source": "knowledge_graph",
|
|
"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.
|
|
|
|
# 8. re-probe (same seeds) and answer from the merged KG
|
|
rows = self.store.probe(probe_seeds)
|
|
self._log(f"merged {self._merged}/{self._checked} candidates; re-probe: {len(rows)} rows", think=True)
|
|
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": {**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
|
|
deterministically from the rendered evidence lines (E1: value (answers
|
|
Qx)), from LIST rows' list_items and scalar rows' values. No LLM."""
|
|
out: list[str] = []
|
|
for line in (evidence or "").splitlines():
|
|
if "(answers" not in line:
|
|
continue
|
|
val = line.split(":", 1)[1].split("(answers")[0].strip()
|
|
if not val:
|
|
continue
|
|
# LIST rows render 'list of N items: a, b, c...' — members are known
|
|
m = re.match(r"list of \d+ items: (.+)$", val)
|
|
if m:
|
|
out.extend(t.strip() for t in m.group(1).rstrip(".").split(","))
|
|
continue
|
|
# scalar: a single named entity (Po) or a short comma list (Po, Adige, Tiber)
|
|
if len(val.split()) <= 6 and not val.isdigit():
|
|
out.extend(t.strip() for t in val.split(",") if t.strip())
|
|
return [e for e in out if e]
|
|
|
|
def _disjoint(self, members: list[str], expected: list[str]) -> bool:
|
|
"""Deterministic overlap check, case-insensitive by prefix-normalized
|
|
tokens. Disjoint (or near-disjoint) ingest is WRONG for a question
|
|
about known entities — keep gathering, don't answer from it."""
|
|
if not expected or not members:
|
|
return False
|
|
en = {norm_name(e) for e in expected}
|
|
mn = {norm_name(m) for m in members}
|
|
inter = en & mn
|
|
# no expected entity appears, or < 1/3 do: wrong article's list
|
|
return len(inter) * 3 < len(mn) or not inter
|
|
|
|
def _guard_ingest(self, ans: dict, evidence: str) -> bool:
|
|
"""The disjointness guard: refuse a LIST ingest whose members don't
|
|
overlap the entities the parent's evidence already names. 'Cabal de
|
|
Po, Adige, Tiber' must never be answered by the Amazon's flow."""
|
|
if not (evidence and ans.get("list_items")):
|
|
return True # nothing to check against — ingest is fine
|
|
expected = self._expected_entities(evidence)
|
|
if not expected:
|
|
return True
|
|
if self._disjoint(ans["list_items"], expected):
|
|
self._log(
|
|
f"guard: ingest of {len(ans['list_items'])} members disjoint from "
|
|
f"{len(expected)} expected entities — refusing, gather continues",
|
|
think=True)
|
|
return False
|
|
return True
|
|
|
|
def _is_enumeration(self, question: str) -> bool:
|
|
"""Deterministic LIST detection: plural nouns + enumeration ask words.
|
|
Cheap, logged, and overridable by the planner's explicit answer_type."""
|
|
q = question.casefold()
|
|
words = set(WORD_RE.findall(q))
|
|
ask = {"which", "what", "list", "name", "enumerate", "identify"}
|
|
plurals = [w for w in words if w.endswith("s") and len(w) > 4
|
|
and w not in ("states?", "does", "was", "has")]
|
|
return bool(words & ask) and len(plurals) >= 1
|
|
|
|
def _verify_count(self, set_name: str, count: int, prose: str,
|
|
charge_llm) -> dict | None:
|
|
"""Answer-level CHECK: corroborate the list COUNT from article prose
|
|
that is NOT the source table.
|
|
|
|
Law split: the LLM finds language (one verbatim sentence stating the
|
|
count); fixed code decides validity — the sentence must be contained
|
|
in the prose AND state the same count as `count` digits. No LLM ever
|
|
compares numbers. Returns a verification record or None (no
|
|
corroborating sentence found — honest, not an error)."""
|
|
if not prose or count <= 0:
|
|
return None
|
|
if charge_llm:
|
|
charge_llm()
|
|
pred = self.verify_count(set_name=set_name, count=str(count),
|
|
text=prose[: self.cfg.chunk_chars_cap])
|
|
q = (pred.quote or "").strip()
|
|
if not q or q.upper() in ("NOQUOTE", "NONE", "N/A"):
|
|
return None
|
|
if not quote_containment(q, prose):
|
|
self._log(f"verify: quote not contained in prose — rejected")
|
|
return None
|
|
# deterministic number comparison: the digits the sentence states
|
|
# must equal the count we computed from the rows
|
|
nums = {int(n.replace(",", "")) for n in re.findall(r"[\d,]{1,7}", q)
|
|
if n.replace(",", "").isdigit()}
|
|
if count in nums:
|
|
return {"count_corroborated": True, "quote": q}
|
|
self._log(f"verify: corroborating sentence states {nums}, not {count} "
|
|
f"— numbers disagree")
|
|
return None
|
|
|
|
def _list_from_page(self, page: WikiPage, question: str, charge_llm) -> dict | None:
|
|
"""The LIST path: SELECT TABLE (LLM picks table+column from metadata,
|
|
never the rows) -> ingest ALL rows as membership edges -> aggregate.
|
|
|
|
Returns the list answer dict, or None when no table in this page
|
|
enumerates the answer (fall through to the extract path)."""
|
|
rendered = chr(10).join(
|
|
f"{t.idx} | {t.caption or '(no caption)'} | "
|
|
f"header: {', '.join(t.header[:6]) or '(none)'} | rows: {t.total_rows}"
|
|
for t in page.tables)
|
|
if charge_llm:
|
|
charge_llm()
|
|
pred = self.select_table(question=question, tables=rendered)
|
|
idx_raw = (pred.table_index or "").strip()
|
|
if not idx_raw or idx_raw.upper() in ("NONE", "N/A", "0"):
|
|
return None
|
|
try:
|
|
idx = int(re.findall(r"\d+", idx_raw)[0])
|
|
except (ValueError, IndexError):
|
|
return None
|
|
table = next((t for t in page.tables if t.idx == idx), None)
|
|
if table is None:
|
|
return None
|
|
page._list_table_idx = idx # the harvest skips the LIST answer's table
|
|
column = (pred.column or "").strip()
|
|
col_i = next((i for i, h in enumerate(table.header)
|
|
if column.casefold() in h.casefold()), 0)
|
|
set_name = (pred.set_name or "").strip() or question[:60]
|
|
origin_question = (pred.origin_question or "").strip() or question
|
|
# INGEST ALL ROWS: one membership edge per row, quote = the full
|
|
# stored row line, containment against the stored table text
|
|
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(table.text_lines())
|
|
members: list[str] = []
|
|
ord_counter = 0
|
|
for row in table.rows:
|
|
element = (row[col_i] if col_i < len(row) else (row[0] if row else "")).strip()
|
|
if not element:
|
|
continue
|
|
if " / " in element:
|
|
element = element.split(" / ")[0].strip() # first of multi-value cell
|
|
if element.casefold() in ("total", "totals", "sum", "average", "mean"):
|
|
continue # aggregate footer rows are not members
|
|
if element.isdigit():
|
|
continue # a bare number in the element column is not a member
|
|
ord_counter += 1
|
|
row_line = " | ".join(row)
|
|
ok, reason = check_candidate(
|
|
{"subject": element, "relation": "member_of", "object": set_name,
|
|
"quote": row_line}, table_text)
|
|
if not ok:
|
|
self._log(f"list row rejected ({reason}): {element[:40]}")
|
|
continue
|
|
qid = self.store.add_quote(doc_id, row_line, page.url, page.fetched_at)
|
|
self.store.add_edge(element, "member_of", set_name, qid,
|
|
src_sort="PLACE", dst_node_name=set_name,
|
|
origin_question=origin_question,
|
|
list_ord=ord_counter)
|
|
members.append(element)
|
|
self._merged += 1
|
|
if not members:
|
|
return None
|
|
# ORDER-PRESERVING dedup: the table's order IS information (a ranked
|
|
# table ranks — top-N slices read it). Sorting alphabetically imposed
|
|
# an order the source never had.
|
|
items = list(dict.fromkeys(members))
|
|
self._log(f"LIST ingest: {len(items)} members of '{set_name}' from "
|
|
f"table {idx} ({table.total_rows} rows)", think=True)
|
|
# ANSWER-LEVEL CHECK: corroborate the count from prose OUTSIDE the
|
|
# table (the extract text is the article prose; tables are separate).
|
|
# One bounded call; failure = honest 'no corroboration', never a loop.
|
|
verify = self._verify_count(set_name, len(items), page.text, charge_llm)
|
|
coverage = {"source": page.title, "table": idx,
|
|
"rows_total": table.total_rows,
|
|
"rows_ingested": len(members),
|
|
"complete_per_source": len(members) == table.total_rows,
|
|
"ranked": True} # row order = source order; top-N reads it
|
|
if verify:
|
|
coverage["count_corroborated"] = True
|
|
coverage["corroboration_quote"] = verify["quote"]
|
|
else:
|
|
coverage["count_corroborated"] = False
|
|
return {
|
|
"value": str(len(items)),
|
|
"list_items": items,
|
|
"list_count": len(items),
|
|
"quote": table.rows[0] and " | ".join(table.rows[0]),
|
|
"url": page.url,
|
|
"confidence": "high" if verify else "medium",
|
|
"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 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 []
|
|
|
|
harvested = 0
|
|
for t in page.tables:
|
|
if harvested >= self.cfg.skim_harvest_max_tables:
|
|
break
|
|
if t.idx == getattr(page, "_list_table_idx", -1):
|
|
continue # the table that answered the LIST question
|
|
goal_hit = any(gt and (gt in (t.caption or "").casefold()
|
|
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])))
|
|
if not goal_hit:
|
|
if qty_signal:
|
|
# a quantity table we cannot tie to the goal vocabulary:
|
|
# 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 — 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
|
|
# header carrying a GOAL term (goal-directed harvest — the
|
|
# header names the attribute the goal asks for), keyword
|
|
# fallbacks (flow/discharge/quantity headers) after
|
|
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 i != ent_i and h and any(
|
|
gt in h.casefold() for gt in goal_terms)), 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:
|
|
self._log(f"skim harvest: table {t.idx} of {page.title}: no "
|
|
f"value column — recorded, not ingested", think=True)
|
|
continue
|
|
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}/{nm} entity overlap — skipped",
|
|
think=True)
|
|
continue
|
|
merged = self._ingest_scalar_table(page, t, ent_i, val_i)
|
|
if merged:
|
|
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
|
|
page. Returns number of candidates merged this page. Counters
|
|
ACCUMULATE on self.
|
|
|
|
PR-1: chunks are RANKED by skim signals (question terms + goal terms
|
|
+ quantity-unit patterns) instead of taking the first N in document
|
|
order — the Italy run burned its extract slots on tangential chunks
|
|
while the discharge table sat later in the document. A chunk without
|
|
ANY signal is skipped for free."""
|
|
chunks = chunk_page(page.text, target=self.cfg.chunk_chars_target,
|
|
cap=self.cfg.chunk_chars_cap)
|
|
gated = [c for c in chunks if self._gate(c, kws)]
|
|
if goal_terms:
|
|
from .store import stem
|
|
|
|
def rank(c) -> tuple[int, int]:
|
|
low = c.text.casefold()
|
|
sig = sum(1 for t in set(kws + goal_terms)
|
|
if t and (t in low or stem(t) in low))
|
|
return (sig + 2 * len(find_quantities(c.text)), -c.idx)
|
|
gated.sort(key=rank, reverse=True)
|
|
capped = gated[: self.cfg.max_chunks_extracted]
|
|
self._log(f"{page.title}: {len(chunks)} chunks, {len(gated)} gated, "
|
|
f"{len(capped)} extracted (skim-ranked)", think=True)
|
|
for chunk in capped:
|
|
if charge_llm:
|
|
charge_llm()
|
|
raw = self.extract(question=question, heading=chunk.heading_path, text=chunk.text)
|
|
for cand in parse_facts(raw.facts):
|
|
self._checked += 1
|
|
ok, reason = check_candidate(cand, page.text)
|
|
if not ok:
|
|
self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}")
|
|
continue
|
|
doc_id = self.store.add_document(
|
|
url=page.url, title=page.title, fetched_at=page.fetched_at,
|
|
sha256=hashlib.sha256(page.text.encode()).hexdigest())
|
|
qid = self.store.add_quote(doc_id, cand["quote"], page.url, page.fetched_at)
|
|
self.store.add_edge(cand["subject"], cand["relation"], cand["object"], qid)
|
|
self._merged += 1
|
|
return self._merged
|
|
|
|
def _gate(self, chunk, keywords: list[str]) -> bool:
|
|
"""Lexical gate with stemming: chunk must mention a question stem."""
|
|
from .store import stem
|
|
if not keywords:
|
|
return True
|
|
low = chunk.text.casefold()
|
|
return any(stem(k) in low or k in low for k in keywords)
|
|
|
|
def _answer_from_rows(self, question: str, rows, charge_llm=None) -> dict:
|
|
if not rows:
|
|
return {"value": "UNKNOWN", "quote": "", "url": "", "confidence": "low"}
|
|
if charge_llm:
|
|
charge_llm()
|
|
rendered = "\n".join(
|
|
f"K{i}: {r.src} | {r.rel} | {r.dst} | quote: {r.quote} | {r.url}"
|
|
f"{' | CONFLICT' if r.conflict else ''}"
|
|
for i, r in enumerate(rows))
|
|
pred = self.answer(question=question, rows=rendered)
|
|
return {
|
|
"value": pred.value.strip(),
|
|
"quote": pred.quote.strip(),
|
|
"url": next((r.url for r in rows if r.quote and pred.quote.strip()
|
|
and r.quote.strip() in pred.quote.strip()), rows[0].url),
|
|
"confidence": pred.confidence.strip().lower(),
|
|
} |