formalizing Named Entity Recognition types, Mask -> NER

This commit is contained in:
2026-10-28 12:41:31 +01:00
parent a007e8da25
commit 12fb3c78b2
11 changed files with 98 additions and 19 deletions
+3
View File
@@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml
+11
View File
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module external.system.id="pyproject.toml" type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/.venv" />
</content>
<orderEntry type="jdk" jdkName="~/Labs/oniric.ai/19.floop/floop/code/.venv" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
+13
View File
@@ -0,0 +1,13 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredPackages">
<list>
<option value="chainlit" />
<option value="dspy" />
</list>
</option>
</inspection_tool>
</profile>
</component>
+6
View File
@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/floop.iml" filepath="$PROJECT_DIR$/.idea/floop.iml" />
</modules>
</component>
</project>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>
+19 -13
View File
@@ -15,29 +15,33 @@ import dspy
from pydantic import BaseModel 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): class NamedEntity(BaseModel):
"""One named entity found in the question.""" """One named entity found in the question."""
name: str = dspy.OutputField( name: str = dspy.OutputField(
desc="the entity's exact surface text as it appears in the question, copied verbatim") desc="the entity's exact surface text as it appears in the question, copied verbatim")
kind: str = dspy.OutputField( 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): class NamedEntityRecognitionSignature(dspy.Signature):
"""You are the MASK step of a reasoning machine. Find the named entities """Find the named entities in the input text. Use only the kinds and
in the question — people, organizations, places, titles of works, events. definitions in the NamedEntity schema. Copy each entity's text exactly
Copy each one's text exactly as it appears; do not add entities that are as it appears; do not add entities that are not explicitly named."""
not explicitly named.""" text: str = dspy.InputField()
question: str = dspy.InputField()
entities: list[NamedEntity] = dspy.OutputField( entities: list[NamedEntity] = dspy.OutputField(
desc="the named entities found; empty when none") 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]: def apply_mask(question: str, entities: list[NamedEntity]) -> tuple[str, dict]:
"""Mask the question deterministically. Longer names first (so """Mask the question deterministically. Longer names first (so
'Pedro Sánchez Pérez-Castejón' is masked before its substrings). '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: if not name or name not in masked:
continue continue
kind = ent.kind.strip().upper() 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 counters[prefix] = counters.get(prefix, 0) + 1
ph = f"{prefix}_{counters[prefix]}" ph = f"{prefix}_{counters[prefix]}"
if ph in restore: # same surface text twice: keep one mask if ph in restore: # same surface text twice: keep one mask
+4 -4
View File
@@ -20,8 +20,8 @@ try:
except ImportError: # pragma: no cover — dspy <3.x except ImportError: # pragma: no cover — dspy <3.x
AdapterParseError = type("AdapterParseError", (Exception,), {"lm_response": ""}) AdapterParseError = type("AdapterParseError", (Exception,), {"lm_response": ""})
from .anonymize import (EntityMaskSignature, apply_mask, identity_answer, from .anonymize import (NamedEntityRecognitionSignature, apply_mask,
restore_mask) identity_answer, restore_mask)
class Subquestion(BaseModel): class Subquestion(BaseModel):
@@ -141,7 +141,7 @@ class FloopModules:
self.expert = predict(ExpertSignature) self.expert = predict(ExpertSignature)
self.missing = predict(MissingSignature) self.missing = predict(MissingSignature)
self.answer = predict(AnswerSignature) self.answer = predict(AnswerSignature)
self.mask = predict(EntityMaskSignature) self.mask = predict(NamedEntityRecognitionSignature)
def init_decompose(self, question: str) -> tuple[list[dict], str]: def init_decompose(self, question: str) -> tuple[list[dict], str]:
"""(parsed subquestions, raw model output). The machine decides what """(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 named entities to typed placeholders. No entity found (or the
mask call dies) -> the question passes unchanged, mask map empty.""" mask call dies) -> the question passes unchanged, mask map empty."""
try: try:
pred = self.mask(question=question) pred = self.mask(text=question)
entities = pred.entities or [] entities = pred.entities or []
except AdapterParseError: except AdapterParseError:
return question, {} return question, {}
+1 -1
View File
@@ -244,7 +244,7 @@ _STAGE_BY_MODULE = {
"Expert": "EXPERT", "Expert": "EXPERT",
"Missing": "MISSING", "Missing": "MISSING",
"Answer": "ANSWER", "Answer": "ANSWER",
"EntityMaskSignature": "MASK", "NamedEntityRecognitionSignature": "MASK",
"KnowledgeExpert": "knowledge", "KnowledgeExpert": "knowledge",
"InitSignature": "INIT", "InitSignature": "INIT",
"RouteSignature": "ROUTE", "RouteSignature": "ROUTE",
+2
View File
@@ -0,0 +1,2 @@
def main() -> None:
print("Hello from code!")
+25 -1
View File
@@ -26,7 +26,9 @@ from dspy._vendor.lm15 import Response, TextPart, Message, Usage
from dspy.utils.exceptions import AdapterParseError from dspy.utils.exceptions import AdapterParseError
from floop.dspy_modules import FloopModules 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: 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)") 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(): def test_init_decompose_masks_and_restores():
# script: first call = MASK, second = INIT # script: first call = MASK, second = INIT
_lm([_MASKED_ENTS, _TWO_SUBS]) _lm([_MASKED_ENTS, _TWO_SUBS])
@@ -147,6 +170,7 @@ def test_mask_death_passthrough():
if __name__ == "__main__": if __name__ == "__main__":
test_apply_restore_deterministic() test_apply_restore_deterministic()
test_entity_types_drive_schema_and_masks()
test_init_decompose_masks_and_restores() test_init_decompose_masks_and_restores()
test_no_entities_passthrough() test_no_entities_passthrough()
test_identity_subquestion_seeded() test_identity_subquestion_seeded()