knowledge: remove the TRANSLATE LLM — deterministic query composition

His 23/10 weights-tightness audit found the TRANSLATE step composing
search queries from its own knowledge of the entities: 'Pedro Sánchez
2018 investiture President of the Government of Spain' for a term-start
question (the '2018' IS the answer, steered into retrieval from weights),
'Po, Adige, Tiber' proposed as entities for a question that named only
Italy. Measured over every logged TRANSLATE call of runs 22-23/10: 5/10
calls carried untraceable query terms, 6/10 untraceable entity terms.

Probed against real Wikipedia before deciding: queries composed
deterministically from question ∪ evidence put the decisive article at
top-1/2 of the search in 8 of 9 cases — the LLM's world knowledge was
never load-bearing; the search engine's own relevance was. So the step
becomes code (the law: LLMs translate, fixed code composes — and here
nothing is left to translate).

- NEW knowledge/queries.py: compose_queries() + proper_nouns/keywords
  (moved here, single source — the expert delegates). Laws: every query
  token traces to the question or an evidence row; deterministic; never
  empty. Top-N asks slice the FIRST N evidence members by source order
  (never dump all members); enumerations with one subject NE get the
  list-article shape ('List of rivers of Italy'); sentence-initial
  capitals are dropped when other NEs exist ('During', 'Ranked').
- DELETED TranslateSignature + the Predict + the stage map entry;
  the gather charges one LLM call less.
- expert.py: COMPOSE at the gather head; the context var (rendered
  only for the dead prompt) removed — evidence feeds the probe seeds,
  the composer and the guards directly.
- Tests: knowledge/tests/queries.py (12) — the sonde's cases as the
  contract, incl. the traceback law over the logged questions.
- DESIGN.md §4 + code/README honest map updated.

Suite 17/17. Live probe (real Wikipedia): rivers/Pedro/France/Po all
fetch the decisive article at top-1.
This commit is contained in:
2026-10-23 15:15:02 +02:00
parent 30d0a48f7a
commit dec1fccb53
7 changed files with 370 additions and 62 deletions
+23 -38
View File
@@ -1,7 +1,7 @@
"""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]
1. COMPOSE: question + evidence -> queries/entities [engine]
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]
@@ -25,8 +25,8 @@ from .checks import check_candidate, quote_containment
from .chunker import chunk_page
from .skim import find_quantities, skim_article
from .extract import (AnswerFromKG, ExtractSignature, Fact, SelectTableSignature,
SkimPromoteSignature, TranslateSignature,
VerifyCountSignature)
SkimPromoteSignature, VerifyCountSignature)
from .queries import compose_queries, keywords, proper_nouns
from .store import KnowledgeStore, norm_name
from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert,
tables_as_chunks, format_table_frag, parse_stop_table)
@@ -90,16 +90,10 @@ def _prop_hit(prop: str, toks: set[str]) -> bool:
def _proper_nouns(question: str) -> set[str]:
"""Capitalized non-question words: 'Italy', 'Po' — the SUBJECT of the
question. The definitive guard for 'which are the three longest rivers
of Italy?' never accepting a world table (run H: Q1 answered Nile/
Amazon/Yangtze because the top search hit was the world list and the
disjointness guard was vacuous — no evidence, nothing to check)."""
words = re.findall(r"[A-Z][a-zÀ-ÿ]+(?:'[A-Za-z]+)?", question or "")
stops = {"What", "Which", "Who", "When", "Where", "Why", "How", "The",
"Is", "Are", "Was", "Were", "In", "On", "At", "For", "Of",
"Their", "Its", "Those", "These", "That", "This"}
return {w for w in words if w not in stops}
"""The subject guard's noun extractor — delegates to knowledge/queries.py
(single source: the query composer and the guards share the NE law).
Semantics unchanged: capitalized non-question words ('Italy', 'Po')."""
return proper_nouns(question)
@dataclass
@@ -130,7 +124,6 @@ class KnowledgeExpert:
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.skim_promote = dspy.Predict(SkimPromoteSignature)
@@ -150,16 +143,10 @@ class KnowledgeExpert:
@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]
"""Deterministic lexical focus — delegates to knowledge/queries.py
(single source: the probe seeds and the query composer share the
same keyword law)."""
return keywords(question, 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.
@@ -211,9 +198,9 @@ class KnowledgeExpert:
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}"
# 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
@@ -263,17 +250,15 @@ class KnowledgeExpert:
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
# 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)
queries = [q.strip() for q in (pred.queries or []) if q.strip()][:2]
if not queries:
queries = [" ".join(kws[:3])]
entity_terms = [t.strip() for t in (pred.entities or []) if t.strip()][:4]
self._log(f"translate -> queries {queries} entities {entity_terms}", think=True)
# 3-4. gap -> search + fetch. COMPOSE (deterministic — the old
# TRANSLATE LLM, 23/10): queries from question ∪ evidence only;
# the model's own knowledge of the entities can no longer steer
# retrieval (it was putting the ANSWER into queries: 'Pedro
# Sánchez 2018 investiture…' for a term-start question).
queries, entity_terms = compose_queries(
question, evidence_entities=ev_entities, list_mode=list_mode)
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