2 Commits
Author SHA1 Message Date
onibot 12a1ffd77f Merge pull request 'knowledge: typed outputs for all 5 remaining signatures (block PR)' (#14) from feature/typed-knowledge into main 2026-10-22 15:11:42 +02:00
onibot 65d42d1942 knowledge: typed outputs for all 5 remaining signatures (block PR)
The typed-output migration completes: every knowledge signature now
declares its structure as Python types and dspy renders/parses it.

- TranslateSignature: queries/entities as list[str] — the
  'QUERIES:'/'ENTITIES:' line protocol and its prefix-scraping parser
  are gone
- AnswerFromKG: confidence is a local Confidence(str, Enum)
  (knowledge stays decoupled from floop)
- SelectTableSignature: chosen is TableChoice | None (index int,
  column, set_name) — 'NONE' string handling gone; origin_question
  dropped (it duplicated the input)
- SkimPromoteSignature: decisions as list[PromotionDecision]
  (table_index int, promote bool, column) — the 'idx: YES col' regex
  parser gone
- VerifyCountSignature: unchanged shape (quote str + NOQUOTE
  convention predates typed migration; kept — it is an answer-shaped
  field, not a format protocol)

Callers consume typed objects directly. Test fakes updated to the new
contracts (promote/store/guards).

VERIFIED:
- suite 14/14 green (84 tests)
- live E2E (ollama-cloud glm-5.3-flash, Italy rivers, fresh KG):
  correct answer 2014 m3/s (Po 1540 + Adige 235 + Tiber 239) with
  verified join; wire prompts show list[str]/TableChoice/Confidence/
  list[Fact] schemas rendered natively
2026-10-22 15:11:33 +02:00
5 changed files with 70 additions and 65 deletions
+15 -30
View File
@@ -269,18 +269,10 @@ class KnowledgeExpert:
if charge_llm: if charge_llm:
charge_llm() charge_llm()
pred = self.translate(question=question, context=context) pred = self.translate(question=question, context=context)
q_raw = (pred.queries or "").strip() queries = [q.strip() for q in (pred.queries or []) if q.strip()][:2]
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: if not queries:
queries = [" ".join(kws[:3])] queries = [" ".join(kws[:3])]
e_raw = (pred.entities or "").strip() entity_terms = [t.strip() for t in (pred.entities or []) if t.strip()][:4]
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) self._log(f"translate -> queries {queries} entities {entity_terms}", think=True)
# search ALL queries first; merge + dedupe candidates; rank GLOBALLY # search ALL queries first; merge + dedupe candidates; rank GLOBALLY
@@ -647,22 +639,19 @@ class KnowledgeExpert:
if charge_llm: if charge_llm:
charge_llm() charge_llm()
pred = self.select_table(question=question, tables=rendered) pred = self.select_table(question=question, tables=rendered)
idx_raw = (pred.table_index or "").strip() chosen = pred.chosen
if not idx_raw or idx_raw.upper() in ("NONE", "N/A", "0"): if chosen is None:
return None
try:
idx = int(re.findall(r"\d+", idx_raw)[0])
except (ValueError, IndexError):
return None return None
idx = chosen.table_index
table = next((t for t in page.tables if t.idx == idx), None) table = next((t for t in page.tables if t.idx == idx), None)
if table is None: if table is None:
return None return None
page._list_table_idx = idx # the harvest skips the LIST answer's table page._list_table_idx = idx # the harvest skips the LIST answer's table
column = (pred.column or "").strip() column = chosen.column.strip()
col_i = next((i for i, h in enumerate(table.header) col_i = next((i for i, h in enumerate(table.header)
if column.casefold() in h.casefold()), 0) if column.casefold() in h.casefold()), 0)
set_name = (pred.set_name or "").strip() or question[:60] set_name = chosen.set_name.strip() or question[:60]
origin_question = (pred.origin_question or "").strip() or question origin_question = question
# INGEST ALL ROWS: one membership edge per row, quote = the full # INGEST ALL ROWS: one membership edge per row, quote = the full
# stored row line, containment against the stored table text # stored row line, containment against the stored table text
doc_id = self.store.add_document( doc_id = self.store.add_document(
@@ -888,16 +877,12 @@ class KnowledgeExpert:
entities=", ".join(expected[:8]), entities=", ".join(expected[:8]),
tables="\n".join(rendered)) tables="\n".join(rendered))
promoted = 0 promoted = 0
for line in (pred.decision or "").strip().splitlines(): for d in (pred.decisions or []):
m = re.match(r"\s*(\d+)\s*:\s*(YES|NO)\s*(.*)$", line.strip(), got = lookup.get(d.table_index)
flags=re.I) if not d.promote or got is None:
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 continue
page, t = got page, t = got
col = (d.column or "").strip()
ent_i = next((i for i, h in enumerate(t.header) ent_i = next((i for i, h in enumerate(t.header)
if h.casefold() in _ENTITY_COL), 0) if h.casefold() in _ENTITY_COL), 0)
val_i = next((i for i, h in enumerate(t.header) val_i = next((i for i, h in enumerate(t.header)
@@ -906,13 +891,13 @@ class KnowledgeExpert:
continue continue
overlap, nm = self._entity_overlap_count(t, ent_i, expected) overlap, nm = self._entity_overlap_count(t, ent_i, expected)
if expected and overlap == 0 and nm >= 2: if expected and overlap == 0 and nm >= 2:
self._log(f"skim promote: table {idx} ({page.title}): LLM said " self._log(f"skim promote: table {d.table_index} ({page.title}): LLM said "
f"YES but {overlap}/{nm} entity overlap — refused", f"YES but {overlap}/{nm} entity overlap — refused",
think=True) think=True)
continue continue
merged = self._ingest_scalar_table(page, t, ent_i, val_i) merged = self._ingest_scalar_table(page, t, ent_i, val_i)
if merged: if merged:
self._log(f"skim promote: {merged} rows of table {idx} " self._log(f"skim promote: {merged} rows of table {d.table_index} "
f"({page.title}) ingested (LLM-proposed)", think=True) f"({page.title}) ingested (LLM-proposed)", think=True)
promoted += 1 promoted += 1
self._skim_leads = [] # consumed: bounded, never re-asked self._skim_leads = [] # consumed: bounded, never re-asked
@@ -1053,5 +1038,5 @@ class KnowledgeExpert:
"quote": pred.quote.strip(), "quote": pred.quote.strip(),
"url": next((r.url for r in rows if r.quote and 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), and r.quote.strip() in pred.quote.strip()), rows[0].url),
"confidence": pred.confidence.strip().lower(), "confidence": str(pred.confidence.value),
} }
+38 -16
View File
@@ -6,10 +6,19 @@ the FULL document text — so chunking can never fake a quote.
""" """
from __future__ import annotations from __future__ import annotations
from enum import Enum
import dspy import dspy
from pydantic import BaseModel from pydantic import BaseModel
class Confidence(str, Enum):
"""Honest self-assessment of an answer drawn from KG rows."""
HIGH = "high"
MEDIUM = "medium"
LOW = "low"
class Fact(BaseModel): class Fact(BaseModel):
"""One fact extracted from a text, with its verbatim supporting quote.""" """One fact extracted from a text, with its verbatim supporting quote."""
subject: str = dspy.OutputField(desc="the fact's subject entity") subject: str = dspy.OutputField(desc="the fact's subject entity")
@@ -23,13 +32,13 @@ class TranslateSignature(dspy.Signature):
"""You are the TRANSLATE step of a knowledge machine. Turn the question """You are the TRANSLATE step of a knowledge machine. Turn the question
into Wikipedia search queries AND resolved entity terms. Resolve into Wikipedia search queries AND resolved entity terms. Resolve
references ('that state', 'the same river') using the context: the original references ('that state', 'the same river') using the context: the original
question and the evidence rows already gathered. Output two lines: question and the evidence rows already gathered."""
QUERIES: 1-2 wikipedia search queries, comma separated.
ENTITIES: the resolved entity names the answer is about, comma separated."""
question: str = dspy.InputField() question: str = dspy.InputField()
context: str = dspy.InputField(desc="the original question + evidence rows with answers already found; resolve pronouns from here; may be empty") context: str = dspy.InputField(desc="the original question + evidence rows with answers already found; resolve pronouns from here; may be empty")
queries: str = dspy.OutputField(desc="line starting with QUERIES: 1-2 comma-separated wikipedia search queries") queries: list[str] = dspy.OutputField(
entities: str = dspy.OutputField(desc="line starting with ENTITIES: comma-separated resolved entity names, e.g. ENTITIES: France, longest river") desc="1-2 Wikipedia search queries, most specific first")
entities: list[str] = dspy.OutputField(
desc="the resolved entity names the answer is about")
class ExtractSignature(dspy.Signature): class ExtractSignature(dspy.Signature):
@@ -59,7 +68,8 @@ class AnswerFromKG(dspy.Signature):
rows: str = dspy.InputField(desc="kg rows: id, subject, relation, object, quote, url") rows: str = dspy.InputField(desc="kg rows: id, subject, relation, object, quote, url")
value: str = dspy.OutputField(desc="the answer, or UNKNOWN") value: str = dspy.OutputField(desc="the answer, or UNKNOWN")
quote: str = dspy.OutputField(desc="VERBATIM supporting quote from the rows, or empty") quote: str = dspy.OutputField(desc="VERBATIM supporting quote from the rows, or empty")
confidence: str = dspy.OutputField(desc="high medium low") confidence: Confidence = dspy.OutputField(
desc="high: rows settle it; medium: plausible but partial; low: weak support")
class VerifyCountSignature(dspy.Signature): class VerifyCountSignature(dspy.Signature):
@@ -81,18 +91,31 @@ class VerifyCountSignature(dspy.Signature):
quote: str = dspy.OutputField(desc="verbatim sentence stating the count, or NOQUOTE") quote: str = dspy.OutputField(desc="verbatim sentence stating the count, or NOQUOTE")
class TableChoice(BaseModel):
"""The table chosen as the answer's enumeration, if any."""
table_index: int = dspy.OutputField(desc="the chosen table's index")
column: str = dspy.OutputField(desc="header name of the column holding the answer elements")
set_name: str = dspy.OutputField(desc="short name of the set this table enumerates")
class SelectTableSignature(dspy.Signature): class SelectTableSignature(dspy.Signature):
"""You are the SELECT TABLE step of a knowledge machine. Given a question """You are the SELECT TABLE step of a knowledge machine. Given a question
and the tables found in an article (index, caption, header columns, row and the tables found in an article (index, caption, header columns, row
count — NOT the rows), decide: does one of these tables enumerate the count — NOT the rows), decide: does one of these tables enumerate the
answer? Output the table index and the column holding the answer answer?"""
elements, or NONE."""
question: str = dspy.InputField() question: str = dspy.InputField()
tables: str = dspy.InputField(desc="one line per table: 'idx | caption | header: a, b, c | rows: N'") tables: str = dspy.InputField(desc="one line per table: 'idx | caption | header: a, b, c | rows: N'")
table_index: str = dspy.OutputField(desc="the chosen table index (e.g. '2'), or NONE") chosen: TableChoice | None = dspy.OutputField(
column: str = dspy.OutputField(desc="header name of the column holding the answer elements; empty if NONE") desc="the chosen table and its answer column; null when NO table enumerates the answer")
set_name: str = dspy.OutputField(desc="short name of the set this table enumerates, e.g. 'sovereign states in Europe'; empty if NONE")
origin_question: str = dspy.OutputField(desc="the question verbatim, for provenance; empty if NONE")
class PromotionDecision(BaseModel):
"""One table's promotion verdict."""
table_index: int = dspy.OutputField(desc="the table's index from the list")
promote: bool = dspy.OutputField(
desc="True when this table holds data about those entities for the goal")
column: str = dspy.OutputField(
desc="when promoted: the header holding the goal's values; empty otherwise")
class SkimPromoteSignature(dspy.Signature): class SkimPromoteSignature(dspy.Signature):
@@ -102,13 +125,12 @@ class SkimPromoteSignature(dspy.Signature):
and the table's words may differ — 'water flow' vs 'Flow at the mouth'). and the table's words may differ — 'water flow' vs 'Flow at the mouth').
Given the run's goal, the entities it is about, and the tables' identity Given the run's goal, the entities it is about, and the tables' identity
(caption, headers, row count, quantity signals — NOT the rows), decide (caption, headers, row count, quantity signals — NOT the rows), decide
per table whether it holds data about those entities for the goal. per table whether it holds data about those entities for the goal."""
Output one line per table: 'idx: YES <column>' or 'idx: NO' — the column
is the header holding the goal's values."""
goal: str = dspy.InputField(desc="the run's overall goal question") goal: str = dspy.InputField(desc="the run's overall goal question")
entities: str = dspy.InputField(desc="the entities the goal is about, comma separated; may be empty") entities: str = dspy.InputField(desc="the entities the goal is about, comma separated; may be empty")
tables: str = dspy.InputField(desc="one line per table: 'idx | caption | header: a, b, c | rows: N | quantities: x, y'") tables: str = dspy.InputField(desc="one line per table: 'idx | caption | header: a, b, c | rows: N | quantities: x, y'")
decision: str = dspy.OutputField(desc="one line per table: 'idx: YES <column>' or 'idx: NO'") decisions: list[PromotionDecision] = dspy.OutputField(
desc="one verdict per table in the list")
def parse_facts(raw: str) -> list[dict]: def parse_facts(raw: str) -> list[dict]:
+3 -4
View File
@@ -13,6 +13,7 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/ sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
from knowledge.wiki import WikiPage, parse_tables from knowledge.wiki import WikiPage, parse_tables
from knowledge.extract import TableChoice
from knowledge.expert import (KnowledgeExpert, KnowledgeConfig, from knowledge.expert import (KnowledgeExpert, KnowledgeConfig,
_tokens, _term_hits, _proper_nouns) _tokens, _term_hits, _proper_nouns)
from knowledge.store import KnowledgeStore from knowledge.store import KnowledgeStore
@@ -118,10 +119,8 @@ def test_subject_guard_list():
e2 = make_expert(KnowledgeStore(f"{tmp2}/kg.sqlite")) e2 = make_expert(KnowledgeStore(f"{tmp2}/kg.sqlite"))
class Pred: class Pred:
table_index = "1" chosen = TableChoice(table_index=1, column="River",
column = "River" set_name="longest rivers of Italy")
set_name = "longest rivers of Italy"
origin_question = q
e2.select_table = lambda **kw: Pred() e2.select_table = lambda **kw: Pred()
ans2 = e2._list_from_page(italy_page(), q, None) ans2 = e2._list_from_page(italy_page(), q, None)
+10 -7
View File
@@ -13,6 +13,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
from knowledge.wiki import WikiPage, WikiTable, parse_tables from knowledge.wiki import WikiPage, WikiTable, parse_tables
from knowledge.store import KnowledgeStore from knowledge.store import KnowledgeStore
from knowledge.extract import PromotionDecision
from knowledge.expert import KnowledgeExpert, KnowledgeConfig from knowledge.expert import KnowledgeExpert, KnowledgeConfig
@@ -32,15 +33,15 @@ def make_expert(store: KnowledgeStore) -> KnowledgeExpert:
class FakePromote: class FakePromote:
"""Scripted skim_promote (dspy module shape): returns fixed decision.""" """Scripted skim_promote (dspy module shape): returns typed decisions."""
def __init__(self, decision: str): def __init__(self, decisions):
self.decision_text = decision self.decisions = decisions
self.calls = 0 self.calls = 0
def __call__(self, **kw): def __call__(self, **kw):
self.calls += 1 self.calls += 1
obj = type("P", (), {})() obj = type("P", (), {})()
obj.decision = self.decision_text obj.decisions = self.decisions
return obj return obj
@@ -81,7 +82,8 @@ def test_promotion_ingests_goal_table():
n = e._harvest_side_tables(lead_page(), None, "q", EVIDENCE) n = e._harvest_side_tables(lead_page(), None, "q", EVIDENCE)
assert n == 0 and len(e._skim_leads) == 1, "queued as lead, not ingested" assert n == 0 and len(e._skim_leads) == 1, "queued as lead, not ingested"
# bounded promotion: LLM says YES (column Mean discharge) # bounded promotion: LLM says YES (column Mean discharge)
e.skim_promote = FakePromote("1: YES Mean discharge") e.skim_promote = FakePromote([PromotionDecision(
table_index=1, promote=True, column="Mean discharge")])
charged = [] charged = []
p = e._promote_leads(EVIDENCE, lambda: charged.append(1)) p = e._promote_leads(EVIDENCE, lambda: charged.append(1))
assert p == 1, "promoted table ingested" assert p == 1, "promoted table ingested"
@@ -100,7 +102,8 @@ def test_promotion_refuses_world_table():
e._current_goal_terms = ["total"] # no overlap with caption/header e._current_goal_terms = ["total"] # no overlap with caption/header
n = e._harvest_side_tables(world_page(), None, "q", EVIDENCE) n = e._harvest_side_tables(world_page(), None, "q", EVIDENCE)
assert n == 0 and len(e._skim_leads) == 1 assert n == 0 and len(e._skim_leads) == 1
e.skim_promote = FakePromote("1: YES Mean discharge") # LLM WRONG e.skim_promote = FakePromote([PromotionDecision(
table_index=1, promote=True, column="Mean discharge")]) # LLM WRONG
p = e._promote_leads(EVIDENCE, lambda: None) p = e._promote_leads(EVIDENCE, lambda: None)
assert p == 0, "code disposes: zero entity overlap -> refused" assert p == 0, "code disposes: zero entity overlap -> refused"
assert all(r.src != "amazon" for r in store.probe(["discharge"])), \ assert all(r.src != "amazon" for r in store.probe(["discharge"])), \
@@ -110,7 +113,7 @@ def test_promotion_refuses_world_table():
def test_no_leads_no_call(): def test_no_leads_no_call():
e = make_expert(KnowledgeStore(":memory:")) e = make_expert(KnowledgeStore(":memory:"))
e.skim_promote = FakePromote("1: YES x") e.skim_promote = FakePromote([])
charged = [] charged = []
p = e._promote_leads(EVIDENCE, lambda: charged.append(1)) p = e._promote_leads(EVIDENCE, lambda: charged.append(1))
assert p == 0 and e.skim_promote.calls == 0 and not charged, \ assert p == 0 and e.skim_promote.calls == 0 and not charged, \
+4 -8
View File
@@ -11,6 +11,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) # repo r
from knowledge.checks import check_candidate, quote_containment, trusted_source from knowledge.checks import check_candidate, quote_containment, trusted_source
from knowledge.chunker import chunk_page from knowledge.chunker import chunk_page
from knowledge.extract import TableChoice
from knowledge.store import KnowledgeStore from knowledge.store import KnowledgeStore
@@ -225,10 +226,8 @@ def test_list_ingest_aggregate(tmp="/tmp/floop_kg_list.sqlite"):
def __call__(self, **kw): def __call__(self, **kw):
class P: pass class P: pass
p = P() p = P()
p.table_index = "1" p.chosen = TableChoice(table_index=1, column="Country",
p.column = "Country" set_name="sovereign states in Europe")
p.set_name = "sovereign states in Europe"
p.origin_question = kw.get("question", "")
return p return p
class FakeStore: class FakeStore:
@@ -286,10 +285,7 @@ def test_list_ingest_aggregate(tmp="/tmp/floop_kg_list.sqlite"):
def __call__(self, **kw): def __call__(self, **kw):
class P: pass class P: pass
p = P() p = P()
p.table_index = "NONE" p.chosen = None
p.column = ""
p.set_name = ""
p.origin_question = ""
return p return p
ke.select_table = FakeNonePicker() ke.select_table = FakeNonePicker()
assert ke._list_from_page(page, "irrelevant", None) is None assert ke._list_from_page(page, "irrelevant", None) is None