> ## Documentation Index
> Fetch the complete documentation index at: https://docs.openlayer.com/llms.txt
> Use this file to discover all available pages before exploring further.

# .NET guardrails

> Use Openlayer guardrails in C# / .NET apps to block, redact or pseudonymize PII and to screen for toxicity and prompt injection

The `Openlayer.Guardrails` packages bring the [Python guardrails library](https://docs.openlayer.com/guardrails/overview.md#guardrails-library)
to C# / .NET. The PII detection is a port of the Python library and gives the same results: a test
suite runs the Python library as the reference.

| Package | Guardrails | Native dependencies |
| - | - | - |
| `Openlayer.Guardrails` | `PiiGuardrail`, `CpniGuardrail` | None |
| `Openlayer.Guardrails.Onnx` | `ToxicityEnGuardrail`, `ToxicityPtGuardrail`, `PromptInjectionGuardrail`, `BertNerModel` | ONNX Runtime |

Both packages support .NET 8+ and any `netstandard2.0` runtime.

## Install

```bash theme={null}
dotnet add package Openlayer.Guardrails
dotnet add package Openlayer.Guardrails.Onnx   # only for the model-based guardrails
```

## PII

`CheckInput` takes a function's arguments as a dictionary, and `CheckOutput(output, inputs)` takes
its return value. Both walk nested dictionaries and lists. A `Modify` result rebuilds the same
structure with the strings redacted.

```csharp theme={null}
using Openlayer.Guardrails;
using Openlayer.Guardrails.Pii;

var guard = new PiiGuardrail(new PresidioGuardrailOptions
{
    BlockEntities = new HashSet<string> { "CREDIT_CARD", "US_SSN" },
    RedactEntities = new HashSet<string> { "EMAIL_ADDRESS", "PHONE_NUMBER" },
});

var result = guard.CheckInput(new Dictionary<string, object?>
{
    ["message"] = "My email is john@example.com",
});

switch (result.Action)
{
    case GuardrailAction.Block:
        Console.WriteLine($"Blocked: {result.Reason}");
        break;
    case GuardrailAction.Modify:
        var redacted = (IDictionary<object, object?>)result.ModifiedData!;
        Console.WriteLine(redacted["message"]); // My email is [EMAIL-REDACTED]
        break;
}
```

The default entities, the confidence threshold (`0.7`) and the keys in `result.Metadata`
(`detected_entities`, `blocked_entities`, `redacted_entities`, ...) are the same as in the Python
`PIIGuardrail`. A guardrail instance is thread-safe, so you can share one instance in your app.

### CPNI

`CpniGuardrail` detects telecom customer proprietary network information (47 U.S.C. 222). It does
not block by default. When you give it a key, it replaces each identifier with a keyed pseudonym, so
you can still join records for the same subscriber. The pseudonyms are the same as the Python
library's for the same key.

```csharp theme={null}
var cpni = new CpniGuardrail(new PresidioGuardrailOptions
{
    PseudonymKey = Environment.GetEnvironmentVariable("CPNI_PSEUDONYM_KEY"),
});

var result = cpni.CheckInput(new Dictionary<string, object?> { ["msg"] = "handset IMEI 352099001761481 blocked" });
// ModifiedData["msg"]         == "handset IMEI <IMEI:...> blocked"
// Metadata["cpni_categories"] == ["technical_configuration"]
```

## Toxicity and prompt injection

The model-based guardrails run on [ONNX Runtime](https://onnxruntime.ai/). They do not download
models: you export each model to ONNX once, and give the guardrail the folder.

```csharp theme={null}
using Openlayer.Guardrails.Onnx;

var toxicity = new ToxicityEnGuardrail(new ToxicityEnGuardrailOptions { ModelDirectory = "models/toxic-bert" });
var result = toxicity.CheckInput(new Dictionary<string, object?> { ["message"] = "You are terrible" });
// result.Metadata["label_scores"], result.Metadata["triggered_categories"], ...
```

The thresholds, categories and metadata keys are the same as in the Python guardrails.

| Guardrail | Model | Folder name |
| - | - | - |
| `ToxicityEnGuardrail` | `unitary/toxic-bert` | `toxic-bert` |
| `ToxicityPtGuardrail` | `nicholasKluge/ToxiGuardrailPT` | `toxiguardrail-pt` |
| `PromptInjectionGuardrail` | `meta-llama/Llama-Prompt-Guard-2-86M` | `prompt-guard` |
| `BertNerModel` | `dslim/bert-base-NER` | `bert-base-ner` |

Instead of `ModelDirectory`, you can set the `OPENLAYER_GUARDRAILS_MODELS_DIR` environment variable
to a folder that contains the folders above.

### Export the models

Export the models with [Optimum](https://huggingface.co/docs/optimum-onnx/onnx/usage_guides/export_a_model)
on a machine with Python. Each output folder holds `model.onnx` and the tokenizer files.

```bash theme={null}
pip install "optimum[onnxruntime]"
hf download unitary/toxic-bert --local-dir src/toxic-bert
optimum-cli export onnx --model src/toxic-bert --task text-classification --opset 17 models/toxic-bert
```

Use `--task token-classification` for `dslim/bert-base-NER`. `meta-llama/Llama-Prompt-Guard-2-86M`
is a gated model: accept its license on Hugging Face, and set `HF_TOKEN` before you download it.

To pin the model version, add `--revision <commit-sha>` to `hf download`. If the Hugging Face Hub is
not reachable, set `HF_ENDPOINT` (and `HF_TOKEN`) to use a mirror, for example a Hugging Face remote
repository in Artifactory or Nexus. For air-gapped deployments, export the models on a machine with
access, then copy the `models` folder to the target.

## Names, places and organizations

The Python `PIIGuardrail` finds `PERSON`, `LOCATION` and `ORGANIZATION` with a spaCy model, which
does not run on .NET. To detect these entities in .NET, give the NLP engine a named-entity model.
`BertNerModel` runs `dslim/bert-base-NER`:

```csharp theme={null}
using Openlayer.Guardrails.Nlp;
using Openlayer.Guardrails.Onnx;

var nlp = new NlpEngine(new NlpEngineOptions
{
    NerModel = new BertNerModel(new BertNerModelOptions { ModelDirectory = "models/bert-base-ner" }),
});
var guard = new PiiGuardrail(new PresidioGuardrailOptions
{
    NlpEngine = nlp,
    RedactEntities = new HashSet<string> { "PERSON", "LOCATION", "EMAIL_ADDRESS" },
});
```

> [!NOTE]
>
> The named-entity model is different from spaCy, so the detected `PERSON`,
> `LOCATION`, `ORGANIZATION` and `DATE_TIME` spans can be different from the
> Python library's. All other entities are the same.

## Tracing

The Python guardrails plug into the `@trace` decorator. The [C# / .NET SDK](https://docs.openlayer.com/api-reference/sdk/libraries/csharp.md)
does not have tracing, so call `CheckInput` before and `CheckOutput` after your LLM call, and act on
`result.Action`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.