Files
floop/code/knowledge/expert.py
T
onibot 6db05fef48 fix(knowledge): cold-start gather — vertical tables, global rank, early exit
Emili's home run failed where the VPS seemed to work: warm-KG illusion; cold path never validated. Reproduced with a wiped KG. Fixes: (1) tables_as_text parses BOTH wikitext layouts (horizontal pipes and one-cell-per-line with row separators) + _clean_cell drops attrs/links/templates; (2) gather searches all queries, dedupes, ranks globally by title relevance, fetches ONE article at a time with EARLY EXIT when the KG answers; (3) hybrid order keeps each query's top-1 slot guaranteed (title relevance buries entity pages like 'Loire'). Also: NameError from refactor caught by baseline fallback; counters accumulate. Cold E2E verified: France (table quote) -> Loire (early exit, 1 article) in 2hops. RUNLOG Run D.
2026-10-17 10:39:34 +02:00

252 lines
12 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)
self._checked = 0
self._merged = 0
# ---- 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])]
e_raw = (pred.entities or "").strip()
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)
# 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]:
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
pages.append(page)
# 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)
self._process_page(page, question, kws, charge_llm)
answer = self._answer_from_rows(
question, self.store.probe(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 {**answer, "source": "knowledge_graph",
"stats": {"pages": [p.title for p in pages]}}
# 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) and answer from the merged KG
rows = self.store.probe(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 {**answer, "source": src,
"stats": {"checked": self._checked, "merged": self._merged,
"pages": [p.title for p in pages],
"elapsed_s": round(time.time() - t0, 1)}}
def _process_page(self, page: WikiPage, question: str, kws: list[str],
charge_llm) -> int:
"""Chunk -> gate -> extract -> check -> merge for ONE page. Returns
number of candidates merged this page. Counters ACCUMULATE on self."""
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):
self._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)
self._merged += 1
return self._merged
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(),
}