feat(knowledge): real Wikipedia vertical with containment-checked KG

knowledge/: wiki.py (official MediaWiki API, own session+UA; fetch_rich appends wikitext tables as text - plain extracts drop them), chunker.py (section-aware, level paths), checks.py (verbatim containment, quote-aware), store.py (SQLite append-only, 4 contradiction cases, probe by entity AND relation with stemming), extract.py (dspy Signatures: TRANSLATE resolves pronouns from context and emits queries+entities, EXTRACT per chunk, ANSWER from KG rows), expert.py (the pipeline: KG-first probe -> gap -> translate -> search -> fetch_rich -> chunk -> gate -> extract -> check -> merge -> re-probe -> answer). Wiring: KnowledgeEngine in floop/engine.py (machine injects charge+modules at call time; baseline fallback on pipeline failure), machine routes knowledge questions to it, config.yaml knowledge: block. E2E verified live: Loire length answered from KG with zero network; the 2-hop EU-river question resolved France (population table row quote) -> Loire (KG hit) in 12 calls/75s. Six live-run bugs closed (wiki lib 403/HTML, dropped tables, pipes-in-quotes parse, gate stemming, relation probe, pronoun context). RUNLOG Run C added; code/README honest map updated. Tests 17/17.
This commit is contained in:
2026-10-16 23:19:09 +02:00
parent aecaac01eb
commit 9094b2aec0
15 changed files with 1111 additions and 13 deletions
+61
View File
@@ -89,4 +89,65 @@ class UserRequestEngine:
provenance=prov,
verified=False,
note="needs_user_input",
)
class KnowledgeEngine:
"""The real knowledge vertical: KG probe -> gather -> containment-checked
extraction -> answer from quoted rows (knowledge/expert.py).
The machine injects `charge` (budget) and `modules` (baseline fallback)
at call time — the budget owner is always the machine.
Falls back to the baseline LLM expert on any pipeline failure (network,
store): the machine never dies because the web did."""
def __init__(self, knowledge_expert) -> None:
self.ke = knowledge_expert
self.charge = None # set by the machine at call time
self.modules = None # set by the machine at call time
self.name = "knowledge"
def run(self, qid, question, parent_question, table, answer_type, streams=None):
charge = self.charge or (lambda: None)
# the machine's context: rows already answered (the question may reference them)
ev_lines = []
for r in table.rows():
val = r.payload.get("value", "")
if val and val.upper() != "UNKNOWN":
ev_lines.append(f"{r.eid}: {r.payload.get('value', '')} (answers: {r.qid})")
evidence = chr(10).join(ev_lines[:6])
try:
ans = self.ke.answer_question(question, parent_question=parent_question,
evidence=evidence, charge_llm=charge)
except Exception as e: # noqa: BLE001 — fallback honesty: log, don't die
if streams:
streams.state(f"knowledge pipeline failed ({e}); baseline fallback")
fallback = LLMExpertEngine(self.modules, charge, expert_kind="knowledge")
return fallback.run(qid, question, parent_question, table,
answer_type, streams=streams)
src = ans.get("source", "wikipedia_miss")
value = ans.get("value", "UNKNOWN")
payload = {"value": value}
if ans.get("quote"):
payload["quote"] = ans["quote"]
if ans.get("url"):
payload["url"] = ans["url"]
prov = {"expert": "knowledge", "source": src,
"note": ("source-verified: verbatim containment in trusted doc"
if ans.get("quote") else "no quote — unverified")}
if parent_question:
prov["parent_question"] = parent_question
note = "" if value.upper() != "UNKNOWN" else "knowledge returned UNKNOWN"
if streams is not None:
streams.output("EXPERT",
f"value={value} quote={(ans.get('quote') or '')[:80]} [{src}]")
return EvidenceRow(
qid=qid,
answer_type=answer_type,
payload=payload,
engine="knowledge",
trace=[f"kg pipeline: source={src} conf={ans.get('confidence', '?')}"],
provenance=prov,
verified=False, # the prover is still a stub; the quote is source-verified
note=note,
)
+19 -7
View File
@@ -51,7 +51,8 @@ class FloopRun:
def __init__(self, question: str, budget: Budget, depth: int = 0,
modules: FloopModules | None = None, parent_goal: str = "",
streams: RunStreams | None = None) -> None:
streams: RunStreams | None = None,
knowledge_engine=None) -> None:
self.query = question
self.budget = budget
self.depth = depth
@@ -62,6 +63,7 @@ class FloopRun:
self.table = EvidenceTable()
self.stack = QuestionStack(question)
self.user_engine = UserRequestEngine(self.modules)
self.knowledge_engine = knowledge_engine # None -> baseline LLM expert
self.notes: list[str] = []
self.engine_calls = 0
@@ -146,11 +148,20 @@ class FloopRun:
q.status = "failed"
q.reason = "user expert not wired (draft)"
elif attendant in EXPERT_ENGINES:
engine = LLMExpertEngine(self.modules, self._charge, expert_kind=attendant)
self.streams.call("EXPERT", f"{attendant} on {q.qid}: {q.text[:80]}",
think=self.tprefix + f"asking {attendant}: {q.text[:90]}")
row = engine.run(q.qid, instantiate(q.text, self.table),
self.query, self.table, q.answer_type, streams=self.streams)
if attendant == "knowledge" and self.knowledge_engine is not None:
self.knowledge_engine.charge = self._charge
self.knowledge_engine.modules = self.modules
self.streams.call("EXPERT", f"knowledge pipeline on {q.qid}: {q.text[:80]}",
think=self.tprefix + f"asking knowledge (KG pipeline): {q.text[:90]}")
row = self.knowledge_engine.run(q.qid, instantiate(q.text, self.table),
self.query, self.table, q.answer_type,
streams=self.streams)
else:
engine = LLMExpertEngine(self.modules, self._charge, expert_kind=attendant)
self.streams.call("EXPERT", f"{attendant} on {q.qid}: {q.text[:80]}",
think=self.tprefix + f"asking {attendant}: {q.text[:90]}")
row = engine.run(q.qid, instantiate(q.text, self.table),
self.query, self.table, q.answer_type, streams=self.streams)
self.engine_calls += 1
self._append_checked(row, q)
else:
@@ -172,7 +183,8 @@ class FloopRun:
child = FloopRun(question=instantiate(q.text, self.table),
budget=child_budget, depth=self.depth + 1,
modules=self.modules, parent_goal=self.query,
streams=self.streams)
streams=self.streams,
knowledge_engine=self.knowledge_engine)
report = child.run()
self.budget.llm_calls += child_budget.llm_calls
self.streams.state(