"""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