Remove the TRANSLATE LLM: deterministic query composition #19
+1
-1
@@ -48,7 +48,7 @@ Compare: `--baseline` vs the loop's many small directed calls.
|
||||
| MISSING — gap decomposition on stuck goal | real (dspy) | `floop/dspy_modules.py` |
|
||||
| ROUTE — one LLM judgement over the catalogue | real (dspy) | `floop/dspy_modules.py` |
|
||||
| Expert attendants (the draft answer) | **BASELINE engine**: LLM answers from its weights; `verified=False`; source recorded (`model_weights`/`given_evidence`) | `floop/engine.py` |
|
||||
| **knowledge** expert | **REAL pipeline** (2026-10-17): KG probe (entity+relation, stemmed) -> TRANSLATE (queries+entities from context) -> en.wikipedia search -> fetch_rich (text + wikitext tables) -> section chunks -> lexical gate -> EXTRACT (verbatim quotes) -> containment check -> merge (4 contradiction cases) -> answer from quoted rows. Fallback: baseline LLM on pipeline failure. | `knowledge/` + `floop/engine.py:KnowledgeEngine` |
|
||||
| **knowledge** expert | **REAL pipeline** (2026-10-17): KG probe (entity+relation, stemmed) -> COMPOSE queries (deterministic, from question ∪ evidence — the old TRANSLATE LLM removed 23/10) -> en.wikipedia search -> fetch_rich (text + wikitext tables) -> section chunks -> lexical gate -> EXTRACT (verbatim quotes) -> containment check -> merge (4 contradiction cases) -> answer from quoted rows. Fallback: baseline LLM on pipeline failure. | `knowledge/` + `floop/engine.py:KnowledgeEngine` |
|
||||
| Arrival check (type check + contradiction) | **STUB**: only UNKNOWN refusal | `machine._append_checked` |
|
||||
| Prover (stop condition, derivability) | **STUB**: question stack terminal | `machine._finish` |
|
||||
| `user` expert | not wired — explicit failure row | `floop/engine.py` |
|
||||
|
||||
@@ -165,7 +165,6 @@ _STAGE_BY_MODULE = {
|
||||
"AnswerSignature": "ANSWER",
|
||||
"ExtractSignature": "EXTRACT",
|
||||
"AnswerFromKG": "answer_kg",
|
||||
"TranslateSignature": "TRANSLATE",
|
||||
"SelectTableSignature": "SELECT_TABLE",
|
||||
"VerifyCountSignature": "VERIFY_COUNT",
|
||||
"SkimPromoteSignature": "PROMOTE",
|
||||
|
||||
@@ -118,8 +118,13 @@ One routed knowledge question = one internal pipeline run, bounded by budget:
|
||||
```
|
||||
question instantiate (already done by the machine)
|
||||
│
|
||||
▼ TRANSLATE (LLM): question + answer_type → retrieval focus:
|
||||
│ keywords, entry entities, what shape of fact closes the gap
|
||||
▼ COMPOSE (engine, 23/10 — the old TRANSLATE LLM removed): question ∪
|
||||
│ evidence → queries + entity terms. Every token traces to the
|
||||
│ question or an evidence row; the model's own knowledge of the
|
||||
│ entities can no longer steer retrieval (it was putting the
|
||||
│ ANSWER into queries). Top-N asks slice the first N evidence
|
||||
│ members by source order; enumerations get the list-article
|
||||
│ shape ('List of rivers of Italy').
|
||||
▼ KG PROBE (engine): BFS from seeds → candidate edges + linked quotes
|
||||
│ gap report: is the question's answer_type coverable from what's found?
|
||||
│ YES → skip gather, go to SELECT
|
||||
@@ -135,10 +140,14 @@ question instantiate (already done by the machine)
|
||||
▼ return: top-k rows payload {quote, url, access_date, kg_corroboration}
|
||||
```
|
||||
|
||||
LLM calls: TRANSLATE, EXTRACT-per-chunk (+ retries), and nothing else — the
|
||||
probe, search, chunking, checking, merging, selecting are all engines. That is
|
||||
the law compliance: the LLM translates; deterministic code decides what is
|
||||
valid, what is dedupe, what is ranked.
|
||||
LLM calls: EXTRACT-per-chunk (+ retries), SELECT TABLE (lists), VERIFY
|
||||
COUNT, SKIM PROMOTE, and ANSWER — and nothing else. The query
|
||||
composition, probe, search, chunking, checking, merging, selecting are
|
||||
all engines. That is the law compliance: the LLM translates; deterministic
|
||||
code decides what is valid, what is dedupe, what is ranked — and since
|
||||
23/10 even the retrieval focus is code (the old TRANSLATE LLM became
|
||||
`knowledge/queries.py`: every query token traces to question ∪ evidence,
|
||||
so no model weight ever steers retrieval).
|
||||
|
||||
## 5. Context budget & chunking (the 16–32k constraint)
|
||||
|
||||
@@ -307,9 +316,10 @@ against the stored table text — the same string the parser produced — so the
|
||||
check stays verbatim and deterministic. The wikitext raw form is kept in the
|
||||
document artifact for audit.
|
||||
|
||||
**Budget law in the LIST path.** TRANSLATE + SELECT TABLE are the only LLM
|
||||
calls (2 + retries); ingestion and aggregation are free. A 500-row table
|
||||
costs the same LLM budget as a 5-row one — the cost of an enumeration is
|
||||
**Budget law in the LIST path.** SELECT TABLE (and the optional VERIFY
|
||||
COUNT) are the only LLM calls; ingestion and aggregation are free (the
|
||||
query composition is engine since 23/10). A 500-row table costs the
|
||||
same LLM budget as a 5-row one — the cost of an enumeration is
|
||||
O(1) in the size of the list.
|
||||
|
||||
## 12. Answer-level verification — the CHECK step for answers (2026-10-19)
|
||||
|
||||
+23
-38
@@ -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
|
||||
|
||||
@@ -28,19 +28,6 @@ class Fact(BaseModel):
|
||||
desc="VERBATIM quote from the text that states the fact: the FULL sentence or table row, copied exactly (at least 10 characters)")
|
||||
|
||||
|
||||
class TranslateSignature(dspy.Signature):
|
||||
"""You are the TRANSLATE step of a knowledge machine. Turn the question
|
||||
into Wikipedia search queries AND resolved entity terms. Resolve
|
||||
references ('that state', 'the same river') using the context: the original
|
||||
question and the evidence rows already gathered."""
|
||||
question: str = dspy.InputField()
|
||||
context: str = dspy.InputField(desc="the original question + evidence rows with answers already found; resolve pronouns from here; may be empty")
|
||||
queries: list[str] = dspy.OutputField(
|
||||
desc="1-2 Wikipedia search queries, most specific first")
|
||||
entities: list[str] = dspy.OutputField(
|
||||
desc="the resolved entity names the answer is about")
|
||||
|
||||
|
||||
class ExtractSignature(dspy.Signature):
|
||||
"""You are the EXTRACT step of a knowledge machine. From the given text,
|
||||
extract the facts that help answer the question. Each fact carries its
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
"""Deterministic query composition — the old TRANSLATE step as fixed code.
|
||||
|
||||
His 23/10 weights-tightness call: the TRANSLATE LLM was composing search
|
||||
queries from its OWN knowledge of the entities — 'Pedro Sánchez 2018
|
||||
investiture President of the Government of Spain' (the '2018' IS the
|
||||
answer to that term-start question, steered into retrieval from
|
||||
weights), 'Po, Adige, Tiber' proposed for a question that named only
|
||||
Italy. Probed against real Wikipedia over every logged TRANSLATE call of
|
||||
runs 22-23/10: queries composed from the question's named entities and
|
||||
keywords (+ the evidence's resolved entities) put the decisive article at
|
||||
top-1/2 in 8 of 9 cases — the LLM's world knowledge was never the
|
||||
load-bearing part; the search engine's own relevance was. So the step
|
||||
becomes code.
|
||||
|
||||
Laws:
|
||||
- Material: question ∪ evidence only. Every token of every query traces
|
||||
to the question or an evidence row — the weights-tightness law, now
|
||||
structural instead of prompted.
|
||||
- Deterministic: same inputs -> same queries, same order, every time.
|
||||
- Never empty: a question with no NEs still gets its keyword join.
|
||||
- Top-N over a list row in evidence slices the FIRST N members by source
|
||||
order (the ranked-list law) — never dumps all members into one query
|
||||
('Ranked Italy Maira K1 K2' retrieved nothing when a naive composer
|
||||
tried exactly that).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
|
||||
_CAP_RE = re.compile(r"[A-Z][a-zÀ-ÿ]+(?:'[A-Za-z]+)?")
|
||||
|
||||
# capitalized words that are question machinery, not subjects
|
||||
_CAP_STOPS = {"What", "Which", "Who", "When", "Where", "Why", "How", "The",
|
||||
"Is", "Are", "Was", "Were", "In", "On", "At", "For", "Of",
|
||||
"Their", "Its", "Those", "These", "That", "This"}
|
||||
|
||||
# content-word stoplist (single source: probe seeds and composer share it)
|
||||
_KW_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"}
|
||||
|
||||
_N_WORDS = {"two": 2, "three": 3, "four": 4, "five": 5, "six": 6,
|
||||
"seven": 7, "eight": 8, "nine": 9, "ten": 10, "eleven": 11,
|
||||
"twelve": 12}
|
||||
|
||||
|
||||
def _caps_in_order(question: str) -> list[str]:
|
||||
"""Capitalized words in question order, deduped."""
|
||||
return list(dict.fromkeys(_CAP_RE.findall(question or "")))
|
||||
|
||||
|
||||
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)."""
|
||||
return {w for w in _caps_in_order(question) if w not in _CAP_STOPS}
|
||||
|
||||
|
||||
def _subjects(question: str) -> list[str]:
|
||||
"""NEs in question order. The SENTENCE-INITIAL word is dropped when
|
||||
other NEs exist: it is capitalized by sentence rules, not because it
|
||||
names an entity ('During what years…', 'Ranked by length…'). When it
|
||||
is the ONLY capitalized word it is kept — it may be the subject
|
||||
('Po length?')."""
|
||||
ne_set = proper_nouns(question)
|
||||
nes = [w for w in _caps_in_order(question) if w in ne_set]
|
||||
first = (question or "").strip().split(" ")[0] if question else ""
|
||||
if len(nes) > 1 and nes and nes[0] == first:
|
||||
nes = nes[1:]
|
||||
return nes
|
||||
|
||||
|
||||
def keywords(question: str, k: int = 6) -> list[str]:
|
||||
"""Deterministic lexical focus: content words of the question."""
|
||||
words = [w.lower() for w in WORD_RE.findall(question)]
|
||||
seen: list[str] = []
|
||||
for w in words:
|
||||
if w not in _KW_STOPS and len(w) > 2 and w not in seen:
|
||||
seen.append(w)
|
||||
return seen[:k]
|
||||
|
||||
|
||||
def _plural_head(kws: list[str]) -> str:
|
||||
"""The enumeration's head noun: first plural content word ('rivers',
|
||||
'countries'). Questions with no plural get no list variant."""
|
||||
return next((w for w in kws if w.endswith("s") and len(w) > 4), "")
|
||||
|
||||
|
||||
def _top_n(question: str) -> int | None:
|
||||
"""The N of a top-N ask ('which three of these…', 'top 5 …'), if any.
|
||||
Only meaningful when the evidence names a list to slice."""
|
||||
for w in WORD_RE.findall(question.casefold()):
|
||||
if w in _N_WORDS:
|
||||
return _N_WORDS[w]
|
||||
if w.isdigit() and 1 <= int(w) <= 12:
|
||||
return int(w)
|
||||
return None
|
||||
|
||||
|
||||
def compose_queries(question: str,
|
||||
evidence_entities: list[str] | None = None,
|
||||
list_mode: bool = False) -> tuple[list[str], list[str]]:
|
||||
"""Wikipedia search queries + entity terms from question ∪ evidence.
|
||||
|
||||
Returns (queries, entities), both deterministic. Queries (≤ 2, the
|
||||
per-gather search cost of the LLM step this replaces):
|
||||
[0] top-N ask over evidence members -> the FIRST N by source order
|
||||
('Po Adige Tiber' — the members themselves retrieve their
|
||||
articles); enumeration with a subject NE -> subject + head
|
||||
noun ('Italy rivers'); multi-NE -> the join ('Pedro Sanchez
|
||||
President'); single NE -> NE + salient keywords ('Po length');
|
||||
no NE but evidence -> the evidence's entities ('that state' +
|
||||
E1:France -> 'France'); else keyword join
|
||||
[1] enumeration with exactly ONE subject NE -> the Wikipedia
|
||||
list-article shape ('List of rivers of Italy'); else the
|
||||
attribute variant ('Pedro term begin'). A second NE makes the
|
||||
list shape ambiguous ('List of countries of Union') — skipped.
|
||||
entities: sliced evidence members (top-N) or question NEs, then the
|
||||
rest of the evidence entities, question order first.
|
||||
|
||||
Every token of every query traces to the question or the evidence.
|
||||
"""
|
||||
nes = _subjects(question)
|
||||
kws = keywords(question)
|
||||
ev = [e for e in (evidence_entities or []) if e]
|
||||
ne_lower = {n.casefold() for n in nes}
|
||||
salient = [w for w in kws if w not in ne_lower]
|
||||
n_ask = _top_n(question)
|
||||
|
||||
queries: list[str] = []
|
||||
if ev and n_ask:
|
||||
# top-N over a list row in evidence: the first N members by source
|
||||
# order carry the query (a ranked list ranks; unranked order is
|
||||
# still the source's own). Never all members at once.
|
||||
queries.append(" ".join(ev[:n_ask]))
|
||||
elif list_mode and nes and (plural := _plural_head(kws)):
|
||||
queries.append(" ".join(nes[:2] + [plural]))
|
||||
elif len(nes) >= 2:
|
||||
queries.append(" ".join(nes[:3]))
|
||||
elif nes and salient:
|
||||
queries.append(" ".join([nes[0], *salient[:2]]))
|
||||
elif nes:
|
||||
queries.append(nes[0])
|
||||
elif ev:
|
||||
queries.append(" ".join(ev[:3]))
|
||||
elif kws:
|
||||
queries.append(" ".join(kws[:3]))
|
||||
else:
|
||||
queries.append(question.strip()[:60] or "wikipedia")
|
||||
|
||||
variant = ""
|
||||
if list_mode and len(nes) == 1 and (plural := _plural_head(kws)):
|
||||
variant = f"List of {plural} of {nes[0]}"
|
||||
if not variant and salient:
|
||||
base = nes[0] if nes else (ev[0] if ev else "")
|
||||
if base and base.casefold() not in [q.casefold() for q in queries]:
|
||||
variant = " ".join([base, *salient[:2]])
|
||||
if variant and variant not in queries:
|
||||
queries.append(variant)
|
||||
|
||||
entities = list(dict.fromkeys((ev[:n_ask] if ev and n_ask else [])
|
||||
+ nes + ev))[:8]
|
||||
return queries[:2], entities
|
||||
@@ -0,0 +1,160 @@
|
||||
"""Deterministic query composition (the old TRANSLATE LLM, removed 23/10).
|
||||
|
||||
Laws under test (his weights-tightness call):
|
||||
1. Every token of every query traces to the question or the evidence —
|
||||
the model's own knowledge of the entities can no longer steer
|
||||
retrieval. The 22/10 logs caught the LLM putting the ANSWER into
|
||||
queries ('Pedro Sánchez 2018 investiture…' for a term-start question).
|
||||
2. Deterministic: same inputs -> same queries, same order, every time.
|
||||
3. Never empty: a question with no entities still gets its keyword join.
|
||||
4. Top-N over a list row in evidence slices the FIRST N members by source
|
||||
order — never dumps all members into one query.
|
||||
5. The subject NE + plural head noun surface the Wikipedia list article
|
||||
('List of rivers of Italy'), the source enumerations actually live in.
|
||||
|
||||
No network, no LLM. Run: uv run python knowledge/tests/queries.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) # repo root
|
||||
|
||||
from knowledge.queries import compose_queries, keywords, proper_nouns
|
||||
|
||||
|
||||
def test_single_entity_with_attribute():
|
||||
q, e = compose_queries("What is the length of Po?")
|
||||
assert q == ["Po length"], q
|
||||
assert e == ["Po"], e
|
||||
print("ok single entity: NE + salient keywords ('Po length')")
|
||||
|
||||
|
||||
def test_multi_entity_join():
|
||||
q, e = compose_queries("What is the discharge of the Po, Adige and Tiber?")
|
||||
assert q[0].startswith("Po"), q
|
||||
assert "Adige" in q[0] and "Tiber" in q[0], q
|
||||
print("ok multi-NE join:", q)
|
||||
|
||||
|
||||
def test_enumeration_list_variant():
|
||||
q, e = compose_queries("What are the three longest rivers of Italy?",
|
||||
list_mode=True)
|
||||
assert q == ["Italy rivers", "List of rivers of Italy"], q
|
||||
print("ok enumeration: subject + plural, then the list-article shape")
|
||||
|
||||
|
||||
def test_evidence_entities_carry_reference_resolution():
|
||||
# 'that state' + E1: France — the evidence resolves the reference,
|
||||
# not the model's knowledge of anything
|
||||
q, e = compose_queries("What is the longest river in that state?",
|
||||
evidence_entities=["France"])
|
||||
assert q == ["France"], q
|
||||
assert e == ["France"], e
|
||||
print("ok reference resolution from evidence, zero weights")
|
||||
|
||||
|
||||
def test_top_n_slices_evidence_by_source_order():
|
||||
# the case the LLM 'helped' with by guessing Po/Adige/Tiber from its
|
||||
# weights — the members are now sliced from the evidence row itself
|
||||
ev = ["Po", "Adige", "Tiber", "Dora", "Reno", "Ticino"]
|
||||
q, e = compose_queries(
|
||||
"Ranked by length, which three of these rivers are the longest in Italy?",
|
||||
evidence_entities=ev)
|
||||
assert q[0] == "Po Adige Tiber", q
|
||||
assert e[:3] == ["Po", "Adige", "Tiber"], e
|
||||
assert len(e) <= 8, e
|
||||
print("ok top-N ask: first N evidence members by source order")
|
||||
|
||||
|
||||
def test_top_n_never_dumps_all_members():
|
||||
ev = [f"R{i}" for i in range(22)]
|
||||
q, e = compose_queries("which three of these rivers are longest?",
|
||||
evidence_entities=ev)
|
||||
assert q[0].split() == ["R0", "R1", "R2"], q
|
||||
print("ok 22-member list: query carries only the sliced 3")
|
||||
|
||||
|
||||
def test_two_subject_ne_gets_no_list_shape():
|
||||
# 'List of countries of Union' would be garbage — with 2+ NEs the
|
||||
# list-article shape is skipped
|
||||
q, e = compose_queries(
|
||||
"Which countries in the continent of Europe are not members of the European Union?",
|
||||
list_mode=True)
|
||||
assert not any(x.startswith("List of") for x in q), q
|
||||
print("ok two subject NEs: no ambiguous list shape:", q)
|
||||
|
||||
|
||||
def test_no_entities_keyword_join():
|
||||
q, e = compose_queries("What is the speed of light?")
|
||||
assert q == ["speed light"], q
|
||||
assert e == [], e
|
||||
print("ok no NEs: keyword join, never empty")
|
||||
|
||||
|
||||
def test_sentence_initial_capital_not_a_subject():
|
||||
# 'During'/'Ranked' are capitalized by sentence rules; with other NEs
|
||||
# present they must not steer the query
|
||||
q, e = compose_queries("During what years did Pedro Sanchez serve as President?")
|
||||
assert q[0].startswith("Pedro"), q
|
||||
assert "During" not in q[0], q
|
||||
print("ok sentence-initial capital dropped when other NEs exist:", q)
|
||||
|
||||
|
||||
def test_weights_never_enter_queries():
|
||||
# the regression the audit found: model knowledge injected into
|
||||
# retrieval ('2018 investiture', 'Prime Minister of Spain' for a
|
||||
# question that says neither). Compose the same logged questions and
|
||||
# assert every query token traces to question ∪ evidence.
|
||||
cases = [
|
||||
("When did Pedro Sanchez's term as President begin (the start date of their presidency)?", []),
|
||||
("Which country's government does Pedro Sanchez lead as President?", []),
|
||||
("What are the three longest rivers of Italy?", []),
|
||||
("What is the length of Po?", []),
|
||||
]
|
||||
for question, ev in cases:
|
||||
qs, _ = compose_queries(question, evidence_entities=ev)
|
||||
material = set(keywords(question)) | {
|
||||
w.casefold() for w in
|
||||
__import__("re").findall(r"[A-Za-zÀ-ÿ0-9']+", question)} | {
|
||||
w.casefold() for w in ev}
|
||||
for query in qs:
|
||||
for tok in __import__("re").findall(r"[A-Za-zÀ-ÿ0-9']+", query):
|
||||
assert tok.casefold() in material, \
|
||||
f"untraceable token {tok!r} in {query!r} for {question!r}"
|
||||
print("ok every query token traces to question ∪ evidence (logged cases)")
|
||||
|
||||
|
||||
def test_deterministic():
|
||||
args = ("What are the three longest rivers of Italy?", None, True)
|
||||
r1 = compose_queries(*args)
|
||||
r2 = compose_queries(*args)
|
||||
assert r1 == r2
|
||||
print("ok same inputs -> same outputs")
|
||||
|
||||
|
||||
def test_proper_nouns_unchanged():
|
||||
# the guards depend on these exact semantics (guards.py contract)
|
||||
assert proper_nouns("Which are the three longest rivers of Italy?") == {"Italy"}
|
||||
assert proper_nouns("What is the discharge of the Po, Adige and Tiber?") == {"Po", "Adige", "Tiber"}
|
||||
assert keywords("Which are the three longest rivers of Italy?") == \
|
||||
["three", "longest", "rivers", "italy"]
|
||||
print("ok proper_nouns/keywords semantics unchanged for the guards")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_single_entity_with_attribute()
|
||||
test_multi_entity_join()
|
||||
test_enumeration_list_variant()
|
||||
test_evidence_entities_carry_reference_resolution()
|
||||
test_top_n_slices_evidence_by_source_order()
|
||||
test_top_n_never_dumps_all_members()
|
||||
test_two_subject_ne_gets_no_list_shape()
|
||||
test_no_entities_keyword_join()
|
||||
test_sentence_initial_capital_not_a_subject()
|
||||
test_weights_never_enter_queries()
|
||||
test_deterministic()
|
||||
test_proper_nouns_unchanged()
|
||||
print("\nqueries tests passed")
|
||||
Reference in New Issue
Block a user