Conflict resolutions, the honest way: - extract/expert gap-step: main's deterministic COMPOSE wins over the branch's TRANSLATE LLM (main removed it 23/10 with measurement: the model was putting the ANSWER into retrieval queries). The branch's _extract_entities contract (question-blind extractor) is fed from compose's entities. - tablefrags/semantic tests: restored the branch's adapted versions + fixed their single-insert sys.path bug (parent.parent resolved to knowledge/, not code/ — the tests were silently importing MAIN's expert.py through the venv pth; same class as the run-085457 trap).
1173 lines
59 KiB
Python
1173 lines
59 KiB
Python
"""The knowledge expert pipeline: KG-first, gather on gap, containment-checked.
|
|
|
|
Per question (one routed knowledge call):
|
|
1. COMPOSE: question + evidence -> queries/entities (deterministic) [engine]
|
|
2. KG PROBE: hybrid — lexical seeds UNION semantic rank (embeddings)[engine]
|
|
3. gap? -> SEARCH en.wikipedia (official search) [engine]
|
|
4. FETCH top articles, CHUNK by sections; TABLE SKIM decides which
|
|
tables deserve extraction (identity + first rows, BEFORE spend)[LLM, 1/page]
|
|
5. EXTRACT per chunk (map), QUESTION-BLIND (entities only) [LLM]
|
|
6. CHECK: containment in FULL text + well-formedness [engine]
|
|
7. MERGE into the store: corroboration / conflicts / supersession
|
|
+ vector cache for the semantic probe [engine]
|
|
8. ANSWER from KG rows (select + one LLM answer call) [LLM]
|
|
|
|
Laws: no quote, no edge; no edge, no answer. The extractor never sees the
|
|
question (research/semantic-kg): it transcribes facts about ENTITIES — the
|
|
question lives in retrieval (skim/ranking/probe) and the judge only.
|
|
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, Fact, SelectTableSignature,
|
|
SkimPromoteSignature, SkimTableSignature,
|
|
VerifyCountSignature)
|
|
from .embeddings import EmbedderDown, embed
|
|
from .queries import compose_queries, keywords, proper_nouns
|
|
from .store import KnowledgeStore, norm_name
|
|
from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert,
|
|
tables_as_chunks, format_table_frag)
|
|
|
|
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
|
|
|
|
# (K5) bug (run 085457, 24-25/10): glm-5.3-flash glues row citations and
|
|
# glosses onto the value field (AnswerFromKG says "cite rows by id" but has
|
|
# no citation output field, so the model cites in the only field it has).
|
|
# Three live shapes, stripped at the judge's output boundary — BEFORE the
|
|
# evidence payload and the ablation audit see the value:
|
|
# "... (K5)" — row-id citation suffix
|
|
# "... (…; cited from rows K16 and K30)" — parenthetical gloss citing rows
|
|
# "15 (list of 15 members: …)" — the LIST path's own gloss of a count
|
|
# Trailing-only, marker-anchored: "(PSOE)" inside a name, "(since 2018)",
|
|
# "(Presidente del Gobierno)" are legitimate and MUST survive. Fixed code
|
|
# cleans the model's proposal (LLMs propose, code decides — the audit's
|
|
# _carries then finds the support rows and the ambiguity audit can run).
|
|
_ROW_CITATION_RE = re.compile(
|
|
r"\s*\(\s*(?:row\s+|rows\s+)?K\d+(?:\s*(?:,|and|;)\s*K?\d+)*\s*\)\s*$",
|
|
re.IGNORECASE)
|
|
_ROW_CITED_GLOSS_RE = re.compile(
|
|
r"\s*\([^()]*\bcited from (?:row|rows)\b[^()]*\)\s*$",
|
|
re.IGNORECASE)
|
|
_LIST_GLOSS_RE = re.compile(
|
|
r"\s*\(\s*list of\b[^()]*\)\s*$",
|
|
re.IGNORECASE)
|
|
|
|
|
|
def _clean_value(value: str) -> str:
|
|
"""Strip trailing citation/gloss parentheticals from a judge value.
|
|
|
|
The boundary law: only TRAILING shapes with a citation/list marker are
|
|
touched; mid-value text and legitimate parentheticals are the model's
|
|
own words and stay. Idempotent by construction (a cleaned value ends
|
|
clean). UNKNOWN and empty pass through untouched.
|
|
"""
|
|
v = (value or "").strip()
|
|
if not v or v.upper() == "UNKNOWN":
|
|
return v
|
|
for rx in (_ROW_CITATION_RE, _ROW_CITED_GLOSS_RE, _LIST_GLOSS_RE):
|
|
v = rx.sub("", v).rstrip()
|
|
return v.strip()
|
|
|
|
|
|
# header/caption terms that name the ENTITY column of a typical scalar table
|
|
_ENTITY_COL = ("river", "country", "name", "state", "city", "entity", "member")
|
|
|
|
|
|
def _tokens(text: str) -> set[str]:
|
|
"""Casefolded word tokens — the boundary-correct matching base. 'flow'
|
|
must not match 'Outflow' (run H: 227 world rows ingested as 'Outflow'
|
|
edges because a goal term hit a substring)."""
|
|
return {w.casefold() for w in WORD_RE.findall(text or "")}
|
|
|
|
|
|
def _term_hits(term: str, text: str) -> bool:
|
|
"""Goal-term match with word boundaries: the term must appear as a
|
|
WHOLE token (stem tolerated) in the text's tokens."""
|
|
if not term:
|
|
return False
|
|
toks = _tokens(text)
|
|
if term.casefold() in toks:
|
|
return True
|
|
from .store import stem
|
|
return stem(term) in {stem(t) for t in toks if t}
|
|
|
|
|
|
def _col_hits(col: str, header: str) -> bool:
|
|
"""The LLM names a column (possibly multi-word: 'Mean discharge').
|
|
It matches a header when any of its content tokens appears as a whole
|
|
token in the header ('discharge' in 'Average discharge' -> True;
|
|
'Flow at the mouth' vs 'Length (km)' -> False)."""
|
|
if not col:
|
|
return False
|
|
stops = {"the", "at", "of", "in", "a", "an", "and"}
|
|
from .store import stem
|
|
ctoks = {t for t in _tokens(col) if t not in stops and len(t) > 2}
|
|
if not ctoks:
|
|
return False
|
|
htoks = _tokens(header)
|
|
hstems = {stem(t) for t in htoks if t}
|
|
return any(c in htoks or stem(c) in hstems for c in ctoks)
|
|
|
|
|
|
def _prop_hit(prop: str, toks: set[str]) -> bool:
|
|
"""Proper-noun subject match: whole token, stem, or WORD PREFIX —
|
|
'Europe' matches 'European' (the gentilici pattern is everywhere on
|
|
Wikipedia: 'List of European states' answers 'countries in Europe?').
|
|
Prefix >= 4 chars keeps it from matching junk."""
|
|
pl = prop.casefold()
|
|
from .store import stem
|
|
ps = stem(pl)
|
|
for t in toks:
|
|
if t == pl or stem(t) == ps:
|
|
return True
|
|
if len(pl) >= 4 and (t.startswith(pl) or pl.startswith(t) and len(t) >= 4):
|
|
return True
|
|
return False
|
|
|
|
|
|
def _proper_nouns(question: str) -> set[str]:
|
|
"""The subject guard's noun extractor — delegates to knowledge/queries.py
|
|
(single source: the query composer and the guards share the NE law).
|
|
Semantics unchanged: capitalized non-question words ('Italy', 'Po')."""
|
|
return proper_nouns(question)
|
|
|
|
|
|
@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
|
|
ambiguity_rounds: int = 3 # ablation rounds per scalar answer (run J)
|
|
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
|
|
# semantic retrieval (research/semantic-kg)
|
|
embed_url: str = "http://127.0.0.1:11435/api/embed"
|
|
embed_model: str = "nomic-embed-text:latest"
|
|
semantic_tau: float = 0.45 # calibration: rivers 0.49-0.52 in, Pedro
|
|
# cross-question 0.35-0.38 out, spouse-noise ~0.67
|
|
max_facts_per_chunk: int = 12 # question-blind extraction needs a cap
|
|
|
|
|
|
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.select_table = dspy.Predict(SelectTableSignature)
|
|
self.verify_count = dspy.Predict(VerifyCountSignature)
|
|
self.skim_promote = dspy.Predict(SkimPromoteSignature)
|
|
self.skim_tables = dspy.Predict(SkimTableSignature)
|
|
self._checked = 0
|
|
self._merged = 0
|
|
# semantic probe: cached question vector for this call (the probe
|
|
# runs after every ingest; embedding the question twice is waste)
|
|
self._qvec_cache: dict[str, list[float]] = {}
|
|
self._embed_ok = True # flips False on first EmbedderDown; honest
|
|
# 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)
|
|
|
|
def _qvec(self, question: str) -> list[float] | None:
|
|
"""Question vector, cached per question text. None = embedder down
|
|
(the probe degrades to lexical — offline fallback law, never dead)."""
|
|
if not self._embed_ok:
|
|
return None
|
|
if question in self._qvec_cache:
|
|
return self._qvec_cache[question]
|
|
try:
|
|
v = embed([question], model=self.cfg.embed_model,
|
|
url=self.cfg.embed_url)[0]
|
|
self._qvec_cache[question] = v
|
|
return v
|
|
except EmbedderDown as e:
|
|
self._embed_ok = False
|
|
self._log(f"semantic probe disabled (embedder down): {e}")
|
|
return None
|
|
|
|
def _probe(self, question: str, seeds: list[str]) -> list:
|
|
"""HYBRID probe (research/semantic-kg): lexical seeds UNION semantic
|
|
rank. The lexical probe keeps exact-vocabulary recall (Po/flow);
|
|
the semantic layer surfaces vocabulary the lexical one cannot see
|
|
('President' vs 'Prime Minister', calibration 0.71). Dedup by edge
|
|
id; semantic order fills the tail after lexical hits."""
|
|
rows = self.store.probe(seeds)
|
|
qv = self._qvec(question)
|
|
if qv is None:
|
|
return rows
|
|
sem = self.store.semantic_probe(qv, tau=self.cfg.semantic_tau)
|
|
if not sem:
|
|
return rows
|
|
seen = {r.eid for r in rows}
|
|
added = 0
|
|
for r in sem:
|
|
if r.eid in seen:
|
|
continue
|
|
seen.add(r.eid)
|
|
rows.append(r)
|
|
added += 1
|
|
if added:
|
|
self._log(f"semantic probe: +{added} edges the lexical probe missed "
|
|
f"(tau={self.cfg.semantic_tau})", think=True)
|
|
return rows
|
|
|
|
@staticmethod
|
|
def _keywords(question: str, k: int = 6) -> list[str]:
|
|
"""Deterministic lexical focus — delegates to knowledge/queries.py
|
|
(single source: the probe seeds and the query composer share the
|
|
same keyword law)."""
|
|
return keywords(question, 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()
|
|
# parent_question/evidence ARE the machine's context (design §4) —
|
|
# consumed directly by the probe seeds, the query composer and the
|
|
# guards; no prompt ever renders them into a TRANSLATE call anymore.
|
|
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]
|
|
# the extractor's ENTITIES (research/semantic-kg): TRANSLATE resolves
|
|
# them; keywords of the question are the fallback when it returns none
|
|
self._extract_entities: list[str] = []
|
|
# 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. HYBRID KG probe: lexical seeds UNION semantic rank (embeddings)
|
|
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._probe(question, 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 {**self._audit_ambiguity(question, answer, rows, charge_llm),
|
|
"source": "knowledge_graph", "kg_rows": len(rows)}
|
|
|
|
# 3-4. gap -> search + fetch. COMPOSE (deterministic, from main 23/10 —
|
|
# the model's own knowledge of the entities can no longer steer
|
|
# retrieval) + the branch's extract-entities contract: the
|
|
# question-blind extractor transcribes facts about THESE.
|
|
queries, entity_terms = compose_queries(
|
|
question, evidence_entities=ev_entities, list_mode=list_mode)
|
|
self._extract_entities = list(dict.fromkeys(
|
|
e for e in (entity_terms + sorted(_proper_nouns(question))) if e))
|
|
self._log(f"compose -> 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(_term_hits(gt, notice) 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._probe(question, 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 {**self._audit_ambiguity(question, answer,
|
|
self._probe(question, probe_seeds),
|
|
charge_llm),
|
|
"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, hybrid) and answer from the merged KG
|
|
rows = self._probe(question, 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 {**self._audit_ambiguity(question, answer, rows, charge_llm), "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 _audit_ambiguity(self, question: str, answer: dict, rows,
|
|
charge_llm=None) -> dict:
|
|
"""Ablation ambiguity detector (KNOWLEDGE.md §8, run J).
|
|
|
|
The KG just answered with value V from some support row(s). Ask the
|
|
SAME judge (AnswerFromKG) whether the question ALSO answers without
|
|
that support: mask the rows whose object/relation produced V, re-ask.
|
|
A DIFFERENT surviving value = a second defensible reading -> flag.
|
|
Repeat (bounded) until the rows run out of answers. Same-value
|
|
survivors are corroboration, not ambiguity — silent.
|
|
|
|
Zero new prompts: same AnswerFromKG signature, one call per round.
|
|
The store is NEVER mutated — the mask is a view, deletion happens
|
|
nowhere. Ordinary questions end at round 1 with UNKNOWN (silent).
|
|
"""
|
|
value = str(answer.get("value", "")).strip()
|
|
if (not value or value.upper() == "UNKNOWN" or not rows):
|
|
return answer
|
|
|
|
# The supporting rows for the PICKED value. DST-FIRST LAW (run L):
|
|
# when a row has a meaningful dst it is the VALUE BEARER — quotes
|
|
# interleave readings in one paragraph ('... Secretary-General ...
|
|
# president of Socialist International ...' is ONE quote), so
|
|
# quote-matching over-masks and the audit dies silent at round 1.
|
|
# The quote is a fallback ONLY for rows whose dst is empty/numeric.
|
|
_NUMERIC_RE = re.compile(r"^[\d\s.,:+\-/–—%]+$")
|
|
|
|
def _dst(r) -> str:
|
|
return (getattr(r, "dst", "") or "").strip()
|
|
|
|
def _dst_meaningful(r) -> bool:
|
|
d = _dst(r)
|
|
return bool(d) and not _NUMERIC_RE.match(d)
|
|
|
|
def _carries(r) -> bool:
|
|
v = value.casefold()
|
|
if _dst_meaningful(r):
|
|
return v in _dst(r).casefold()
|
|
quote = (getattr(r, "quote", "") or "").strip().casefold()
|
|
return v in quote
|
|
|
|
def _carries_target(r, val: str) -> bool:
|
|
"""DST-FIRST law, parameterized for a round's surviving value.
|
|
|
|
The judge's value may be an OFFICE DESCRIPTION, not the dst
|
|
entity itself ('prime minister of Spain' vs dst='Spain') —
|
|
resolve the row by reciprocal token containment: the dst
|
|
names the entity, the value describes the reading; overlap
|
|
means this row carried it."""
|
|
v = val.casefold()
|
|
if _dst_meaningful(r):
|
|
d = _dst(r).casefold()
|
|
if v == d or v in d or d in v:
|
|
return True
|
|
vt = set(WORD_RE.findall(v))
|
|
dt = set(WORD_RE.findall(d))
|
|
return bool(vt & dt) if vt and dt else False
|
|
quote = (getattr(r, "quote", "") or "").strip().casefold()
|
|
return v in quote
|
|
|
|
support = [r for r in rows if _carries(r)]
|
|
if not support:
|
|
return answer # the judge invented it: nothing to ablate
|
|
|
|
alternatives: list[dict] = []
|
|
seen = {norm_name(value)}
|
|
masked = set(id(r) for r in support)
|
|
|
|
for _ in range(self.cfg.ambiguity_rounds):
|
|
view = [r for r in rows if id(r) not in masked]
|
|
if not view:
|
|
break
|
|
re_ans = self._answer_from_rows(question, view, charge_llm)
|
|
re_val = str(re_ans.get("value", "")).strip()
|
|
if not re_val or re_val.upper() == "UNKNOWN":
|
|
break # the KG has no other reading: clean
|
|
key = norm_name(re_val)
|
|
if key in seen:
|
|
break # same value again: corroboration, not ambiguity
|
|
seen.add(key)
|
|
# which surviving row produced this reading? DST-FIRST here too
|
|
# — same law as the pick's mask, for the report and the next mask
|
|
src_row = next((r for r in view if _carries_target(r, re_val)), None)
|
|
alternatives.append({
|
|
"value": re_val,
|
|
"quote": re_ans.get("quote", ""),
|
|
"url": (src_row.url if src_row is not None
|
|
else re_ans.get("url", "")),
|
|
})
|
|
# mask this reading's own support too — next round hunts a third
|
|
new_support = [r for r in view if _carries_target(r, re_val)]
|
|
if not new_support:
|
|
break
|
|
masked |= set(id(r) for r in new_support)
|
|
|
|
if not alternatives:
|
|
return answer # ordinary question: byte-identical
|
|
self._log(f"ambiguity audit: {len(alternatives)} other reading(s) "
|
|
f"({'; '.join(a['value'][:40] for a in alternatives[:3])}) "
|
|
f"— flagging, not choosing", think=True)
|
|
return {**answer, "ambiguous": True,
|
|
"axis": f"which {question.strip().rstrip('?')}?",
|
|
"alternatives": alternatives}
|
|
|
|
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)."""
|
|
# SUBJECT GUARD (run H): proper nouns of the question ('Italy') must
|
|
# appear in the article title OR the tables' captions/headers — a
|
|
# world list must never answer a question about one country. With no
|
|
# evidence yet (first hop), the disjointness guard is vacuous; THIS
|
|
# is the guard that fired instead of it.
|
|
props = _proper_nouns(question)
|
|
if props:
|
|
surface = " ".join([page.title]
|
|
+ [t.caption or "" for t in page.tables]
|
|
+ [" ".join(t.header) for t in page.tables])
|
|
toks = _tokens(surface)
|
|
if not any(_prop_hit(p, toks) for p in props):
|
|
self._log(f"subject guard: {page.title} names none of "
|
|
f"{sorted(props)} — refusing LIST from this article",
|
|
think=True)
|
|
return None
|
|
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)
|
|
chosen = pred.chosen
|
|
if chosen is None:
|
|
return None
|
|
idx = chosen.table_index
|
|
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 = chosen.column.strip()
|
|
col_i = next((i for i, h in enumerate(table.header)
|
|
if column.casefold() in h.casefold()), 0)
|
|
set_name = chosen.set_name.strip() or question[:60]
|
|
origin_question = 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
|
|
# WORD BOUNDARIES (run H: 'flow' matched 'Outflow' by substring
|
|
# and 227 world rows entered the KG as 'Outflow' edges)
|
|
goal_hit = any(
|
|
_term_hits(gt, (t.caption or "") + " " + " ".join(t.header))
|
|
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 _ENTITY_COL), 0)
|
|
val_i = next((i for i, h in enumerate(t.header)
|
|
if i != ent_i and h and any(
|
|
_term_hits(gt, h) for gt in goal_terms)), 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 d in (pred.decisions or []):
|
|
got = lookup.get(d.table_index)
|
|
if not d.promote or got is None:
|
|
continue
|
|
page, t = got
|
|
col = (d.column or "").strip()
|
|
ent_i = next((i for i, h in enumerate(t.header)
|
|
if h.casefold() in _ENTITY_COL), 0)
|
|
val_i = next((i for i, h in enumerate(t.header)
|
|
if col and _col_hits(col, h)), 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 {d.table_index} ({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 {d.table_index} "
|
|
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.
|
|
|
|
research/semantic-kg: the extractor is QUESTION-BLIND — it receives
|
|
the ENTITIES (from TRANSLATE + evidence + proper nouns) and
|
|
transcribes their facts; ranking/gating still uses the question
|
|
(the machine's slots are limited — the best-guess chunks get them).
|
|
Tables: SkimTableSignature decides BEFORE extraction which tables
|
|
deserve fragments (identity + first rows, one call per page);
|
|
fragments of rejected tables are skipped with zero extract spend."""
|
|
entities = self._extract_entities or sorted(_proper_nouns(question))
|
|
ent_str = ", ".join(entities[:8]) or "(none named)"
|
|
chunks = chunk_page(page.text, target=self.cfg.chunk_chars_target,
|
|
cap=self.cfg.chunk_chars_cap)
|
|
# the gate keeps question terms OR entity mentions — a chunk about
|
|
# the entity (but in other vocabulary) is exactly what the semantic
|
|
# layer exists for; a chunk about neither is noise for both
|
|
gated = [c for c in chunks if self._gate(c, kws)
|
|
or any(_term_hits(e, c.text) for e in entities)]
|
|
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]
|
|
|
|
# ---- TABLE SKIM (research/semantic-kg): decide table relevance
|
|
# BEFORE paying extraction — identity + first rows, one call per
|
|
# page. The LIST answer's own table never enters; tables that name
|
|
# an entity are ALWAYS relevant (never skipped by the LLM's word).
|
|
list_idx = getattr(page, "_list_table_idx", -1)
|
|
table_frags_all = [f for f in tables_as_chunks(page.wikitext)
|
|
if f["table_idx"] != list_idx]
|
|
stopped: set[int] = set()
|
|
if table_frags_all and page.tables:
|
|
# deterministic safety net: a table whose caption/headers/first
|
|
# rows NAME an entity is relevant, no LLM call needed
|
|
def _names_entity(t) -> bool:
|
|
surface = " ".join([t.caption or ""] + list(t.header[:6])
|
|
+ [r and " ".join(r[:2]) or ""
|
|
for r in t.rows[:3]])
|
|
toks = _tokens(surface)
|
|
return any(_prop_hit(e, toks) for e in entities)
|
|
|
|
undecided = [t for t in page.tables
|
|
if t.idx != list_idx and not _names_entity(t)]
|
|
if undecided:
|
|
rendered = chr(10).join(
|
|
f"{t.idx} | {t.caption or '(no caption)'} | "
|
|
f"header: {', '.join(t.header[:6]) or '(none)'} | "
|
|
f"rows: {t.total_rows} | first rows: "
|
|
+ " ;; ".join(" | ".join(r) for r in t.rows[:3] if r)
|
|
for t in undecided)
|
|
if charge_llm:
|
|
charge_llm()
|
|
pred = self.skim_tables(question=question,
|
|
entities=ent_str, tables=rendered)
|
|
for d in (pred.decisions or []):
|
|
if not d.relevant:
|
|
stopped.add(d.table_index)
|
|
self._log(f"table skim: table {d.table_index} "
|
|
f"({(d.reason or '')[:50]}) — skipped before "
|
|
f"extraction", think=True)
|
|
table_frags = [f for f in table_frags_all
|
|
if f["table_idx"] not in stopped]
|
|
frag_slots = max(0, self.cfg.max_chunks_extracted - len(capped))
|
|
frag_budget = min(frag_slots, len(table_frags))
|
|
|
|
self._log(f"{page.title}: {len(chunks)} chunks, {len(gated)} gated, "
|
|
f"{len(capped)} extracted (skim-ranked); "
|
|
f"{len(table_frags)} table frags, {frag_budget} considered",
|
|
think=True)
|
|
extracted = 0
|
|
for chunk in capped:
|
|
if charge_llm:
|
|
charge_llm()
|
|
raw = self.extract(entities=ent_str, heading=chunk.heading_path,
|
|
text=chunk.text)
|
|
for cand in (raw.facts or [])[: self.cfg.max_facts_per_chunk]:
|
|
extracted += self._ingest_candidate(cand, page, containment=page.text)
|
|
# ---- table fragments (extract path) -----------------------------
|
|
from .store import stem as _stem
|
|
# containment target: prose + ALL table rows (the fragment's rows
|
|
# live in page.tables, not in page.text, since the enrichment left)
|
|
tables_text = "\n".join("\n".join(t.text_lines()) for t in page.tables)
|
|
containment = page.text + "\n" + tables_text if tables_text else page.text
|
|
frag_considered = 0
|
|
for frag in table_frags[:frag_budget]:
|
|
if frag["table_idx"] in stopped:
|
|
continue
|
|
text = format_table_frag(frag)
|
|
low = text.casefold()
|
|
sig = sum(1 for t in set(kws + goal_terms)
|
|
if t and (t in low or _stem(t) in low))
|
|
qty = len(find_quantities(low))
|
|
if sig == 0 and qty == 0:
|
|
self._log(f"table frag skipped (no signal): "
|
|
f"table {frag['table_idx']} part {frag['part']}/{frag['of']}")
|
|
continue
|
|
frag_considered += 1
|
|
if charge_llm:
|
|
charge_llm()
|
|
heading = f"== Tables == (table {frag['table_idx']}, part {frag['part']}/{frag['of']})"
|
|
raw = self.extract(entities=ent_str, heading=heading, text=text)
|
|
for cand in (raw.facts or [])[: self.cfg.max_facts_per_chunk]:
|
|
extracted += self._ingest_candidate(cand, page, containment=containment)
|
|
return self._merged
|
|
|
|
def _ingest_candidate(self, cand, page: WikiPage, containment: str) -> int:
|
|
"""Containment-check one typed Fact, merge it, cache its vector.
|
|
Returns 1 when merged, 0 otherwise. Shared by the prose and table-
|
|
fragment extract paths (research/semantic-kg)."""
|
|
self._checked += 1
|
|
cand = {"subject": cand.subject, "relation": cand.relation,
|
|
"object": cand.object, "quote": cand.quote}
|
|
ok, reason = check_candidate(cand, containment)
|
|
if not ok:
|
|
self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}")
|
|
return 0
|
|
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)
|
|
eid = self.store.add_edge(cand["subject"], cand["relation"],
|
|
cand["object"], qid)
|
|
self._merged += 1
|
|
if eid is not None:
|
|
self._cache_edge_vector(eid, cand["subject"], cand["relation"],
|
|
cand["object"])
|
|
return 1
|
|
|
|
def _cache_edge_vector(self, eid: int, subject: str, relation: str,
|
|
obj: str) -> None:
|
|
"""Embed 'subject | relation | object' and cache it for the semantic
|
|
probe. Batched lazily: failures flip _embed_ok off (lexical fallback
|
|
keeps the run alive); no failure ever blocks an ingest."""
|
|
if not self._embed_ok:
|
|
return
|
|
text = f"{subject} | {relation} | {obj}"
|
|
try:
|
|
v = embed([text], model=self.cfg.embed_model,
|
|
url=self.cfg.embed_url)[0]
|
|
self.store.set_edge_vector(eid, self.cfg.embed_model,
|
|
hashlib.sha1(text.encode()).hexdigest(), v)
|
|
except EmbedderDown:
|
|
self._embed_ok = False
|
|
self._log("semantic probe disabled (embedder down at ingest)")
|
|
|
|
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": _clean_value(pred.value),
|
|
"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": str(pred.confidence.value),
|
|
} |