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
+171
View File
@@ -0,0 +1,171 @@
"""Wikipedia access via the official MediaWiki API (action API, en.wikipedia only).
Why raw API over the `wikipedia` pip package (tested 2026-10-17): the package
sends params with empty-string values (e.g. redirects: '') which make the API
return an HTML error page instead of JSON, and its default User-Agent is blocked
(403). The official action API called directly with a proper session is reliable
and gives us search + plain-text extracts + revision ids in one place.
Search-first per Emili (2026-10-17): use the Wikipedia search engine to find
articles, then fetch and analyze them chunk by chunk.
"""
from __future__ import annotations
import re
import time
from dataclasses import dataclass, field
import requests
API = "https://en.wikipedia.org/w/api.php"
UA = "floop-bot/0.1 (research; contact: emili@oniricapps.com)"
LANG = "en"
def tables_as_text(wikitext: str, max_tables: int = 3, max_rows: int = 40) -> str:
"""Parse wikitext tables into plain text rows. Used by fetch_rich so
ranking/list articles (whose data lives in tables, not prose) carry
their facts; containment is checked against the ENRICHED text."""
out: list[str] = []
for m in re.finditer(r"\{\|(.*?)\|\}", wikitext, flags=re.S):
if len(out) >= max_tables:
break
rows: list[str] = []
for line in m.group(1).splitlines():
line = line.strip()
if re.fullmatch(r"\|-?", line): # wikitext row separator, not a cell
continue
if line.startswith("!") or line.startswith("|"):
cells = [c.strip().lstrip("!|").strip() for c in line.split("||")]
cells = [re.sub(r"\[\[(?:[^|\]]*\|)?([^\]]+)\]\]", r"\1", c) for c in cells]
cells = [re.sub(r"\{\{[^}]*\|([^}]*)\}\}", r"\1", c) for c in cells]
cells = [re.sub(r"\{\{[^}]*\}\}", "", c) for c in cells]
cells = [re.sub(r"<[^>]+>", "", c).replace("!!", " ").strip() for c in cells if c]
if cells:
rows.append(" | ".join(cells))
if len(rows) >= max_rows:
break
if rows:
out.append(chr(10).join(rows))
return (chr(10) * 2).join(out)
class WikiError(RuntimeError):
pass
@dataclass
class WikiPage:
"""A fetched article: plain text + section structure, verbatim-preserving."""
title: str
pageid: int
url: str
text: str # the full plain-text extract (contains section headings)
fetched_at: str # ISO timestamp
rev_id: int | None = None
@property
def sections(self) -> list[str]:
"""Heading lines as present in the extract (== Section == markers)."""
return re.findall(r"^==+ .+? ==+\s*$", self.text, flags=re.M)
class WikipediaClient:
"""Thin, honest client over the MediaWiki action API. All calls logged by the caller."""
def __init__(self, timeout: int = 15, max_retries: int = 2, backoff: float = 1.5):
self.timeout = timeout
self.max_retries = max_retries
self.backoff = backoff
self.session = requests.Session()
self.session.headers.update({"User-Agent": UA})
self.calls = 0
# ---- low-level ---------------------------------------------------------
def _get(self, **params) -> dict:
params.setdefault("format", "json")
params.setdefault("formatversion", "2")
last_err: Exception | None = None
for attempt in range(self.max_retries + 1):
self.calls += 1
try:
r = self.session.get(API, params=params, timeout=self.timeout)
if r.status_code == 403:
raise WikiError("403 forbidden — check User-Agent policy compliance")
r.raise_for_status()
ct = r.headers.get("content-type", "")
if "json" not in ct:
raise WikiError(f"non-JSON response (content-type={ct}) — API misuse")
return r.json()
except (requests.RequestException, WikiError) as e:
last_err = e
if attempt < self.max_retries:
time.sleep(self.backoff * (attempt + 1))
raise WikiError(f"wikipedia api failed after {self.max_retries + 1} attempts: {last_err}")
# ---- api surface --------------------------------------------------------
def search(self, query: str, limit: int = 5) -> list[str]:
"""Official search: list=search. Returns candidate article titles."""
data = self._get(action="query", list="search", srsearch=query, srlimit=limit)
return [h["title"] for h in data.get("query", {}).get("search", [])]
def summary(self, title: str) -> str:
data = self._get(action="query", titles=title, prop="extracts",
explaintext=True, exintro=True, redirects=True)
pages = data.get("query", {}).get("pages", [])
if not pages:
raise WikiError(f"no page for {title!r}")
pg = pages[0]
if "missing" in pg:
raise WikiError(f"page missing: {title!r}")
return pg.get("extract", "")
def fetch(self, title: str) -> WikiPage:
"""Full plain-text extract with headings preserved (for section chunking)."""
from datetime import datetime, timezone
data = self._get(action="query", titles=title, prop="extracts|info",
explaintext=True, redirects=True, inprop="url")
pages = data.get("query", {}).get("pages", [])
if not pages:
raise WikiError(f"no page for {title!r}")
pg = pages[0]
if "missing" in pg or "extract" not in pg:
raise WikiError(f"page missing or empty: {title!r}")
return WikiPage(
title=pg["title"],
pageid=pg["pageid"],
url=pg.get("fullurl", f"https://{LANG}.wikipedia.org/wiki/{pg['title'].replace(' ', '_')}"),
text=pg["extract"],
fetched_at=datetime.now(timezone.utc).isoformat(timespec="seconds"),
rev_id=pg.get("lastrevid"),
)
def fetch_wikitext(self, title: str) -> str:
"""Raw wikitext (tables live here; the plain extract drops them)."""
data = self._get(action="query", titles=title, prop="revisions",
rvprop="content", rvslots="main", redirects=True)
pages = data.get("query", {}).get("pages", [])
if not pages:
raise WikiError(f"no page for {title!r}")
pg = pages[0]
if "missing" in pg or "revisions" not in pg:
raise WikiError(f"page missing: {title!r}")
return pg["revisions"][0]["slots"]["main"]["content"]
def fetch_rich(self, title: str) -> WikiPage:
"""Extract + table text appended: wikitext tables are parsed into rows
and appended as text so ranking/list questions have their data."""
page = self.fetch(title)
extra = tables_as_text(self.fetch_wikitext(title))
if extra:
page.text = page.text + "\n\n== Tables ==\n" + extra
return page
def disambiguation(self, title: str) -> list[str]:
"""Titles a disambiguation page points to (handles the wiki lib's classic trap)."""
data = self._get(action="query", titles=title, prop="links", pllimit=50,
plnamespace=0, redirects=True)
pages = data.get("query", {}).get("pages", [])
if not pages:
return []
return [l["title"] for l in pages[0].get("links", [])]