120 lines
5.2 KiB
Python
120 lines
5.2 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
|
|
|
|
|
|
ENTITY_TYPES = {
|
|
"PERSON": "individual human beings or legal entities",
|
|
"ORGANIZATION": "companies, institutions, and groups",
|
|
"LOCATION": "geographical locations such as cities and countries",
|
|
"DATE": "specific dates or time periods",
|
|
"PRODUCT": "items or goods, including brands and models",
|
|
}
|
|
|
|
|
|
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="; ".join(f"{kind}: {definition}"
|
|
for kind, definition in ENTITY_TYPES.items()))
|
|
|
|
|
|
class NamedEntityRecognitionSignature(dspy.Signature):
|
|
"""Find the named entities in the input text. Use only the kinds and
|
|
definitions in the NamedEntity schema. Copy each entity's text exactly
|
|
as it appears; do not add entities that are not explicitly named."""
|
|
text: str = dspy.InputField()
|
|
entities: list[NamedEntity] = dspy.OutputField(
|
|
desc="the named entities found; empty when none")
|
|
|
|
|
|
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()
|
|
if kind not in ENTITY_TYPES:
|
|
continue
|
|
prefix = kind
|
|
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 with the placeholder as the
|
|
REFERENT: 'refer(s) to' must govern <ph> DIRECTLY ('what does
|
|
PERSON_1 refer to?', 'the placeholder PERSON_1 refers to…'). A bare
|
|
'refer to' anywhere in the sentence no longer fires — his 23/10 run:
|
|
INIT's hidden-precondition phrasing 'does the title "President"
|
|
refer to in relation to PERSON_1?' asked about the TITLE, the old
|
|
clause seeded 'Pedro Sanchez' as the answer to which office was
|
|
meant (a false positive with wrong semantics)."""
|
|
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()
|
|
# lookahead: end-of-sentence/punctuation AFTER the placeholder — but
|
|
# never an apostrophe: "PERSON_1's predecessor" is a possessive, not an
|
|
# identity question (pre-existing trap found while verifying the 23/10
|
|
# fix; the old test only covered 'Who WAS…', which dodges the literal)
|
|
literal = re.match(
|
|
rf"^(?:who|what)\s+(?:is|are)\s+{re.escape(ph)}(?=$|[\s,.?!:;)\"])",
|
|
t, flags=re.IGNORECASE)
|
|
if literal:
|
|
return restore[ph]
|
|
# mechanism mention: strict — the placeholder must be the REFERENT of
|
|
# 'refer(s) to', not merely present in a sentence that uses the verb
|
|
for pat in (rf"\brefer(?:s)?\s+to\s+{re.escape(ph)}\b",
|
|
rf"{re.escape(ph)}\s+refer(?:s)?\s+to\b"):
|
|
if re.search(pat, t, flags=re.IGNORECASE):
|
|
return restore[ph]
|
|
return None |