Files
floop/code/knowledge/expert.py
T
onibot 9094b2aec0 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.
2026-10-16 23:19:09 +02:00

195 lines
9.2 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
from .chunker import chunk_page
from .extract import (AnswerFromKG, ExtractSignature, TranslateSignature,
parse_facts)
from .store import KnowledgeStore
from .wiki import WikipediaClient, WikiPage
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
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)
# ---- 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]
# ---- the pipeline --------------------------------------------------------
def answer_question(self, question: str, parent_question: str = "",
evidence: str = "", charge_llm=None) -> 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)
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)
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])]
self._log(f"translate -> queries {queries}", think=True)
pages: list[WikiPage] = []
seen: set[str] = set()
for query in queries:
candidates = self.client.search(query, limit=self.cfg.max_search_results)
self._log(f"wiki search ({query!r}): {candidates}", think=True)
for title in candidates:
if len(pages) >= self.cfg.max_articles or title in seen:
continue
seen.add(title)
try:
pages.append(self.client.fetch_rich(title))
except Exception as e: # noqa: BLE001 — network honesty: log and continue
self._log(f"fetch failed: {title}: {e}")
# 5-7. chunk -> extract -> check -> merge (lexical gate on chunks)
checked = 0
merged = 0
for page in pages:
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)][: self.cfg.max_chunks_extracted]
self._log(f"{page.title}: {len(chunks)} chunks, {len(gated)} gated in")
for chunk in gated:
if charge_llm:
charge_llm()
raw = self.extract(question=question, heading=chunk.heading_path, text=chunk.text)
for cand in parse_facts(raw.facts):
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)
merged += 1
# 8. re-probe (same seeds) and answer from the merged KG
rows = self.store.probe(probe_seeds)
self._log(f"merged {merged}/{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": {"checked": checked, "merged": merged,
"pages": [p.title for p in pages],
"elapsed_s": round(time.time() - t0, 1)}}
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(),
}