"""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, quote_containment from .chunker import chunk_page from .extract import (AnswerFromKG, ExtractSignature, SelectTableSignature, TranslateSignature, VerifyCountSignature, parse_facts) from .store import KnowledgeStore, norm_name 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.select_table = dspy.Predict(SelectTableSignature) self.verify_count = dspy.Predict(VerifyCountSignature) 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] def _set_gate_hit(self, probe_seeds: list[str], question: str) -> str | None: """The membership set (if any) this question may be served from. Mention rows never answer enumerations — only a set does. And a set belongs to ITS question: serving Q1's 'countries in Europe' set to 'which are EU members?' would be a confident wrong answer. The match is stem-Jaccard >= 0.5 between the incoming question and the set's ORIGIN question — near-repeats are served, different questions gather.""" from .store import stem q_stems = {stem(w) for w in WORD_RE.findall(question.casefold()) if len(w) > 2} for set_name, origin in self.store.set_origins(): o_stems = {stem(w) for w in WORD_RE.findall(origin.casefold()) if len(w) > 2} if not q_stems or not o_stems: continue jac = len(q_stems & o_stems) / len(q_stems | o_stems) if jac >= 0.5 and self.store.list_members(set_name): return set_name return None def _serve_set(self, set_name: str, question: str) -> dict: """Answer an enumeration from a held membership set: the full member list with provenance, coverage complete per source.""" members = self.store.list_members(set_name) quote, url = self.store.set_provenance(set_name) self._log(f"kg set hit: {set_name} ({len(members)} members)", think=True) return {"value": str(len(members)), "list_items": members, "list_count": len(members), "quote": quote, "url": url, "confidence": "high", "coverage": {"source": "knowledge_graph", "set": set_name, "rows_ingested": len(members), "rows_total": len(members), "complete_per_source": True}} # ---- the pipeline -------------------------------------------------------- def answer_question(self, question: str, parent_question: str = "", evidence: str = "", charge_llm=None, answer_type: str = "") -> 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) # LIST activation (moved up: the set gate needs it before the probe) list_mode = (str(answer_type or "").upper() == "LIST" or self._is_enumeration(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) # SET GATE (lists): mention rows never answer an enumeration — only a # membership set does. With no set held, the probe result is not # answerability evidence; the gather must run. if list_mode: kg_set = self._set_gate_hit(probe_seeds, question) if kg_set: return {**self._serve_set(kg_set, question), "source": "knowledge_graph", "kg_rows": len(rows)} self._log(f"set gate: {len(rows)} mention rows are not answerability " f"for an enumeration; gather runs", think=True) else: 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) # LIST path: one SELECT TABLE call per article; on hit, ingest ALL # rows and answer by aggregation (no extract calls, no gate) if list_mode and page.tables: ans = self._list_from_page(page, question, charge_llm) if ans is not None: self._log(f"early exit after {page.title}: list " f"({ans['list_count']} items)", think=True) return {**ans, "source": "knowledge_graph", "stats": {"pages": [p.title for p in pages]}} # 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). For enumerations the set gate applies # here too: mention rows never answer a list question. self._process_page(page, question, kws, charge_llm) if list_mode: hit = self._set_gate_hit(probe_seeds, question) if hit is not None: self._log(f"early exit after {page.title}: set {hit}", think=True) return {**self._serve_set(hit, question), "source": "knowledge_graph", "stats": {"pages": [p.title for p in pages]}} else: 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 _is_enumeration(self, question: str) -> bool: """Deterministic LIST detection: plural nouns + enumeration ask words. Cheap, logged, and overridable by the planner's explicit answer_type.""" q = question.casefold() words = set(WORD_RE.findall(q)) ask = {"which", "what", "list", "name", "enumerate", "identify"} plurals = [w for w in words if w.endswith("s") and len(w) > 4 and w not in ("states?", "does", "was", "has")] return bool(words & ask) and len(plurals) >= 1 def _verify_count(self, set_name: str, count: int, prose: str, charge_llm) -> dict | None: """Answer-level CHECK: corroborate the list COUNT from article prose that is NOT the source table. Law split: the LLM finds language (one verbatim sentence stating the count); fixed code decides validity — the sentence must be contained in the prose AND state the same count as `count` digits. No LLM ever compares numbers. Returns a verification record or None (no corroborating sentence found — honest, not an error).""" if not prose or count <= 0: return None if charge_llm: charge_llm() pred = self.verify_count(set_name=set_name, count=str(count), text=prose[: self.cfg.chunk_chars_cap]) q = (pred.quote or "").strip() if not q or q.upper() in ("NOQUOTE", "NONE", "N/A"): return None if not quote_containment(q, prose): self._log(f"verify: quote not contained in prose — rejected") return None # deterministic number comparison: the digits the sentence states # must equal the count we computed from the rows nums = {int(n.replace(",", "")) for n in re.findall(r"[\d,]{1,7}", q) if n.replace(",", "").isdigit()} if count in nums: return {"count_corroborated": True, "quote": q} self._log(f"verify: corroborating sentence states {nums}, not {count} " f"— numbers disagree") return None def _list_from_page(self, page: WikiPage, question: str, charge_llm) -> dict | None: """The LIST path: SELECT TABLE (LLM picks table+column from metadata, never the rows) -> ingest ALL rows as membership edges -> aggregate. Returns the list answer dict, or None when no table in this page enumerates the answer (fall through to the extract path).""" rendered = chr(10).join( f"{t.idx} | {t.caption or '(no caption)'} | " f"header: {', '.join(t.header[:6]) or '(none)'} | rows: {t.total_rows}" for t in page.tables) if charge_llm: charge_llm() pred = self.select_table(question=question, tables=rendered) idx_raw = (pred.table_index or "").strip() if not idx_raw or idx_raw.upper() in ("NONE", "N/A", "0"): return None try: idx = int(re.findall(r"\d+", idx_raw)[0]) except (ValueError, IndexError): return None table = next((t for t in page.tables if t.idx == idx), None) if table is None: return None column = (pred.column or "").strip() col_i = next((i for i, h in enumerate(table.header) if column.casefold() in h.casefold()), 0) set_name = (pred.set_name or "").strip() or question[:60] origin_question = (pred.origin_question or "").strip() or question # INGEST ALL ROWS: one membership edge per row, quote = the full # stored row line, containment against the stored table text doc_id = self.store.add_document( url=page.url, title=page.title, fetched_at=page.fetched_at, sha256=hashlib.sha256(page.text.encode()).hexdigest()) table_text = chr(10).join(table.text_lines()) members: list[str] = [] for row in table.rows: element = (row[col_i] if col_i < len(row) else (row[0] if row else "")).strip() if not element: continue if " / " in element: element = element.split(" / ")[0].strip() # first of multi-value cell if element.casefold() in ("total", "totals", "sum", "average", "mean"): continue # aggregate footer rows are not members if element.isdigit(): continue # a bare number in the element column is not a member row_line = " | ".join(row) ok, reason = check_candidate( {"subject": element, "relation": "member_of", "object": set_name, "quote": row_line}, table_text) if not ok: self._log(f"list row rejected ({reason}): {element[:40]}") continue qid = self.store.add_quote(doc_id, row_line, page.url, page.fetched_at) self.store.add_edge(element, "member_of", set_name, qid, src_sort="PLACE", dst_node_name=set_name, origin_question=origin_question) members.append(element) self._merged += 1 if not members: return None items = sorted(set(members)) self._log(f"LIST ingest: {len(items)} members of '{set_name}' from " f"table {idx} ({table.total_rows} rows)", think=True) # ANSWER-LEVEL CHECK: corroborate the count from prose OUTSIDE the # table (the extract text is the article prose; tables are separate). # One bounded call; failure = honest 'no corroboration', never a loop. verify = self._verify_count(set_name, len(items), page.text, charge_llm) coverage = {"source": page.title, "table": idx, "rows_total": table.total_rows, "rows_ingested": len(members), "complete_per_source": len(members) == table.total_rows} if verify: coverage["count_corroborated"] = True coverage["corroboration_quote"] = verify["quote"] else: coverage["count_corroborated"] = False return { "value": str(len(items)), "list_items": items, "list_count": len(items), "quote": table.rows[0] and " | ".join(table.rows[0]), "url": page.url, "confidence": "high" if verify else "medium", "coverage": coverage, } 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(), }