Files
floop/code/floop/engine.py
T
onibot 8b50e3076e 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.
2026-10-21 23:42:20 +02:00

209 lines
10 KiB
Python

"""Expert engines for the draft: the LLM IS the engine; deterministic engines come later.
The Engine interface and its laws are already the real ones: the instantiated
question in, typed payload out — never free-form rows. Stub engines mark
verified=False; the arrival check (in the machine) refuses UNKNOWN.
Routing (v0.1) — catalogue + one LLM judgement per question. Learned router:
v2 (PIPELINE.md §7); logged trajectories train it.
"""
from __future__ import annotations
from typing import Callable, Protocol
from .state import AnswerType, EvidenceRow, EvidenceTable
CATALOG = (
"knowledge: search and fetch trusted sources (Wikipedia); answer factual questions with verbatim quotes; enumerations and lists are ONE fetch, not many questions\n"
"logic: derive conclusions validly from provided premises — including how-many / counting questions over lists or tables already in the evidence\n"
"analytic: solve equations / symbolic relations over provided quantities\n"
"numeric: evaluate a closed arithmetic expression over provided numbers\n"
"floop: needs multi-hop derivation across subgoals — NOT mere size (a list or a table is one knowledge fetch)\n"
"user: nothing else plausibly covers it — ask the person\n"
)
NO_ROUTER = ["knowledge", "logic", "analytic", "numeric", "floop", "user"]
class Engine(Protocol):
def run(self, qid: str, question: str, parent_question: str,
table: EvidenceTable, answer_type: AnswerType) -> EvidenceRow: ...
class LLMExpertEngine:
"""Draft engine: the dspy call produces the draft; a stub check layer passes
it through with verified=False. Each engine call charges the LLM budget."""
def __init__(self, modules, charge_llm: Callable[[], None],
expert_kind: str = "expert") -> None:
self.modules = modules
self.charge = charge_llm
self.kind = expert_kind
self.name = f"stub:{expert_kind}"
def run(self, qid, question, parent_question, table, answer_type, streams=None):
self.charge() # the engine IS an LLM call in this draft — it costs budget
ev = table.dump()
draft = self.modules.expert_draft(
question, self.kind, ev, parent_question=parent_question)
if streams is not None:
streams.output("EXPERT", f"value={draft['value']} quote={draft['source_quote'][:80]}")
verified = False # v0.2: formal check layer (sorts/units/consistency) BEFORE engine
payload: dict = {"value": draft["value"]}
if draft["source_quote"]:
payload["quote"] = draft["source_quote"]
prov = {"expert": self.kind,
"source": "model_weights" if not draft["source_quote"] else "given_evidence",
"note": "baseline v0.1 — LLM answers directly; engines come later"}
if parent_question:
prov["parent_question"] = parent_question
return EvidenceRow(
qid=qid,
answer_type=answer_type,
payload=payload,
engine=self.name,
trace=[f"llm draft: value={draft['value']} confidence={draft['confidence']}"],
provenance=prov,
verified=verified,
note="" if str(draft["value"]).upper() != "UNKNOWN" else "expert reported UNKNOWN",
)
class UserRequestEngine:
"""v0.1: the user expert is not wired (no chat channel); returns an explicit failure row."""
def __init__(self, modules) -> None:
self.modules = modules
self.name = "stub:user"
def run(self, qid, question, parent_question, table, answer_type):
prov = {"expert": "user"}
if parent_question:
prov["parent_question"] = parent_question
return EvidenceRow(
qid=qid,
answer_type=answer_type,
payload={"value": "UNKNOWN"},
engine=self.name,
trace=["user expert not wired in draft"],
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,
answer_type=str(answer_type.value)
if hasattr(answer_type, "value") else str(answer_type))
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}
# Layer-1 ambiguity flag (run J): the answer is ONE defensible
# reading; the payload carries the others for the layers above
if ans.get("ambiguous"):
payload["ambiguous"] = True
payload["axis"] = ans.get("axis", "")
payload["alternatives"] = ans.get("alternatives", [])
if ans.get("quote"):
payload["quote"] = ans["quote"]
if ans.get("url"):
payload["url"] = ans["url"]
if ans.get("list_items") is not None:
payload["list_items"] = ans["list_items"]
payload["list_count"] = ans.get("list_count", len(ans["list_items"]))
if ans.get("coverage"):
payload["coverage"] = ans["coverage"]
# PR-3 — the skim notice: what the fetched articles contained beyond
# this answer (tables/infobox/link surfaces with goal signals). A
# POINTER for later steps, not evidence: it never answers a question,
# it tells the router what exists and where it lives.
skim_notices = (ans.get("stats") or {}).get("skim") or []
if skim_notices:
payload["skim"] = skim_notices[:3]
prov = {"expert": "knowledge", "source": src,
"note": ("ambiguous: several office readings exist — the "
"choice among them is not verified"
if ans.get("ambiguous") else
("source-verified: verbatim containment in trusted doc"
if ans.get("quote") else "no quote — unverified"))}
# LIST rows: the answer-level check corroborates the count outside the
# source table; combined with per-source completeness it makes the
# row verified (E3-style verified semantics, first non-stub use).
verified = False
cov = ans.get("coverage") or {}
if (isinstance(ans.get("list_items"), list) and ans["list_items"]
and cov.get("complete_per_source") and cov.get("count_corroborated")):
verified = True
prov["note"] = "count corroborated outside the source table"
if parent_question:
prov["parent_question"] = parent_question
note = "" if value.upper() != "UNKNOWN" else "knowledge returned UNKNOWN"
if streams is not None:
# THE ANSWER, in full view (run H: the first knowledge answer was
# only deducible from the fan-out that followed). Q ref + every
# field the machine will act on.
qref = qid if qid else "Q?"
if isinstance(ans.get("list_items"), list) and ans["list_items"]:
items = ans["list_items"]
shown = ", ".join(items[:8]) + (f" (+{len(items) - 8} more)" if len(items) > 8 else "")
streams.output("EXPERT",
f"{qref} -> ANSWER value={value} (list of "
f"{len(items)} members: {shown}) quote="
f"{(ans.get('quote') or '')[:60]} url="
f"{ans.get('url') or ''} [{src}]")
elif ans.get("ambiguous"):
alts = "; ".join(a.get("value", "")
for a in (ans.get("alternatives") or [])[:3])
streams.output("EXPERT",
f"{qref} -> ANSWER value={value} "
f"AMBIGUOUS ({alts}) quote="
f"{(ans.get('quote') or '')[:60]} url="
f"{ans.get('url') or ''} [{src}]")
else:
streams.output("EXPERT",
f"{qref} -> ANSWER value={value} quote="
f"{(ans.get('quote') or '')[:80]} url="
f"{ans.get('url') or ''} [{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=verified, # True only when the count is corroborated
# outside the source table (LIST rows)
note=note,
)