Metadata-Version: 2.4
Name: nemoguardrails-redefiner
Version: 0.1.0
Summary: PII detection and masking rails for NVIDIA NeMo Guardrails, using ReDefiNER and a plain-English rulebook.
Author: Sethuraman T A, Jungroo AI Labs
Author-email: Cibe Hariharan K <cibe@jungroo.com>
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/Jungroo-AI/nemoguardrails-redefiner
Project-URL: Repository, https://github.com/Jungroo-AI/nemoguardrails-redefiner
Project-URL: Issues, https://github.com/Jungroo-AI/nemoguardrails-redefiner/issues
Project-URL: ReDefiNER, https://github.com/jungroo-ai/redefiner
Keywords: nemo-guardrails,nemoguardrails,guardrails,pii,redaction,pii-detection,named-entity-recognition,redefiner
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Security
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: nemoguardrails>=0.25
Requires-Dist: redefiner>=1.0.9
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pytest-asyncio; extra == "dev"
Requires-Dist: ruff; extra == "dev"
Dynamic: license-file

# nemoguardrails-redefiner

PII detection and masking rails for [NVIDIA NeMo Guardrails](https://github.com/NVIDIA-NeMo/Guardrails), using
[ReDefiNER](https://github.com/jungroo-ai/redefiner): an open model (0.8B parameters, Apache 2.0) that finds what a
rulebook written in plain English defines. The model runs inside your NeMo Guardrails process on CPU or GPU, so no text
leaves your machine and there is no server to run. English only.

- **`redefiner local mask pii on input|output|retrieval`**: replaces personal data with its type in brackets, e.g.
  `Hi, I am [PERSON]. Email me at [EMAIL].`
- **`redefiner local detect pii on input|output|retrieval`**: blocks the message instead.

By default the PII rulebook of [`jungroo-ai/redefiner-pii`](https://huggingface.co/jungroo-ai/redefiner-pii) is used,
with 20 types: `PERSON`, `TITLE`, `USERNAME`, `EMAIL`, `PHONE`, `ADDRESS`, `LOCATION`, `COORDINATE`, `ORGANIZATION`,
`OCCUPATION`, `DATE_TIME`, `AGE`, `GENDER`, `DEMOGRAPHIC`, `GOVERNMENT_ID`, `ID_NUMBER`, `IP_ADDRESS`, `URL`,
`FINANCIAL` and `SECRET`. Set your own rulebook to decide what counts as personal data for your application.

This package is maintained by Jungroo AI Labs. It is not part of NeMo Guardrails.

## Install

```bash
pip install nemoguardrails-redefiner
```

It needs `nemoguardrails` 0.25 or later and Python 3.11 or later. The first message downloads the model weights
(about 0.8 GB) from Hugging Face.

## Set up a config folder

Add the flows and actions to your NeMo Guardrails config folder:

```bash
python -m nemoguardrails_redefiner init config/
# wrote config/redefiner.co (Colang 1.0)
# wrote config/config.py
```

`redefiner.co` defines the six flows. `config.py` registers the two actions:

```python
from nemoguardrails_redefiner import register


def init(app):
    register(app)
```

If your folder already has a `config.py`, `init` leaves it alone and prints the two lines to add. It never overwrites a
file. For a Colang 2.x config, pass `--colang 2.x`.

Then turn the flows on in `config.yml`:

```yaml
rails:
  input:
    flows:
      - redefiner local mask pii on input
  output:
    flows:
      - redefiner local mask pii on output
```

```python
from nemoguardrails import Guardrails, RailsConfig
from nemoguardrails.rails.llm.options import RailType

rails = Guardrails(RailsConfig.from_path("config"))
result = rails.check(
    [{"role": "user", "content": "Hi, I am Maria Okafor. Email me at maria.okafor@acme.com or call +1 415 555 0134."}],
    rail_types=[RailType.INPUT],
)
print(result.content)
# Hi, I am [PERSON]. Email me at [EMAIL] or call [PHONE].
```

## Your own rulebook

Settings go under `custom_data.redefiner` in `config.yml`. A rulebook defines each type in plain English, and a
`[TYPE] NOT_AN_ENTITY` section says what must not be extracted:

```yaml
custom_data:
  redefiner:
    rulebook: |
      [RULES]
      G1 Extract every piece of personal data of the supplied types. Return exact spans from the text.

      [TYPE] PERSON
      [DESCRIPTION] A person's name, without titles such as "Dr." or "Ms".

      [TYPE] EMPLOYEE_ID
      [DESCRIPTION] An employee number, such as "E-48213".

      [TYPE] SALARY
      [DESCRIPTION] A person's pay: salary, bonus or hourly rate, with its currency.

      [TYPE] NOT_AN_ENTITY
      NE1 Names of teams, departments and products, and the company's own name.

rails:
  input:
    flows:
      - redefiner local mask pii on input
```

`Dr. Maria Okafor (E-40917) joins the Payments team at Acme on a salary of $96,500.` becomes
`Dr. [PERSON] ([EMPLOYEE_ID]) joins the Payments team at Acme on a salary of [SALARY].` The rulebook can also be a path
to a file, relative to the config folder (`rulebook: rules/pii.txt`). For how to write rules, see the
[ReDefiNER rulebook guide](https://github.com/jungroo-ai/redefiner/blob/main/docs/writing-rules.md).

## Settings

All settings are optional.

| Setting | Default | Meaning |
|---|---|---|
| `model` | `jungroo-ai/redefiner-pii` | A Hugging Face repo or local folder |
| `rulebook` | the model's default | Rulebook text, or a path to a rulebook file |
| `input.entities`, `output.entities`, `retrieval.entities` | all types | Only these rulebook types block or are masked on that source, e.g. `[PERSON, EMAIL]`. With your own rulebook, a type it does not define is an error. |
| `min_confidence` | `0.0` | Ignore spans below this confidence |
| `threshold`, `none_bias`, `max_span_tokens` | model defaults | ReDefiNER settings; see its README |
| `device` | GPU if available | `cpu`, `cuda` or `cuda:N` |
| `revision` | latest | A Hugging Face revision of the model |
| `preload` | `false` | Load the model when the config loads, not on the first message |

```yaml
custom_data:
  redefiner:
    preload: true
    output:
      entities: [PERSON, PHONE, EMAIL]
```

## How it behaves

- **Fails closed.** If the model can't load or raises, the action raises too, and NeMo Guardrails answers with its
  internal-error message (`blocked` from `check`) instead of passing the text on unchecked. A misconfigured
  `custom_data.redefiner` raises the same way, with the setting's name in the error.
- **Speed.** The first message loads the model and reads the rulebook: about 20 seconds on a laptop CPU in our test.
  Later messages took about 0.6 seconds each for a sentence. Set `preload: true` to load the model at start-up.
- **One model per process.** Every config that uses the same model, device and settings shares one loaded copy, and
  calls to it run one at a time.
- **What is logged.** The actions log nothing. Their outcome metadata holds the types found and the span count, never
  the text.
- **Colang.** Both Colang 1.0 and 2.x configs work, through the `LLMRails` engine. Colang 2.x is deprecated as of
  NeMo Guardrails 0.25. With Colang 2.x, a failure ends the turn without a reply.

## Limitations

- English only.
- The model can miss personal data, and accuracy depends on the rulebook. Check it on your own conversations, and don't
  rely on it alone.
- Overlapping spans are merged into one placeholder that uses the first span's type.

## License

Apache 2.0. ReDefiNER's weights are Apache 2.0 too.
