Refactorin KnowledgeExpert.answer_question too long function
This commit is contained in:
+174
-183
@@ -29,7 +29,7 @@ from floop.llm import predict
|
||||
|
||||
from .checks import check_candidate, quote_containment
|
||||
from .chunker import chunk_page
|
||||
from .skim import find_quantities, skim_article
|
||||
from .skim import SkimSheet, find_quantities, skim_article
|
||||
from .extract import (AnswerFromKG, ExtractClaims, ExtractSignature, Fact,
|
||||
SelectTableSignature, SkimPromoteSignature,
|
||||
SkimTableSignature, TypeClaim, VerifyCountSignature)
|
||||
@@ -144,6 +144,45 @@ def _proper_nouns(question: str) -> set[str]:
|
||||
return proper_nouns(question)
|
||||
|
||||
|
||||
def _probe_seeds(kws: list[str], evidence: str) -> list[str]:
|
||||
"""Augment keywords with short values from the parent's evidence."""
|
||||
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:
|
||||
seeds.extend(val.split())
|
||||
return seeds
|
||||
|
||||
|
||||
def _rank_article_titles(per_query: list[list[str]],
|
||||
terms: list[str]) -> list[str]:
|
||||
"""Keep each query's winner first, then stably rank unique other titles."""
|
||||
from .store import stem
|
||||
title_terms = {t for w in terms 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(dict.fromkeys(t for found in per_query for t in found))
|
||||
winners = list(dict.fromkeys(found[0] for found in per_query if found))
|
||||
picked = set(winners)
|
||||
return winners + sorted((t for t in candidates if t not in picked),
|
||||
key=relevance, reverse=True)
|
||||
|
||||
|
||||
def _goal_skim_notice(sheet: SkimSheet, goal_terms: list[str]) -> str:
|
||||
"""Keep goal-relevant notices and quantity signals, not unrelated prose."""
|
||||
notice = sheet.notice()
|
||||
if notice and (not goal_terms
|
||||
or any(_term_hits(gt, notice) for gt in goal_terms)
|
||||
or any(find_quantities(notice))):
|
||||
return notice
|
||||
return ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class KnowledgeConfig:
|
||||
kb_path: str = "knowledge_store/kg.sqlite"
|
||||
@@ -455,60 +494,87 @@ class KnowledgeExpert:
|
||||
`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."""
|
||||
resolve against them. Orchestrates proof, cached answers, then
|
||||
article-by-article gathering with early exit."""
|
||||
t0 = time.time()
|
||||
# parent_question/evidence ARE the machine's context (design §4) —
|
||||
# consumed directly by the probe seeds, the query composer and the
|
||||
# guards; no prompt ever renders them into a TRANSLATE call anymore.
|
||||
kws = self._keywords(question)
|
||||
goal_terms = self._keywords(parent_question) if parent_question else []
|
||||
self._current_goal_terms = goal_terms # the harvest reads these
|
||||
self._current_goal_terms = goal_terms
|
||||
self._current_goal_question = parent_question or question
|
||||
# ---- phase 3b: the derived-answer engine, BEFORE any judge ----
|
||||
# If the question translates to the DSL and the store closes the
|
||||
# path, the proof term IS the answer (re-execution = the check,
|
||||
# verified=True) — the judge never runs on this question. No
|
||||
# translation or no closed path -> the judge path, unchanged.
|
||||
try:
|
||||
proven = self._prover_answer(question, charge_llm)
|
||||
except Exception as e: # noqa: BLE001 — the prover must never kill a run
|
||||
self._log(f"prover path failed ({e!r}); judge path", think=True)
|
||||
proven = None
|
||||
proven = self._try_prover_answer(question, charge_llm)
|
||||
if proven is not None:
|
||||
return proven
|
||||
# per-CALL skim state (PR-3): notices for the machine + ambiguous
|
||||
# leads pending the bounded promotion decision
|
||||
self._skim_notices: list[str] = []
|
||||
self._skim_leads: list[tuple[WikiPage, object]] = []
|
||||
ev_entities = [e for e in self._expected_entities(evidence or "")][:8]
|
||||
# the extractor's ENTITIES (research/semantic-kg): TRANSLATE resolves
|
||||
# them; keywords of the question are the fallback when it returns none
|
||||
self._extract_entities: list[str] = []
|
||||
# SEEN-INDEX (PR-2): articles already fetched this RUN — consulted
|
||||
# before network search so a later question pays zero re-fetch
|
||||
if not hasattr(self, "_seen_pages"):
|
||||
self._seen_pages: dict[str, WikiPage] = {}
|
||||
# LINK QUEUE (PR-2): goal-region links from skims, joining the fetch
|
||||
# order as candidates (hops still live in the plan — the law stands)
|
||||
if not hasattr(self, "_link_queue"):
|
||||
self._link_queue: list[str] = []
|
||||
# LIST activation (moved up: the set gate needs it before the probe)
|
||||
|
||||
self._prepare_gather_state()
|
||||
ev_entities = self._expected_entities(evidence or "")[:8]
|
||||
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)
|
||||
probe_seeds = _probe_seeds(kws, evidence)
|
||||
answer = self._try_stored_answer(question, probe_seeds, list_mode, charge_llm)
|
||||
if answer is not None:
|
||||
return answer
|
||||
|
||||
# 2. HYBRID KG probe: lexical seeds UNION semantic rank (embeddings)
|
||||
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())
|
||||
ordered = self._search_articles(question, kws, ev_entities, list_mode)
|
||||
pages: list[WikiPage] = []
|
||||
for title in ordered[: self.cfg.max_articles]:
|
||||
page = self._fetch_page(title)
|
||||
if page is None:
|
||||
continue
|
||||
pages.append(page)
|
||||
sheet = self._skim_page(page, kws, goal_terms, ev_entities)
|
||||
self._harvest_side_tables(page, sheet, question, evidence)
|
||||
self._promote_leads(evidence, charge_llm)
|
||||
if list_mode and page.tables:
|
||||
ans = self._list_from_page(page, question, charge_llm)
|
||||
if ans is not None and self._guard_ingest(ans, evidence):
|
||||
self._log(f"early exit after {page.title}: list "
|
||||
f"({ans['list_count']} items)", think=True)
|
||||
return {**ans, "source": "knowledge_graph",
|
||||
"stats": {**self._skim_stats(pages),
|
||||
"skim": self._skim_notices}}
|
||||
self._process_page(page, question, kws, charge_llm,
|
||||
goal_terms=goal_terms)
|
||||
answer = self._try_gathered_answer(
|
||||
question, probe_seeds, list_mode, page.title, charge_llm)
|
||||
if answer is not None:
|
||||
return {**answer, "source": "knowledge_graph",
|
||||
"stats": {**self._skim_stats(pages),
|
||||
"skim": self._skim_notices}}
|
||||
|
||||
rows = self._probe(question, 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 {**self._audit_ambiguity(question, answer, rows, charge_llm), "source": src,
|
||||
"stats": {**self._skim_stats(pages),
|
||||
"checked": self._checked, "merged": self._merged,
|
||||
"skim": self._skim_notices,
|
||||
"elapsed_s": round(time.time() - t0, 1)}}
|
||||
|
||||
def _try_prover_answer(self, question: str, charge_llm=None) -> dict | None:
|
||||
"""A closed proof bypasses the judge; a failed proof must not kill a run."""
|
||||
try:
|
||||
return self._prover_answer(question, charge_llm)
|
||||
except Exception as e: # noqa: BLE001 — the prover must never kill a run
|
||||
self._log(f"prover path failed ({e!r}); judge path", think=True)
|
||||
return None
|
||||
|
||||
def _prepare_gather_state(self) -> None:
|
||||
"""Reset per-call extraction/skim state, preserving the run's page cache."""
|
||||
self._skim_notices = []
|
||||
self._skim_leads = []
|
||||
self._extract_entities = []
|
||||
if not hasattr(self, "_seen_pages"):
|
||||
self._seen_pages: dict[str, WikiPage] = {}
|
||||
if not hasattr(self, "_link_queue"):
|
||||
self._link_queue: list[str] = []
|
||||
|
||||
def _try_stored_answer(self, question: str, probe_seeds: list[str],
|
||||
list_mode: bool, charge_llm=None) -> dict | None:
|
||||
"""Probe held knowledge, enforcing the membership-set gate for lists."""
|
||||
rows = self._probe(question, 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:
|
||||
@@ -522,11 +588,11 @@ class KnowledgeExpert:
|
||||
self._log(f"kg hit: {answer['value'][:60]}", think=True)
|
||||
return {**self._audit_ambiguity(question, answer, rows, charge_llm),
|
||||
"source": "knowledge_graph", "kg_rows": len(rows)}
|
||||
return None
|
||||
|
||||
# 3-4. gap -> search + fetch. COMPOSE (deterministic, from main 23/10 —
|
||||
# the model's own knowledge of the entities can no longer steer
|
||||
# retrieval) + the branch's extract-entities contract: the
|
||||
# question-blind extractor transcribes facts about THESE.
|
||||
def _search_articles(self, question: str, kws: list[str],
|
||||
ev_entities: list[str], list_mode: bool) -> list[str]:
|
||||
"""Compose and search all queries before globally ranking candidates."""
|
||||
queries, entity_terms = compose_queries(
|
||||
question, evidence_entities=ev_entities, list_mode=list_mode)
|
||||
self._rec("fn.done", fn="compose",
|
||||
@@ -537,21 +603,6 @@ class KnowledgeExpert:
|
||||
e for e in (entity_terms + sorted(_proper_nouns(question))) if e))
|
||||
self._log(f"compose -> 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)
|
||||
@@ -560,131 +611,71 @@ class KnowledgeExpert:
|
||||
in_={"query": query, "limit": self.cfg.max_search_results},
|
||||
out_={"titles": 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)
|
||||
ordered = _rank_article_titles(per_query, entity_terms + kws)
|
||||
self._log(f"fetch order: {ordered[: self.cfg.max_articles]}", think=True)
|
||||
return ordered
|
||||
|
||||
pages: list[WikiPage] = []
|
||||
for title in ordered[: self.cfg.max_articles]:
|
||||
if title in self._seen_pages:
|
||||
page = self._seen_pages[title]
|
||||
self._rec("fn.done", fn="fetch", in_={"title": title},
|
||||
out_={"cached": True})
|
||||
self._log(f"seen-index hit: {title} (already fetched this run)",
|
||||
think=True)
|
||||
else:
|
||||
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
|
||||
self._seen_pages[title] = page
|
||||
self._rec("fn.done", fn="fetch", in_={"title": title},
|
||||
out_={"url": page.url, "chars": len(page.text),
|
||||
"tables": len(page.tables)})
|
||||
pages.append(page)
|
||||
# SKIM (PR-1): the structural read, in passing — question AND goal
|
||||
# oriented; surfaces + signals, zero LLM. The sheet drives chunk
|
||||
# ranking in _process_page; PR-2's harvest runs on its signals.
|
||||
sheet = skim_article(page, question_terms=kws, goal_terms=goal_terms,
|
||||
evidence_entities=ev_entities)
|
||||
self._rec("fn.done", fn="skim",
|
||||
in_={"title": page.title, "question_terms": kws,
|
||||
"goal_terms": goal_terms},
|
||||
out_={"tables": len(sheet.tables),
|
||||
"infobox_quantities": len(sheet.infobox_quantities),
|
||||
"link_candidates": len(sheet.link_candidates),
|
||||
"notice": sheet.notice()[:200]})
|
||||
self._log(f"skim {page.title}: {len(sheet.tables)} tables, "
|
||||
f"{len(sheet.infobox_quantities)} infobox quantities, "
|
||||
f"{len(sheet.link_candidates)} link candidates", think=True)
|
||||
# PR-3 — the skim notice: goal-relevant surfaces seen in passing,
|
||||
# so later steps (router context, run notes) know what exists
|
||||
# and where it lives. Filtered to goal signals: the notice is a
|
||||
# pointer, not a dump.
|
||||
notice = sheet.notice()
|
||||
if notice:
|
||||
goal_signal = (any(_term_hits(gt, notice) for gt in goal_terms)
|
||||
or any(find_quantities(notice)))
|
||||
if goal_signal or not goal_terms:
|
||||
self._skim_notices.append(notice)
|
||||
if self.cfg.skim_link_queue:
|
||||
for link in sheet.link_candidates:
|
||||
if link not in self._link_queue:
|
||||
self._link_queue.append(link)
|
||||
# PR-2 — the opportunistic harvest: goal-relevant side-tables
|
||||
# seen in passing become typed edges (zero LLM, containment law)
|
||||
self._harvest_side_tables(page, sheet, question, evidence)
|
||||
# PR-3 — bounded promotion of ambiguous leads (one LLM call,
|
||||
# only when leads exist): promoted tables ingest through the
|
||||
# same containment-checked path as the deterministic harvest
|
||||
self._promote_leads(evidence, charge_llm)
|
||||
# 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 and self._guard_ingest(ans, evidence):
|
||||
self._log(f"early exit after {page.title}: list "
|
||||
f"({ans['list_count']} items)", think=True)
|
||||
return {**ans, "source": "knowledge_graph",
|
||||
"stats": {**self._skim_stats(pages),
|
||||
"skim": self._skim_notices}}
|
||||
# refused by the guard: wrong article's list — keep gathering
|
||||
# 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,
|
||||
goal_terms=goal_terms)
|
||||
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": {**self._skim_stats(pages),
|
||||
"skim": self._skim_notices}}
|
||||
else:
|
||||
answer = self._answer_from_rows(
|
||||
question, self._probe(question, 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 {**self._audit_ambiguity(question, answer,
|
||||
self._probe(question, probe_seeds),
|
||||
charge_llm),
|
||||
"source": "knowledge_graph",
|
||||
"stats": {**self._skim_stats(pages),
|
||||
"skim": self._skim_notices}}
|
||||
def _fetch_page(self, title: str) -> WikiPage | None:
|
||||
"""Reuse fetched articles; log network failures and let gathering continue."""
|
||||
if title in self._seen_pages:
|
||||
self._rec("fn.done", fn="fetch", in_={"title": title},
|
||||
out_={"cached": True})
|
||||
self._log(f"seen-index hit: {title} (already fetched this run)",
|
||||
think=True)
|
||||
return self._seen_pages[title]
|
||||
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}")
|
||||
return None
|
||||
self._seen_pages[title] = page
|
||||
self._rec("fn.done", fn="fetch", in_={"title": title},
|
||||
out_={"url": page.url, "chars": len(page.text),
|
||||
"tables": len(page.tables)})
|
||||
return page
|
||||
|
||||
# 5-7. remaining pages already processed inline via _process_page
|
||||
# (early exit); fall through to the final re-probe and answer.
|
||||
def _skim_page(self, page: WikiPage, kws: list[str], goal_terms: list[str],
|
||||
ev_entities: list[str]) -> SkimSheet:
|
||||
"""Record structural signals and retain notices/links for later questions."""
|
||||
sheet = skim_article(page, question_terms=kws, goal_terms=goal_terms,
|
||||
evidence_entities=ev_entities)
|
||||
self._rec("fn.done", fn="skim",
|
||||
in_={"title": page.title, "question_terms": kws,
|
||||
"goal_terms": goal_terms},
|
||||
out_={"tables": len(sheet.tables),
|
||||
"infobox_quantities": len(sheet.infobox_quantities),
|
||||
"link_candidates": len(sheet.link_candidates),
|
||||
"notice": sheet.notice()[:200]})
|
||||
self._log(f"skim {page.title}: {len(sheet.tables)} tables, "
|
||||
f"{len(sheet.infobox_quantities)} infobox quantities, "
|
||||
f"{len(sheet.link_candidates)} link candidates", think=True)
|
||||
notice = _goal_skim_notice(sheet, goal_terms)
|
||||
if notice:
|
||||
self._skim_notices.append(notice)
|
||||
if self.cfg.skim_link_queue:
|
||||
for link in sheet.link_candidates:
|
||||
if link not in self._link_queue:
|
||||
self._link_queue.append(link)
|
||||
return sheet
|
||||
|
||||
# 8. re-probe (same seeds, hybrid) and answer from the merged KG
|
||||
rows = self._probe(question, 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 {**self._audit_ambiguity(question, answer, rows, charge_llm), "source": src,
|
||||
"stats": {**self._skim_stats(pages),
|
||||
"checked": self._checked, "merged": self._merged,
|
||||
"skim": self._skim_notices,
|
||||
"elapsed_s": round(time.time() - t0, 1)}}
|
||||
def _try_gathered_answer(self, question: str, probe_seeds: list[str],
|
||||
list_mode: bool, page_title: str,
|
||||
charge_llm=None) -> dict | None:
|
||||
"""Stop after an article closes the gap, using the list gate or judge."""
|
||||
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)
|
||||
else:
|
||||
answer = self._answer_from_rows(
|
||||
question, self._probe(question, 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 self._audit_ambiguity(
|
||||
question, answer, self._probe(question, probe_seeds), charge_llm)
|
||||
return None
|
||||
|
||||
def _skim_stats(self, pages: list[WikiPage]) -> dict:
|
||||
"""stats shared by every return path: pages seen + link queue state."""
|
||||
|
||||
Reference in New Issue
Block a user