From 12fb3c78b2cfe3755e707068b534f4f0eb767138 Mon Sep 17 00:00:00 2001 From: OniricApps Date: Wed, 28 Oct 2026 12:41:31 +0100 Subject: [PATCH] formalizing Named Entity Recognition types, Mask -> NER --- code/.idea/.gitignore | 3 ++ code/.idea/floop.iml | 11 +++++++ .../inspectionProfiles/Project_Default.xml | 13 ++++++++ .../inspectionProfiles/profiles_settings.xml | 6 ++++ code/.idea/modules.xml | 8 +++++ code/.idea/vcs.xml | 6 ++++ code/floop/anonymize.py | 32 +++++++++++-------- code/floop/dspy_modules.py | 8 ++--- code/floop/llm.py | 2 +- code/src/code/__init__.py | 2 ++ code/tests/anonymize.py | 26 ++++++++++++++- 11 files changed, 98 insertions(+), 19 deletions(-) create mode 100644 code/.idea/.gitignore create mode 100644 code/.idea/floop.iml create mode 100644 code/.idea/inspectionProfiles/Project_Default.xml create mode 100644 code/.idea/inspectionProfiles/profiles_settings.xml create mode 100644 code/.idea/modules.xml create mode 100644 code/.idea/vcs.xml create mode 100644 code/src/code/__init__.py diff --git a/code/.idea/.gitignore b/code/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/code/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/code/.idea/floop.iml b/code/.idea/floop.iml new file mode 100644 index 0000000..097bb84 --- /dev/null +++ b/code/.idea/floop.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/code/.idea/inspectionProfiles/Project_Default.xml b/code/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..ad37791 --- /dev/null +++ b/code/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,13 @@ + + + + \ No newline at end of file diff --git a/code/.idea/inspectionProfiles/profiles_settings.xml b/code/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000..105ce2d --- /dev/null +++ b/code/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/code/.idea/modules.xml b/code/.idea/modules.xml new file mode 100644 index 0000000..bd9c966 --- /dev/null +++ b/code/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/code/.idea/vcs.xml b/code/.idea/vcs.xml new file mode 100644 index 0000000..6c0b863 --- /dev/null +++ b/code/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/code/floop/anonymize.py b/code/floop/anonymize.py index 182c22c..f6c6eff 100644 --- a/code/floop/anonymize.py +++ b/code/floop/anonymize.py @@ -15,29 +15,33 @@ 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="PERSON, ORGANIZATION, PLACE, WORK, EVENT, or OTHER") + desc="; ".join(f"{kind}: {definition}" + for kind, definition in ENTITY_TYPES.items())) -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() +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") -# 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). @@ -50,7 +54,9 @@ def apply_mask(question: str, entities: list[NamedEntity]) -> tuple[str, dict]: if not name or name not in masked: continue kind = ent.kind.strip().upper() - prefix = _PREFIX.get(kind, "OTHER") + 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 diff --git a/code/floop/dspy_modules.py b/code/floop/dspy_modules.py index ec2ed71..eca77b8 100644 --- a/code/floop/dspy_modules.py +++ b/code/floop/dspy_modules.py @@ -20,8 +20,8 @@ try: except ImportError: # pragma: no cover — dspy <3.x AdapterParseError = type("AdapterParseError", (Exception,), {"lm_response": ""}) -from .anonymize import (EntityMaskSignature, apply_mask, identity_answer, - restore_mask) +from .anonymize import (NamedEntityRecognitionSignature, apply_mask, + identity_answer, restore_mask) class Subquestion(BaseModel): @@ -141,7 +141,7 @@ class FloopModules: self.expert = predict(ExpertSignature) self.missing = predict(MissingSignature) self.answer = predict(AnswerSignature) - self.mask = predict(EntityMaskSignature) + self.mask = predict(NamedEntityRecognitionSignature) def init_decompose(self, question: str) -> tuple[list[dict], str]: """(parsed subquestions, raw model output). The machine decides what @@ -178,7 +178,7 @@ class FloopModules: """Mask named entities to typed placeholders. No entity found (or the mask call dies) -> the question passes unchanged, mask map empty.""" try: - pred = self.mask(question=question) + pred = self.mask(text=question) entities = pred.entities or [] except AdapterParseError: return question, {} diff --git a/code/floop/llm.py b/code/floop/llm.py index 6cfe136..46d90e9 100644 --- a/code/floop/llm.py +++ b/code/floop/llm.py @@ -244,7 +244,7 @@ _STAGE_BY_MODULE = { "Expert": "EXPERT", "Missing": "MISSING", "Answer": "ANSWER", - "EntityMaskSignature": "MASK", + "NamedEntityRecognitionSignature": "MASK", "KnowledgeExpert": "knowledge", "InitSignature": "INIT", "RouteSignature": "ROUTE", diff --git a/code/src/code/__init__.py b/code/src/code/__init__.py new file mode 100644 index 0000000..83b067d --- /dev/null +++ b/code/src/code/__init__.py @@ -0,0 +1,2 @@ +def main() -> None: + print("Hello from code!") diff --git a/code/tests/anonymize.py b/code/tests/anonymize.py index e915b4c..2766768 100644 --- a/code/tests/anonymize.py +++ b/code/tests/anonymize.py @@ -26,7 +26,9 @@ from dspy._vendor.lm15 import Response, TextPart, Message, Usage from dspy.utils.exceptions import AdapterParseError from floop.dspy_modules import FloopModules -from floop.anonymize import NamedEntity, apply_mask, identity_answer, restore_mask +from floop.anonymize import ( + ENTITY_TYPES, NamedEntity, apply_mask, identity_answer, restore_mask, +) def _lm(script: list[str]) -> None: @@ -75,6 +77,27 @@ def test_apply_restore_deterministic(): print("ok: apply/restore deterministic (longest-first, typed, reorder-safe)") +def test_entity_types_drive_schema_and_masks(): + description = NamedEntity.model_fields["kind"].json_schema_extra["desc"] + for kind, definition in ENTITY_TYPES.items(): + assert f"{kind}: {definition}" in description + + entities = [NamedEntity(name=name, kind=kind) for kind, name in ( + ("PERSON", "Ada"), ("ORGANIZATION", "Acme"), + ("LOCATION", "Paris"), ("DATE", "2026"), + ("PRODUCT", "Widget"), + )] + entities.append(NamedEntity(name="Unknown", kind="OTHER")) + masked, restore = apply_mask("Ada Acme Paris 2026 Widget Unknown", entities) + assert masked == ( + "PERSON_1 ORGANIZATION_1 LOCATION_1 DATE_1 PRODUCT_1 Unknown") + assert restore == { + "PERSON_1": "Ada", "ORGANIZATION_1": "Acme", + "LOCATION_1": "Paris", "DATE_1": "2026", "PRODUCT_1": "Widget", + } + print("ok: schema descriptions and mask prefixes use the shared entity types") + + def test_init_decompose_masks_and_restores(): # script: first call = MASK, second = INIT _lm([_MASKED_ENTS, _TWO_SUBS]) @@ -147,6 +170,7 @@ def test_mask_death_passthrough(): if __name__ == "__main__": test_apply_restore_deterministic() + test_entity_types_drive_schema_and_masks() test_init_decompose_masks_and_restores() test_no_entities_passthrough() test_identity_subquestion_seeded()