knowledge: replace curated-vocab ambiguity audit with ablation detector (run J)
PR-7's audit (merged hours earlier) detected office ambiguity with a
curated role vocabulary (president, prime minister, ...) plus entity
and shape heuristics. His run-K log killed it: all three alternatives
came out '[prime minister]', Mariano Rajoy (a person, not an office)
was one, PSOE never appeared — the vocabulary could not see the
difference. His design replaces it, and it is better: instead of
listing what counts as a role, ask the judge whether the question
STILL answers once the support for the picked value is masked out.
_audit_ambiguity (knowledge/expert.py), zero new prompts:
- After a scalar KG answer V, find V's support rows (dst/quote carry
the value) and MASK them from the view — the store is never
mutated, the mask is a Python-level view.
- Re-ask the SAME judge (AnswerFromKG) on the surviving rows.
A DIFFERENT value = a second defensible reading -> record, mask
its support too, repeat (ambiguity_rounds=3, budget law).
- Same surviving value = corroboration -> silent stop.
- UNKNOWN -> clean answer, byte-identical to pre-audit behaviour.
- Run J: pick 'Socialist International' -> ablation surfaces
'prime minister of Spain' then 'secretary-general of PSOE' — the
third paragraph reading, no role vocabulary anywhere.
Removed: knowledge/ambiguity.py + knowledge/tests/ambiguity.py
(PR-7), the .ambiguity import, and _maybe_ambig at the three scalar
return paths — replaced by _audit_ambiguity(question, answer, rows,
charge_llm) at the same three sites.
Consumers (engine/machine) now render the simpler alternative shape
{value, quote, url} — no 'role' field exists to render.
Tests: knowledge/tests/ablation.py — the 4 agreed cases (2 Pedro
positives flag with 2 alternatives each, EU and rivers
counterexamples silent), corroboration-not-ambiguity, store
unchanged after audit (mask is a view), single-source silent, rounds
cap. Suite 70/70. Live smoke: full pipeline over the run-J page
picks SI and flags PM+SG via two ablation rounds; the rivers
question over the same KG stays silent.
This commit is contained in:
+79
-28
@@ -27,7 +27,6 @@ from .skim import find_quantities, skim_article
|
||||
from .extract import (AnswerFromKG, ExtractSignature, SelectTableSignature,
|
||||
SkimPromoteSignature, TranslateSignature,
|
||||
VerifyCountSignature, parse_facts)
|
||||
from .ambiguity import audit_role_multiplicity, ref_entity, role_in_text
|
||||
from .store import KnowledgeStore, norm_name
|
||||
from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert,
|
||||
tables_as_chunks, format_table_frag, parse_stop_table)
|
||||
@@ -110,6 +109,7 @@ class KnowledgeConfig:
|
||||
max_search_results: int = 4 # candidates considered
|
||||
max_chunks_extracted: int = 6 # per call (lexical gate decides which)
|
||||
max_extract_retries: int = 2
|
||||
ambiguity_rounds: int = 3 # ablation rounds per scalar answer (run J)
|
||||
chunk_chars_target: int = 32000
|
||||
chunk_chars_cap: int = 48000
|
||||
# skim harvest (PR-2): goal-relevant side-tables are ingested in passing
|
||||
@@ -260,7 +260,7 @@ class KnowledgeExpert:
|
||||
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 {**self._maybe_ambig(question, answer),
|
||||
return {**self._audit_ambiguity(question, answer, rows, charge_llm),
|
||||
"source": "knowledge_graph", "kg_rows": len(rows)}
|
||||
|
||||
# 3-4. gap -> search + fetch. TRANSLATE (LLM) first: the question becomes
|
||||
@@ -395,7 +395,9 @@ class KnowledgeExpert:
|
||||
if answer["value"] and answer["value"].upper() != "UNKNOWN":
|
||||
self._log(f"early exit after {page.title}: "
|
||||
f"{answer['value'][:60]}", think=True)
|
||||
return {**self._maybe_ambig(question, answer),
|
||||
return {**self._audit_ambiguity(question, answer,
|
||||
self.store.probe(probe_seeds),
|
||||
charge_llm),
|
||||
"source": "knowledge_graph",
|
||||
"stats": {**self._skim_stats(pages),
|
||||
"skim": self._skim_notices}}
|
||||
@@ -408,7 +410,7 @@ class KnowledgeExpert:
|
||||
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._maybe_ambig(question, answer), "source": src,
|
||||
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,
|
||||
@@ -480,31 +482,80 @@ class KnowledgeExpert:
|
||||
and w not in ("states?", "does", "was", "has")]
|
||||
return bool(words & ask) and len(plurals) >= 1
|
||||
|
||||
def _maybe_ambig(self, question: str, answer: dict) -> dict:
|
||||
"""Layer-1 ambiguity audit (KNOWLEDGE.md §8): after a scalar answer,
|
||||
check the KG for OTHER office-class readings of the same question
|
||||
(run J: 'president of Pedro Sanchez' legitimately resolved to
|
||||
Socialist International while the KG also held prime minister of
|
||||
Spain and secretary-general of PSOE). Zero LLM, zero network —
|
||||
rows the KG already holds. Flags the answer; never chooses."""
|
||||
if (not answer.get("value")
|
||||
or str(answer["value"]).upper() == "UNKNOWN"):
|
||||
def _audit_ambiguity(self, question: str, answer: dict, rows,
|
||||
charge_llm=None) -> dict:
|
||||
"""Ablation ambiguity detector (KNOWLEDGE.md §8, run J).
|
||||
|
||||
The KG just answered with value V from some support row(s). Ask the
|
||||
SAME judge (AnswerFromKG) whether the question ALSO answers without
|
||||
that support: mask the rows whose object/relation produced V, re-ask.
|
||||
A DIFFERENT surviving value = a second defensible reading -> flag.
|
||||
Repeat (bounded) until the rows run out of answers. Same-value
|
||||
survivors are corroboration, not ambiguity — silent.
|
||||
|
||||
Zero new prompts: same AnswerFromKG signature, one call per round.
|
||||
The store is NEVER mutated — the mask is a view, deletion happens
|
||||
nowhere. Ordinary questions end at round 1 with UNKNOWN (silent).
|
||||
"""
|
||||
value = str(answer.get("value", "")).strip()
|
||||
if (not value or value.upper() == "UNKNOWN" or not rows):
|
||||
return answer
|
||||
if not role_in_text(question):
|
||||
return answer # ordinary question: audit stays quiet
|
||||
ent = ref_entity(question)
|
||||
if not ent:
|
||||
return answer
|
||||
rows = self.store.probe([ent] + ent.split())
|
||||
audit = audit_role_multiplicity(question, rows, answer["value"])
|
||||
if not audit:
|
||||
return answer # single reading: byte-identical answer
|
||||
self._log(f"ambiguity audit: {len(audit['alternatives'])} other "
|
||||
f"office readings for {ent!r} ({'; '.join(
|
||||
a['value'] for a in audit['alternatives'][:3])}) — "
|
||||
f"flagging, not choosing", think=True)
|
||||
return {**answer, "ambiguous": True, "axis": audit["axis"],
|
||||
"alternatives": audit["alternatives"]}
|
||||
|
||||
# The supporting rows for the PICKED value: those whose dst or quote
|
||||
# carries it. Masked cumulatively each round; the store never
|
||||
# changes — the view handed to the judge shrinks, nothing else.
|
||||
def _carries(r) -> bool:
|
||||
dst = (getattr(r, "dst", "") or "").strip().casefold()
|
||||
quote = (getattr(r, "quote", "") or "").strip().casefold()
|
||||
v = value.casefold()
|
||||
return v in dst or v in quote
|
||||
|
||||
support = [r for r in rows if _carries(r)]
|
||||
if not support:
|
||||
return answer # the judge invented it: nothing to ablate
|
||||
|
||||
alternatives: list[dict] = []
|
||||
seen = {norm_name(value)}
|
||||
masked = set(id(r) for r in support)
|
||||
|
||||
for _ in range(self.cfg.ambiguity_rounds):
|
||||
view = [r for r in rows if id(r) not in masked]
|
||||
if not view:
|
||||
break
|
||||
re_ans = self._answer_from_rows(question, view, charge_llm)
|
||||
re_val = str(re_ans.get("value", "")).strip()
|
||||
if not re_val or re_val.upper() == "UNKNOWN":
|
||||
break # the KG has no other reading: clean
|
||||
key = norm_name(re_val)
|
||||
if key in seen:
|
||||
break # same value again: corroboration, not ambiguity
|
||||
seen.add(key)
|
||||
# which surviving row produced this reading? the one whose
|
||||
# dst/quote carries it — for the report and the next mask
|
||||
src_row = next((r for r in view
|
||||
if re_val.casefold() in (r.dst or "").casefold()
|
||||
or re_val.casefold() in (r.quote or "").casefold()), None)
|
||||
alternatives.append({
|
||||
"value": re_val,
|
||||
"quote": re_ans.get("quote", ""),
|
||||
"url": (src_row.url if src_row is not None
|
||||
else re_ans.get("url", "")),
|
||||
})
|
||||
# mask this reading's own support too — next round hunts a third
|
||||
new_support = [r for r in view if re_val.casefold() in (
|
||||
(r.dst or "").casefold() + " " + (r.quote or "").casefold())]
|
||||
if not new_support:
|
||||
break
|
||||
masked |= set(id(r) for r in new_support)
|
||||
|
||||
if not alternatives:
|
||||
return answer # ordinary question: byte-identical
|
||||
self._log(f"ambiguity audit: {len(alternatives)} other reading(s) "
|
||||
f"({'; '.join(a['value'][:40] for a in alternatives[:3])}) "
|
||||
f"— flagging, not choosing", think=True)
|
||||
return {**answer, "ambiguous": True,
|
||||
"axis": f"which {question.strip().rstrip('?')}?",
|
||||
"alternatives": alternatives}
|
||||
|
||||
def _verify_count(self, set_name: str, count: int, prose: str,
|
||||
charge_llm) -> dict | None:
|
||||
|
||||
Reference in New Issue
Block a user