His two-part direction after the PR-16 live run (the model spent a subquestion asking 'who is PERSON_1?'): 1. INIT desc now says masked entities (PERSON_1, ORGANIZATION_1...) are ALREADY-RESOLVED named entities — treat each as a known specific entity; do not ask what or who the placeholder is. 2. Safety net: identity_answer() detects a subquestion that ONLY asks who/what one placeholder refers to — the mask map already knows. The machine seeds it as evidence (engine=mask:seed, verified, zero LLM calls) instead of routing it to an expert. Detection is deterministic and conservative by law: exactly one placeholder in the text, literal 'who/what is <ph>' (ending there or in punctuation — possessives like 'who is PERSON_1's predecessor' do NOT match) or the text names the mask mechanism. Detection runs on the MASKED text (placeholders still present) before restore. VERIFIED: tests/anonymize.py 6/6 (seed marking, conservative detection incl. possessives/comparatives/no-placeholder forms); suite 15/15. Live E2E (glm-5.3-flash): with the new desc INIT returns exactly the TWO subquestions he wants (term years + predecessor) — no identity question, seed unused but armed; run answers Rajoy (E1+E2, 30 calls).
99 lines
4.1 KiB
Python
99 lines
4.1 KiB
Python
"""Query anonymization before INIT (his design, 22/10): the model must
|
|
decompose the question's SHAPE, not lean on its knowledge of the people in
|
|
it. Named entities are masked to typed placeholders (PERSON_1, ORGANIZATION_1,
|
|
...) before INIT sees the query; the placeholders are restored in the
|
|
returned subquestions — deterministically, by exact string replacement.
|
|
|
|
LLMs translate (NER proposal); fixed code applies and restores (ALGORITHM
|
|
§7: LLMs never decide). The mask map is run-scoped state, not a prompt.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
|
|
import dspy
|
|
from pydantic import BaseModel
|
|
|
|
|
|
class NamedEntity(BaseModel):
|
|
"""One named entity found in the question."""
|
|
name: str = dspy.OutputField(
|
|
desc="the entity's exact surface text as it appears in the question, copied verbatim")
|
|
kind: str = dspy.OutputField(
|
|
desc="PERSON, ORGANIZATION, PLACE, WORK, EVENT, or OTHER")
|
|
|
|
|
|
class EntityMaskSignature(dspy.Signature):
|
|
"""You are the MASK step of a reasoning machine. Find the named entities
|
|
in the question — people, organizations, places, titles of works, events.
|
|
Copy each one's text exactly as it appears; do not add entities that are
|
|
not explicitly named."""
|
|
question: str = dspy.InputField()
|
|
entities: list[NamedEntity] = dspy.OutputField(
|
|
desc="the named entities found; empty when none")
|
|
|
|
|
|
# placeholder order: PERSON_1, PERSON_2, ORGANIZATION_1, ...
|
|
_PREFIX = {"PERSON": "PERSON", "ORGANIZATION": "ORGANIZATION", "PLACE": "PLACE",
|
|
"WORK": "WORK", "EVENT": "EVENT", "OTHER": "OTHER"}
|
|
|
|
|
|
def apply_mask(question: str, entities: list[NamedEntity]) -> tuple[str, dict]:
|
|
"""Mask the question deterministically. Longer names first (so
|
|
'Pedro Sánchez Pérez-Castejón' is masked before its substrings).
|
|
Returns (masked_question, restore_map placeholder -> original)."""
|
|
restore: dict[str, str] = {}
|
|
counters: dict[str, int] = {}
|
|
masked = question
|
|
for ent in sorted(entities, key=lambda e: len(e.name), reverse=True):
|
|
name = ent.name.strip()
|
|
if not name or name not in masked:
|
|
continue
|
|
kind = ent.kind.strip().upper()
|
|
prefix = _PREFIX.get(kind, "OTHER")
|
|
counters[prefix] = counters.get(prefix, 0) + 1
|
|
ph = f"{prefix}_{counters[prefix]}"
|
|
if ph in restore: # same surface text twice: keep one mask
|
|
continue
|
|
masked = masked.replace(name, ph)
|
|
restore[ph] = name
|
|
return masked, restore
|
|
|
|
|
|
def restore_mask(text: str, restore: dict[str, str]) -> str:
|
|
"""Restore placeholders to the original names, longest first (so
|
|
PERSON_10 is not eaten by PERSON_1)."""
|
|
for ph, name in sorted(restore.items(), key=lambda kv: len(kv[0]),
|
|
reverse=True):
|
|
text = text.replace(ph, name)
|
|
return text
|
|
|
|
|
|
# an identity question about ONE placeholder — the model asking who/what
|
|
# the mask refers to. Detection lives in identity_answer: conservative
|
|
# by law (his: never over-detect) — 'who/what is <ph>' exactly, or the
|
|
# text names the mask mechanism ('placeholder', 'refer(s) to').
|
|
|
|
|
|
def identity_answer(masked_text: str, restore: dict[str, str]) -> str | None:
|
|
"""If a subquestion only asks who/what one placeholder refers to, the
|
|
answer is the mask map itself — no expert ever needed. None otherwise.
|
|
|
|
Conservative by law (never over-detect): exactly one placeholder in
|
|
the text, and the question is literally 'who/what is <ph>' (ending
|
|
there or in punctuation — 'who is PERSON_1's predecessor' does NOT
|
|
match) or it names the mask mechanism ('placeholder', 'refer(s) to')."""
|
|
phs = [ph for ph in restore if re.search(rf"\b{re.escape(ph)}\b",
|
|
masked_text)]
|
|
if len(phs) != 1:
|
|
return None
|
|
ph = phs[0]
|
|
t = masked_text.strip()
|
|
literal = re.match(
|
|
rf"^(?:who|what)\s+(?:is|are)\s+{re.escape(ph)}(?=$|[\s,.?!:;)\"'])",
|
|
t, flags=re.IGNORECASE)
|
|
mechanism = any(k in t.casefold() for k in
|
|
("placeholder", "refer to", "refers to"))
|
|
if literal or mechanism:
|
|
return restore[ph]
|
|
return None |