feat(knowledge): LIST answer path — full table ingestion, typed list payloads

Part 1 of the lists design (DESIGN.md §11): mechanical full ingestion, separated from epistemic answer-completeness. parse_tables rewritten as a GRID parser: cells accumulate until |- (both layouts), empty cells kept as placeholders (image cells clean to ''; dropping them shifted France rows to start at 'FRA'), rowspan/colspan expanded at placement, total_rows is the computed extent — no truncation. _clean_cell: refs/sup/File links dropped, citation templates (cref2/efn...) resolve empty, links take display text, attrs split first. LIST path in expert.py: deterministic enumeration detection OR planner-declared LIST; SELECT TABLE (one LLM call over table metadata, never rows); ingest ALL rows as member_of edges (quote = full row line, containment against stored table text); aggregate via len() — no LLM. AnswerType.LIST added; evidence payloads carry list_items + coverage. Verified live cold: 50 sovereign states from the Europe article table (51 rows - Total footer), every member with verbatim quote. 19/19 tests.
This commit is contained in:
2026-10-18 16:53:10 +02:00
parent a78f65de2c
commit 6fcb3c0a86
9 changed files with 480 additions and 40 deletions
+102 -3
View File
@@ -23,8 +23,8 @@ import dspy
from .checks import check_candidate
from .chunker import chunk_page
from .extract import (AnswerFromKG, ExtractSignature, TranslateSignature,
parse_facts)
from .extract import (AnswerFromKG, ExtractSignature, SelectTableSignature,
TranslateSignature, parse_facts)
from .store import KnowledgeStore
from .wiki import WikipediaClient, WikiPage
@@ -55,6 +55,7 @@ class KnowledgeExpert:
self.extract = dspy.Predict(ExtractSignature)
self.answer = dspy.Predict(AnswerFromKG)
self.translate = dspy.Predict(TranslateSignature)
self.select_table = dspy.Predict(SelectTableSignature)
self._checked = 0
self._merged = 0
@@ -78,7 +79,8 @@ class KnowledgeExpert:
# ---- the pipeline --------------------------------------------------------
def answer_question(self, question: str, parent_question: str = "",
evidence: str = "", charge_llm=None) -> dict:
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
@@ -167,6 +169,12 @@ class KnowledgeExpert:
self._log(f"fetch order: {ordered[: self.cfg.max_articles]}", think=True)
pages: list[WikiPage] = []
# LIST activation: declared by the planner (answer_type=LIST) OR
# detected deterministically when the question is an enumeration ask
# (planner support pending on the local model — the path must work
# regardless of who declares it)
list_mode = (str(answer_type or "").upper() == "LIST"
or self._is_enumeration(question))
for title in ordered[: self.cfg.max_articles]:
try:
page = self.client.fetch_rich(title)
@@ -174,6 +182,15 @@ class KnowledgeExpert:
self._log(f"fetch failed: {title}: {e}")
continue
pages.append(page)
# 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:
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]}}
# 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)
@@ -199,6 +216,88 @@ class KnowledgeExpert:
"pages": [p.title for p in pages],
"elapsed_s": round(time.time() - t0, 1)}}
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 _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
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]
# 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] = []
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 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
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)
members.append(element)
self._merged += 1
if not members:
return None
items = sorted(set(members))
self._log(f"LIST ingest: {len(items)} members of '{set_name}' from "
f"table {idx} ({table.total_rows} rows)", think=True)
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",
"coverage": {"source": page.title, "table": idx,
"rows_total": table.total_rows,
"rows_ingested": len(members),
"complete_per_source": len(members) == table.total_rows},
}
def _process_page(self, page: WikiPage, question: str, kws: list[str],
charge_llm) -> int:
"""Chunk -> gate -> extract -> check -> merge for ONE page. Returns