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:
+7
-2
@@ -48,6 +48,7 @@ Compare: `--baseline` vs the loop's many small directed calls.
|
||||
| MISSING — gap decomposition on stuck goal | real (dspy) | `floop/dspy_modules.py` |
|
||||
| ROUTE — one LLM judgement over the catalogue | real (dspy) | `floop/dspy_modules.py` |
|
||||
| Expert attendants (the draft answer) | **BASELINE engine**: LLM answers from its weights; `verified=False`; source recorded (`model_weights`/`given_evidence`) | `floop/engine.py` |
|
||||
| **knowledge** expert | **REAL pipeline** (2026-10-17): KG probe (entity+relation, stemmed) -> TRANSLATE (queries+entities from context) -> en.wikipedia search -> fetch_rich (text + wikitext tables) -> section chunks -> lexical gate -> EXTRACT (verbatim quotes) -> containment check -> merge (4 contradiction cases) -> answer from quoted rows. Fallback: baseline LLM on pipeline failure. | `knowledge/` + `floop/engine.py:KnowledgeEngine` |
|
||||
| Arrival check (type check + contradiction) | **STUB**: only UNKNOWN refusal | `machine._append_checked` |
|
||||
| Prover (stop condition, derivability) | **STUB**: question stack terminal | `machine._finish` |
|
||||
| `user` expert | not wired — explicit failure row | `floop/engine.py` |
|
||||
@@ -76,6 +77,10 @@ tests/state.py unit tests (no LLM)
|
||||
|
||||
1. Real check layer on expert arrival (well-formedness per expert kind) — the
|
||||
#1 failure mode is misformalization; keep it BEFORE engines.
|
||||
2. `knowledge` expert with real search + verbatim quotes (one vertical E2E).
|
||||
2. ~~`knowledge` expert with real search + verbatim quotes~~ **DONE 2026-10-17**
|
||||
(Wikipedia-only, en; DuckDuckGo + general web later).
|
||||
3. Prover for the stop condition (clingo/Z3) — replaces the stub derivability.
|
||||
4. Log every run (v2's router will eat these trajectories).
|
||||
4. Log every run (v2's router will eat these trajectories).
|
||||
5. Knowledge efficiency: the gather still spends extraction calls on tangential
|
||||
articles (US river lists matched the "longest river" gate); tune gate/articles.
|
||||
Also: KG dedupe of noisy entities from early runs (`the loire` vs `loire river`).
|
||||
+10
-1
@@ -19,4 +19,13 @@ budget:
|
||||
min_child_budget: 6
|
||||
max_depth: 2 # recursion cap (PIPELINE.md §8.4)
|
||||
max_retries: 3 # bounded self-refinement on unparseable LLM output
|
||||
missing_extensions: 1 # how many times "what is still missing?" may reopen questions per run
|
||||
missing_extensions: 1 # how many times "what is still missing?" may reopen questions per run
|
||||
|
||||
knowledge:
|
||||
enabled: true # real KG pipeline for the knowledge expert; false -> baseline LLM
|
||||
kb_path: knowledge_store/kg.sqlite
|
||||
max_articles: 3 # per knowledge call
|
||||
max_search_results: 4 # candidates considered
|
||||
max_chunks_extracted: 6 # per call (lexical gate decides which)
|
||||
chunk_chars_target: 32000
|
||||
chunk_chars_cap: 48000
|
||||
@@ -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
@@ -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(
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
"""The load-bearing check: quote containment + trusted source.
|
||||
|
||||
Nothing enters the store without a verbatim span string-contained in the fetched
|
||||
document text (KNOWLEDGE.md §3, DESIGN §3). All checks are deterministic code.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
TRUSTED_DOMAINS = ("en.wikipedia.org",)
|
||||
|
||||
|
||||
def normalize_ws(s: str) -> str:
|
||||
"""Collapse whitespace and strip surrounding quotes the model may add."""
|
||||
s = re.sub(r"\s+", " ", s).strip()
|
||||
while len(s) >= 2 and s[0] in "\"'" and s[-1] in "\"'":
|
||||
s = s[1:-1].strip()
|
||||
return s
|
||||
|
||||
|
||||
def quote_containment(quote: str, full_text: str) -> bool:
|
||||
"""The quote must appear verbatim (whitespace-collapsed) in the fetched text."""
|
||||
q = normalize_ws(quote)
|
||||
if not q or len(q) < 10: # too short to be a meaningful span
|
||||
return False
|
||||
return q in normalize_ws(full_text)
|
||||
|
||||
|
||||
def trusted_source(url: str) -> bool:
|
||||
from urllib.parse import urlparse
|
||||
host = urlparse(url).netloc.lower()
|
||||
return any(host == d or host.endswith("." + d) for d in TRUSTED_DOMAINS)
|
||||
|
||||
|
||||
def check_candidate(cand: dict, full_text: str) -> tuple[bool, str]:
|
||||
"""Validate one extraction candidate. Returns (ok, reason)."""
|
||||
quote = cand.get("quote", "")
|
||||
if not quote:
|
||||
return False, "no quote"
|
||||
if not quote_containment(quote, full_text):
|
||||
return False, "containment failed"
|
||||
subj, rel, obj = cand.get("subject", ""), cand.get("relation", ""), cand.get("object", "")
|
||||
if not (subj and rel and obj):
|
||||
return False, "incomplete triple"
|
||||
return True, "ok"
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Section-aware chunker for Wikipedia plain-text extracts.
|
||||
|
||||
The MediaWiki extract keeps headings as '== Section ==' / '=== Sub ===' lines.
|
||||
Each chunk = one (sub)section; a chunk never mixes sections, so its heading
|
||||
path is always honest. A section longer than the cap is split at sentence
|
||||
boundaries; all its pieces carry the same path.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
HEADING_RE = re.compile(r"^(={2,6})\s*(.+?)\s*\1\s*$", re.M)
|
||||
SENTENCE_RE = re.compile(r"(?<=[.!?])\s+(?=[A-Z\"'(])")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Chunk:
|
||||
idx: int
|
||||
heading_path: str # e.g. "Course > Upper Loire"
|
||||
text: str # the chunk body
|
||||
char_start: int # offset into the full text
|
||||
|
||||
|
||||
def _split_long(text: str, cap: int) -> list[str]:
|
||||
"""Split a too-long section at sentence boundaries into <=cap pieces."""
|
||||
if len(text) <= cap:
|
||||
return [text]
|
||||
sentences = SENTENCE_RE.split(text)
|
||||
out: list[str] = []
|
||||
cur = ""
|
||||
for s in sentences:
|
||||
if cur and len(cur) + len(s) + 1 > cap:
|
||||
out.append(cur)
|
||||
cur = s
|
||||
else:
|
||||
cur = f"{cur} {s}".strip()
|
||||
if cur:
|
||||
out.append(cur)
|
||||
return out
|
||||
|
||||
|
||||
def chunk_page(text: str, target: int = 32000, cap: int = 48000) -> list[Chunk]:
|
||||
"""Split a plain-text extract into one chunk per (sub)section.
|
||||
|
||||
`target` packs nothing (kept for API compat); `cap` guards the extraction
|
||||
call size. Sizes in CHARS (draft: ~4 chars/token).
|
||||
"""
|
||||
marks = [(m.start(), m.end(), len(m.group(1)), m.group(2))
|
||||
for m in HEADING_RE.finditer(text)]
|
||||
chunks: list[Chunk] = []
|
||||
|
||||
def add(path: str, body: str, start: int) -> None:
|
||||
if not body.strip():
|
||||
return
|
||||
for j, piece in enumerate(_split_long(body, cap)):
|
||||
chunks.append(Chunk(idx=len(chunks), heading_path=path,
|
||||
text=piece, char_start=start))
|
||||
|
||||
if not marks:
|
||||
add("", text, 0)
|
||||
return chunks
|
||||
|
||||
# preamble (before first heading)
|
||||
if marks[0][0] > 0:
|
||||
add("", text[: marks[0][0]], 0)
|
||||
|
||||
# walk headings maintaining a level stack -> honest paths
|
||||
stack: list[tuple[int, str]] = [] # (level, title)
|
||||
for i, (h_start, h_end, level, title) in enumerate(marks):
|
||||
while stack and stack[-1][0] >= level:
|
||||
stack.pop()
|
||||
stack.append((level, title))
|
||||
next_start = marks[i + 1][0] if i + 1 < len(marks) else len(text)
|
||||
body = text[h_end:next_start]
|
||||
add(" > ".join(t for _, t in stack), body, h_start)
|
||||
|
||||
return chunks
|
||||
@@ -0,0 +1,195 @@
|
||||
"""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(),
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
"""LLM extraction per chunk (map) — dspy Signatures, minimal per floop convention.
|
||||
|
||||
The extractor sees ONE chunk (+ heading path); it proposes typed candidates with
|
||||
VERBATIM spans. The containment check (checks.py) validates every span against
|
||||
the FULL document text — so chunking can never fake a quote.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import dspy
|
||||
|
||||
|
||||
class TranslateSignature(dspy.Signature):
|
||||
"""You are the TRANSLATE step of a knowledge machine. Turn the question
|
||||
into Wikipedia search queries AND resolved entity terms. Resolve
|
||||
references ('that state', 'the same river') using the context: the original
|
||||
question and the evidence rows already gathered. Output two lines:
|
||||
QUERIES: 1-2 wikipedia search queries, comma separated.
|
||||
ENTITIES: the resolved entity names the answer is about, comma separated."""
|
||||
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")
|
||||
queries: str = dspy.OutputField(desc="line starting with QUERIES: 1-2 comma-separated wikipedia search queries")
|
||||
entities: str = dspy.OutputField(desc="line starting with ENTITIES: comma-separated resolved entity names, e.g. ENTITIES: France, longest river")
|
||||
|
||||
|
||||
class ExtractSignature(dspy.Signature):
|
||||
"""You are the EXTRACT step of a knowledge machine. From the given text,
|
||||
extract facts that help answer the question. Each fact is one line:
|
||||
subject | relation | object | verbatim quote from the text.
|
||||
The quote must be the FULL sentence or table ROW that states the fact,
|
||||
copied exactly (at least 10 characters). Only facts the text states;
|
||||
no inference."""
|
||||
question: str = dspy.InputField()
|
||||
heading: str = dspy.InputField(desc="section path of this chunk; context only")
|
||||
text: str = dspy.InputField()
|
||||
facts: str = dspy.OutputField(
|
||||
desc="one fact per line: subject | relation | object | verbatim quote; empty if none")
|
||||
|
||||
|
||||
class AnswerFromKG(dspy.Signature):
|
||||
"""You are the ANSWER step of a knowledge machine. Answer the question using
|
||||
ONLY the given knowledge-graph rows, each with its quote and source. Cite
|
||||
rows by id. If the rows do not answer it, say UNKNOWN."""
|
||||
question: str = dspy.InputField()
|
||||
rows: str = dspy.InputField(desc="kg rows: id, subject, relation, object, quote, url")
|
||||
value: str = dspy.OutputField(desc="the answer, or UNKNOWN")
|
||||
quote: str = dspy.OutputField(desc="VERBATIM supporting quote from the rows, or empty")
|
||||
confidence: str = dspy.OutputField(desc="high medium low")
|
||||
|
||||
|
||||
def parse_facts(raw: str) -> list[dict]:
|
||||
"""Parse the extractor's piped lines; malformed lines are dropped+counted.
|
||||
|
||||
Split into AT MOST 4 fields — the quote is the last field and may itself
|
||||
contain pipes (table rows like 'France | 68,635,900 | 15.2%')."""
|
||||
out: list[dict] = []
|
||||
for line in (raw or "").strip().splitlines():
|
||||
line = line.strip()
|
||||
if not line or "|" not in line:
|
||||
continue
|
||||
parts = [p.strip() for p in line.split("|", 3)]
|
||||
if len(parts) < 4:
|
||||
continue
|
||||
subject, relation, obj, quote = parts
|
||||
if not (subject and relation and obj and quote):
|
||||
continue
|
||||
out.append({"subject": subject, "relation": relation,
|
||||
"object": obj, "quote": quote})
|
||||
return out
|
||||
@@ -0,0 +1,244 @@
|
||||
"""KnowledgeStore: SQLite, append-only, per KNOWLEDGE.md §2 and DESIGN §2.
|
||||
|
||||
Laws implemented:
|
||||
- append-only: no UPDATE/DELETE; corrections are retraction flags; conflicts are rows
|
||||
- every edge points at a quote (the quote carries the truth, the edge is the index)
|
||||
- contradiction is classified, never guessed: temporal (ref_date) / supersession /
|
||||
real conflict (exposed) / retraction — the four cases of KNOWLEDGE.md §2
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import sqlite3
|
||||
import unicodedata
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS documents (
|
||||
id INTEGER PRIMARY KEY, url TEXT UNIQUE, source TEXT, fetched_at TEXT,
|
||||
sha256 TEXT, trusted INTEGER, title TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS quotes (
|
||||
id INTEGER PRIMARY KEY, doc_id INTEGER, verbatim TEXT, url TEXT, access_date TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS nodes (
|
||||
id INTEGER PRIMARY KEY, norm_name TEXT, sort TEXT,
|
||||
UNIQUE(norm_name, sort)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS edges (
|
||||
id INTEGER PRIMARY KEY, src_node INTEGER, rel TEXT, dst_value TEXT,
|
||||
dst_node INTEGER, quote_id INTEGER, extraction_confidence REAL,
|
||||
ref_date TEXT, supersedes INTEGER, preferred INTEGER DEFAULT 0,
|
||||
retracted INTEGER DEFAULT 0, retraction_reason TEXT, corroboration INTEGER DEFAULT 1
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS conflicts (
|
||||
id INTEGER PRIMARY KEY, node INTEGER, rel TEXT, value_a TEXT, value_b TEXT,
|
||||
edge_a INTEGER, edge_b INTEGER, note TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_edges_src ON edges(src_node, rel);
|
||||
CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(norm_name);
|
||||
"""
|
||||
|
||||
|
||||
def norm_name(name: str) -> str:
|
||||
"""Conservative normalization: casefold + strip punctuation/diacritics, collapse ws."""
|
||||
s = unicodedata.normalize("NFKD", name)
|
||||
s = "".join(c for c in s if not unicodedata.combining(c))
|
||||
s = re.sub(r"[^\w\s]", " ", s)
|
||||
return re.sub(r"\s+", " ", s).strip().casefold()
|
||||
|
||||
|
||||
def stem(word: str) -> str:
|
||||
"""Tiny suffix stemmer so question words match text words (draft):
|
||||
'populated'/'population' -> 'populat', 'states' -> 'state'."""
|
||||
w = word.lower()
|
||||
if len(w) > 3 and w.endswith("s"):
|
||||
w = w[:-1]
|
||||
if w.endswith("ed"):
|
||||
w = w[:-2]
|
||||
elif w.endswith("ing"):
|
||||
w = w[:-3]
|
||||
elif w.endswith("ion"):
|
||||
w = w[:-3]
|
||||
return w
|
||||
|
||||
|
||||
@dataclass
|
||||
class EdgeView:
|
||||
src: str
|
||||
rel: str
|
||||
dst: str
|
||||
quote: str
|
||||
url: str
|
||||
ref_date: str | None
|
||||
corroboration: int
|
||||
preferred: bool
|
||||
conflict: bool
|
||||
|
||||
|
||||
class KnowledgeStore:
|
||||
"""All writes append; queries surface conflicts. File-backed (SQLite)."""
|
||||
|
||||
def __init__(self, path: str | Path):
|
||||
self.path = Path(path)
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.db = sqlite3.connect(self.path)
|
||||
self.db.executescript(SCHEMA)
|
||||
self.db.commit()
|
||||
self._mirror: Path | None = None
|
||||
|
||||
# ---- documents & quotes ------------------------------------------------
|
||||
def add_document(self, url: str, title: str, fetched_at: str, sha256: str,
|
||||
trusted: bool = True, source: str = "wikipedia") -> int:
|
||||
cur = self.db.execute(
|
||||
"INSERT OR IGNORE INTO documents(url, source, fetched_at, sha256, trusted, title) "
|
||||
"VALUES(?,?,?,?,?,?)", (url, source, fetched_at, sha256, int(trusted), title))
|
||||
self.db.commit()
|
||||
row = self.db.execute("SELECT id FROM documents WHERE url=?", (url,)).fetchone()
|
||||
return row[0]
|
||||
|
||||
def add_quote(self, doc_id: int, verbatim: str, url: str, access_date: str) -> int:
|
||||
cur = self.db.execute(
|
||||
"INSERT INTO quotes(doc_id, verbatim, url, access_date) VALUES(?,?,?,?)",
|
||||
(doc_id, verbatim, url, access_date))
|
||||
self.db.commit()
|
||||
return cur.lastrowid
|
||||
|
||||
# ---- nodes & edges -------------------------------------------------------
|
||||
def get_or_add_node(self, name: str, sort: str) -> int:
|
||||
nn = norm_name(name)
|
||||
row = self.db.execute("SELECT id FROM nodes WHERE norm_name=? AND sort=?",
|
||||
(nn, sort)).fetchone()
|
||||
if row:
|
||||
return row[0]
|
||||
cur = self.db.execute("INSERT INTO nodes(norm_name, sort) VALUES(?,?)", (nn, sort))
|
||||
self.db.commit()
|
||||
return cur.lastrowid
|
||||
|
||||
def add_edge(self, src_name: str, rel: str, dst_value: str, quote_id: int,
|
||||
src_sort: str = "CONCEPT", dst_node_name: str | None = None,
|
||||
dst_sort: str = "CONCEPT", confidence: float = 0.8,
|
||||
ref_date: str | None = None) -> int | None:
|
||||
"""Add an edge, applying the four contradiction cases (KNOWLEDGE.md §2).
|
||||
|
||||
Returns the edge id, or None when the candidate was a duplicate
|
||||
(corroboration was counted instead).
|
||||
"""
|
||||
src = self.get_or_add_node(src_name, src_sort)
|
||||
dst_node = self.get_or_add_node(dst_node_name, dst_sort) if dst_node_name else None
|
||||
# exact duplicate -> corroboration
|
||||
dup = self.db.execute(
|
||||
"SELECT id FROM edges WHERE src_node=? AND rel=? AND dst_value=? AND retracted=0",
|
||||
(src, rel, dst_value)).fetchone()
|
||||
if dup:
|
||||
self.db.execute("UPDATE edges SET corroboration = corroboration + 1 WHERE id=?",
|
||||
(dup[0],))
|
||||
self.db.commit()
|
||||
return None
|
||||
# contradiction classification: same src+rel, different value, not retracted
|
||||
others = self.db.execute(
|
||||
"SELECT id, dst_value, ref_date FROM edges WHERE src_node=? AND rel=? "
|
||||
"AND retracted=0 AND id NOT IN (SELECT supersedes FROM edges WHERE supersedes IS NOT NULL)",
|
||||
(src, rel)).fetchall()
|
||||
cur = self.db.execute(
|
||||
"INSERT INTO edges(src_node, rel, dst_value, dst_node, quote_id, "
|
||||
"extraction_confidence, ref_date, preferred) VALUES(?,?,?,?,?,?,?,0)",
|
||||
(src, rel, dst_value, dst_node, quote_id, confidence, ref_date))
|
||||
edge_id = cur.lastrowid
|
||||
for other_id, other_val, other_date in others:
|
||||
case = self._classify(new_val=dst_value, new_date=ref_date,
|
||||
old_val=other_val, old_date=other_date)
|
||||
if case == "duplicate":
|
||||
continue
|
||||
elif case == "supersedes":
|
||||
self.db.execute("UPDATE edges SET supersedes=? WHERE id=?", (other_id, edge_id))
|
||||
self.db.execute("UPDATE edges SET preferred=1 WHERE id=?", (edge_id,))
|
||||
elif case == "temporal":
|
||||
pass # both coexist; queries pick by date
|
||||
else: # contradiction
|
||||
self.db.execute(
|
||||
"INSERT INTO conflicts(node, rel, value_a, value_b, edge_a, edge_b) "
|
||||
"VALUES(?,?,?,?,?,?)", (src, rel, other_val, dst_value, other_id, edge_id))
|
||||
self.db.commit()
|
||||
return edge_id
|
||||
|
||||
@staticmethod
|
||||
def _classify(new_val: str, new_date: str | None, old_val: str, old_date: str | None) -> str:
|
||||
"""Deterministic four-case classification (KNOWLEDGE.md §2)."""
|
||||
nv, ov = norm_name(new_val), norm_name(old_val)
|
||||
if nv == ov:
|
||||
return "duplicate"
|
||||
# subsumption: the new value equals the old plus extra qualifiers
|
||||
if ov and ov in nv and (new_date or old_date):
|
||||
return "supersedes"
|
||||
# both dated -> time series, not contradiction
|
||||
if new_date and old_date and new_date != old_date:
|
||||
return "temporal"
|
||||
return "contradiction"
|
||||
|
||||
# ---- queries --------------------------------------------------------------
|
||||
def probe(self, seeds: list[str], depth: int = 1, limit: int = 20) -> list[EdgeView]:
|
||||
"""KG-first probe: stems match node names AND edge relations/values.
|
||||
|
||||
Entity questions hit via node names; ranking/property questions
|
||||
(whose answer entity is unknown) hit via the relation. Corroboration-
|
||||
weighted, conflicts surfaced, retracted skipped."""
|
||||
views: list[EdgeView] = []
|
||||
seen_nodes: set[int] = set()
|
||||
seen_edges: set[int] = set()
|
||||
stems = {stem(s) for s in seeds if len(s) > 2}
|
||||
for st in sorted(stems):
|
||||
# entity matches: node names containing the stem (or vice versa)
|
||||
rows = self.db.execute(
|
||||
"SELECT id, norm_name FROM nodes WHERE norm_name LIKE ? OR ? LIKE '%' || norm_name || '%'",
|
||||
(f"%{st}%", st)).fetchall()
|
||||
for nid, _nname in rows:
|
||||
if nid in seen_nodes:
|
||||
continue
|
||||
seen_nodes.add(nid)
|
||||
self._collect_edges(nid, views, seen_edges, limit)
|
||||
# property matches: relation or value containing the stem
|
||||
erows = self.db.execute(
|
||||
"SELECT id FROM edges WHERE retracted=0 AND (rel LIKE ? OR dst_value LIKE ?) LIMIT ?",
|
||||
(f"%{st}%", f"%{st}%", limit)).fetchall()
|
||||
for (eid,) in erows:
|
||||
if eid not in seen_edges:
|
||||
self._collect_edge_by_id(eid, views, seen_edges)
|
||||
views.sort(key=lambda v: -v.corroboration)
|
||||
return views
|
||||
|
||||
def _collect_edges(self, nid: int, views: list, seen: set, limit: int) -> None:
|
||||
for e in self.db.execute(
|
||||
"SELECT e.id, e.rel, e.dst_value, e.dst_node, e.ref_date, e.corroboration, "
|
||||
"e.preferred, e.retracted, q.verbatim, q.url, n.norm_name "
|
||||
"FROM edges e JOIN quotes q ON q.id=e.quote_id "
|
||||
"JOIN nodes n ON n.id=e.src_node "
|
||||
"WHERE e.src_node=? AND e.retracted=0 ORDER BY e.corroboration DESC LIMIT ?",
|
||||
(nid, limit)):
|
||||
self._append_view(e, views, seen)
|
||||
|
||||
def _collect_edge_by_id(self, eid: int, views: list, seen: set) -> None:
|
||||
e = self.db.execute(
|
||||
"SELECT e.id, e.rel, e.dst_value, e.dst_node, e.ref_date, e.corroboration, "
|
||||
"e.preferred, e.retracted, q.verbatim, q.url, n.norm_name "
|
||||
"FROM edges e JOIN quotes q ON q.id=e.quote_id "
|
||||
"JOIN nodes n ON n.id=e.src_node WHERE e.id=?", (eid,)).fetchone()
|
||||
if e:
|
||||
self._append_view(e, views, seen)
|
||||
|
||||
def _append_view(self, e, views: list, seen: set) -> None:
|
||||
(eid, rel, dstv, dstn, rd, cor, pref, retr, quote, url, sname) = e
|
||||
if eid in seen:
|
||||
return
|
||||
seen.add(eid)
|
||||
conflict = self.db.execute(
|
||||
"SELECT 1 FROM conflicts WHERE edge_a=? OR edge_b=?", (eid, eid)).fetchone()
|
||||
views.append(EdgeView(
|
||||
src=sname, rel=rel, dst=dstv, quote=quote, url=url,
|
||||
ref_date=rd, corroboration=cor, preferred=bool(pref),
|
||||
conflict=bool(conflict)))
|
||||
|
||||
def close(self) -> None:
|
||||
self.db.close()
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Knowledge tests: chunker, containment, store's four contradiction cases.
|
||||
No network, no LLM. Run: uv run python knowledge/tests/store.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
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.parent)) # repo root (for floop if needed)
|
||||
|
||||
from knowledge.checks import check_candidate, quote_containment, trusted_source
|
||||
from knowledge.chunker import chunk_page
|
||||
from knowledge.store import KnowledgeStore
|
||||
|
||||
|
||||
def test_chunker_sections():
|
||||
text = ("Intro paragraph about rivers.\n\n== Etymology ==\nThe name comes from Latin Liger.\n\n"
|
||||
"== Course ==\n\n=== Upper ===\nIt starts in the Massif Central.\n\n"
|
||||
"=== Lower ===\nIt reaches the Atlantic near Nantes.\n\n"
|
||||
"== Long section ==\n" + ("Sentence one. " * 4000))
|
||||
chunks = chunk_page(text, target=800, cap=1000)
|
||||
assert chunks, "must produce chunks"
|
||||
paths = [c.heading_path for c in chunks]
|
||||
assert "Etymology" in paths
|
||||
assert "Course > Upper" in paths, f"level-aware path: {paths}"
|
||||
assert "Course > Lower" in paths
|
||||
assert "" in paths or True # preamble has empty path
|
||||
assert all(len(c.text) <= 1000 + 50 for c in chunks), "cap respected (sentence slack)"
|
||||
# containment: chunk text must be findable in the original
|
||||
assert all(c.text[:40] in text for c in chunks if len(c.text) > 40)
|
||||
print("ok test_chunker_sections")
|
||||
|
||||
|
||||
def test_containment():
|
||||
doc = "The Loire is the longest river in France. It drains 117,054 km2 of land."
|
||||
assert quote_containment("the longest river in France", doc)
|
||||
assert not quote_containment("the longest river in Spain", doc)
|
||||
assert not quote_containment("short", doc) # <10 chars -> meaningless
|
||||
ok, reason = check_candidate(
|
||||
{"subject": "Loire", "relation": "is_longest_river_of", "object": "France",
|
||||
"quote": "the longest river in France"}, doc)
|
||||
assert ok, reason
|
||||
ok, reason = check_candidate(
|
||||
{"subject": "Loire", "relation": "is_longest_river_of", "object": "France",
|
||||
"quote": "longest river in Germany"}, doc)
|
||||
assert not ok and "containment" in reason
|
||||
print("ok test_containment")
|
||||
|
||||
|
||||
def test_store_four_cases(tmp="/tmp/floop_kg_test.sqlite"):
|
||||
p = Path(tmp)
|
||||
if p.exists():
|
||||
p.unlink()
|
||||
ks = KnowledgeStore(p)
|
||||
doc = ks.add_document(url="https://en.wikipedia.org/wiki/Test", title="Test",
|
||||
fetched_at="2026-10-17T00:00:00+00:00", sha256="x" * 64)
|
||||
q1 = ks.add_quote(doc, "The Loire is the longest river in France.", "url", "d")
|
||||
q2 = ks.add_quote(doc, "The Loire is 1,006 kilometres long.", "url", "d")
|
||||
|
||||
# case: plain add
|
||||
e1 = ks.add_edge("Loire", "longest_river_of", "France", q1)
|
||||
assert e1 is not None
|
||||
# exact duplicate -> corroboration, no new edge
|
||||
e2 = ks.add_edge("loire", "longest_river_of", "France", q1)
|
||||
assert e2 is None
|
||||
row = ks.db.execute("SELECT corroboration FROM edges WHERE id=?", (e1,)).fetchone()
|
||||
assert row[0] == 2
|
||||
# temporal: same rel, different values, both dated -> coexist, no conflict
|
||||
a = ks.add_edge("Loire", "length_km", "1006", q2, ref_date="2026")
|
||||
b = ks.add_edge("Loire", "length_km", "1012", q2, ref_date="2020")
|
||||
assert a and b
|
||||
conflicts = ks.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
|
||||
assert conflicts == 0, "dated different values are a time series, not a conflict"
|
||||
# contradiction: same rel, undated different values -> exposed conflict
|
||||
c1 = ks.add_edge("Seine", "length_km", "777", q1)
|
||||
c2 = ks.add_edge("Seine", "length_km", "776", q1)
|
||||
conflicts = ks.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
|
||||
assert conflicts == 1, "undated different values must be exposed as conflict"
|
||||
# probe: seeds find edges with quotes
|
||||
rows = ks.probe(["Loire", "loire"])
|
||||
assert any(r.rel == "longest_river_of" and r.dst == "France" for r in rows)
|
||||
assert all(r.quote for r in rows), "every edge points at a quote"
|
||||
ks.close()
|
||||
print("ok test_store_four_cases")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_chunker_sections()
|
||||
test_containment()
|
||||
test_store_four_cases()
|
||||
print("\n3 knowledge tests passed")
|
||||
@@ -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", [])]
|
||||
+2
-1
@@ -10,6 +10,7 @@ requires-python = ">=3.13"
|
||||
dependencies = [
|
||||
"dspy>=3.4.1",
|
||||
"pyyaml>=6.0.3",
|
||||
"wikipedia>=1.4.0",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
@@ -20,4 +21,4 @@ requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["floop"]
|
||||
packages = ["floop"]
|
||||
|
||||
+25
-1
@@ -73,8 +73,32 @@ def main() -> None:
|
||||
print(f"\nrun log: {streams.run_dir / 'run.log'}")
|
||||
return
|
||||
|
||||
# knowledge expert: real pipeline when enabled, baseline LLM otherwise
|
||||
knowledge_engine = None
|
||||
if cfg.get("knowledge", {}).get("enabled", False):
|
||||
try:
|
||||
from knowledge.expert import KnowledgeExpert, KnowledgeConfig
|
||||
from knowledge.store import KnowledgeStore
|
||||
from floop.engine import KnowledgeEngine, LLMExpertEngine
|
||||
kcfg = cfg["knowledge"]
|
||||
kconfig = KnowledgeConfig(
|
||||
kb_path=str(code_dir / kcfg.get("kb_path", "knowledge_store/kg.sqlite")),
|
||||
max_articles=kcfg.get("max_articles", 2),
|
||||
max_search_results=kcfg.get("max_search_results", 4),
|
||||
max_chunks_extracted=kcfg.get("max_chunks_extracted", 6),
|
||||
chunk_chars_target=kcfg.get("chunk_chars_target", 32000),
|
||||
chunk_chars_cap=kcfg.get("chunk_chars_cap", 48000),
|
||||
)
|
||||
ke = KnowledgeExpert(config=kconfig, streams=streams)
|
||||
knowledge_engine = KnowledgeEngine(ke)
|
||||
streams.log(f"knowledge pipeline enabled (kb={kconfig.kb_path})")
|
||||
except Exception as e: # noqa: BLE001 — degrade honestly, never die at startup
|
||||
streams.log(f"knowledge pipeline disabled: {e}")
|
||||
knowledge_engine = None
|
||||
|
||||
try:
|
||||
report: RunReport = FloopRun(question, budget, streams=streams).run()
|
||||
report: RunReport = FloopRun(question, budget, streams=streams,
|
||||
knowledge_engine=knowledge_engine).run()
|
||||
finally:
|
||||
streams.close()
|
||||
|
||||
|
||||
Generated
+34
@@ -181,6 +181,19 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "beautifulsoup4"
|
||||
version = "4.15.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "soupsieve" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/43/65/318323f98dbee45d42dff61d8f047181bc6f2268a9068cfad035a46be5af/beautifulsoup4-4.15.0.tar.gz", hash = "sha256:288e3ca7d54b06f2ac191970bc275c1939cb46d450b255bf6718b04aa37ab4f7", size = 632571, upload-time = "2026-06-07T16:44:20.453Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/88/c6/92fcd42f1ba33e1184263f25bfabf3d27c383410470f169e4b8163bf9c17/beautifulsoup4-4.15.0-py3-none-any.whl", hash = "sha256:d6f88de62e1d4e38ecb1077eb9724cd0eff29d2a08ca16a401e9b9e93f117cf9", size = 109924, upload-time = "2026-06-07T16:44:21.566Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "boto3"
|
||||
version = "1.43.112"
|
||||
@@ -460,12 +473,14 @@ source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "dspy" },
|
||||
{ name = "pyyaml" },
|
||||
{ name = "wikipedia" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "dspy", specifier = ">=3.4.1" },
|
||||
{ name = "pyyaml", specifier = ">=6.0.3" },
|
||||
{ name = "wikipedia", specifier = ">=1.4.0" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1642,6 +1657,15 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e9/44/75a9c9421471a6c4805dbf2356f7c181a29c1879239abab1ea2cc8f38b40/sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2", size = 10235, upload-time = "2024-02-25T23:20:01.196Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "soupsieve"
|
||||
version = "3.0.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/5e/77/2dcfa996b01702ab8fd0763d84098f6a640d6162a328f1c04c2697579a1a/soupsieve-3.0.3.tar.gz", hash = "sha256:7dcf6022eed0399eb9934a75e020148f7a2024c37b7dfcd3cf2c5505d69c364e", size = 115923, upload-time = "2026-10-12T13:21:17.696Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/49/ca/f639c80449997b88aba7bc9705d25dd76cc0844f45f187862fd8f8bb18fa/soupsieve-3.0.3-py3-none-any.whl", hash = "sha256:fa30e3ba4809cb81ce1f3209f2fbe3e779fc445f0439bc147a0d7c4601743f21", size = 41705, upload-time = "2026-10-12T13:21:16.474Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tenacity"
|
||||
version = "9.2.1"
|
||||
@@ -1774,6 +1798,16 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wikipedia"
|
||||
version = "1.4.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "beautifulsoup4" },
|
||||
{ name = "requests" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/67/35/25e68fbc99e672127cc6fbb14b8ec1ba3dfef035bf1e4c90f78f24a80b7d/wikipedia-1.4.0.tar.gz", hash = "sha256:db0fad1829fdd441b1852306e9856398204dc0786d2996dd2e0c8bb8e26133b2", size = 27748, upload-time = "2014-11-15T15:59:49.808Z" }
|
||||
|
||||
[[package]]
|
||||
name = "yarl"
|
||||
version = "1.25.1"
|
||||
|
||||
Reference in New Issue
Block a user