# Guardrails

> Check each message against a policy such as toxicity with one yes-or-no question, block or allow what decisio can stand behind, and send the rest to a moderator.

Source: https://opendecisio.com/docs/use-cases/guardrails/

The script asks one yes-or-no [question](https://opendecisio.com/docs/glossary/#question) and blocks or allows only on a [certified answer](https://opendecisio.com/docs/glossary/#certified-answer):

 

[Figure: The model judges the input; your code chooses the action. Input: A message to screen. Question: Is this message toxic: insulting, hateful, threatening or sexually explicit?. Typed answer: The probability of yes. Your code: Apply your allow/block policy to certified answers; review the rest..]

 

## TL;DR

 

Save the [complete caller](https://opendecisio.com/examples/recipes/guardrails.py) as `guardrails.py` and run it with Python 3.12 or later. Set `DECISIO_BASE_URL` to your server, or leave the local default. Until you register and certify this question, the caller sends answers to review.

 python

```
import json
import os
import urllib.error
import urllib.request

QUESTION = {
    "type": "noul",
    "instructions": "Is this message toxic: insulting, hateful, threatening or sexually explicit?"
}
BASE_URL = os.environ.get("DECISIO_BASE_URL", "http://127.0.0.1:8000").rstrip("/")
TIMEOUT = 15
REVIEW = "to a moderator"

def route(text):
    request = urllib.request.Request(
        BASE_URL + "/v1/systemone",
        data=json.dumps({"state": text, "questions": {"toxic": QUESTION}}).encode(),
        headers={"Content-Type": "application/json"},
    )
    try:
        with urllib.request.urlopen(request, timeout=TIMEOUT) as response:
            answer = json.load(response)["answers"]["toxic"]
        if not isinstance(answer, dict) or answer.get("type") != QUESTION["type"]:
            return REVIEW
        if not (type(answer.get("noul")) in (int, float) and 0 &#x3C;= answer["noul"] &#x3C;= 1):
            return REVIEW
        # A gold certificate is about correctness; agreement alone is insufficient.
        if (answer.get("certified") is True
                and answer.get("certificate_kind") == "gold"
                and isinstance(answer.get("certificate"), str)
                and answer["certificate"]):
            return "block" if answer["noul"] >= 0.5 else "allow"
        return "to a moderator"
    except (urllib.error.URLError, TimeoutError, OSError, ValueError, KeyError, TypeError):
        return REVIEW

if __name__ == "__main__":
    print(route("Thanks, that fixed it!"))
```

 Output

```
to a moderator
```

 

## Is it a good fit?

 

Good fit

- A policy you can state as a yes-or-no question: is it toxic, is it off-topic, does it ask for a refund.
- Labelled messages, to certify from.

Not a good fit

- A policy that needs the whole conversation when you send one message.
- A single gate in front of something dangerous: keep a person or a second check on what is not certified.

 

## 1 Write the question

 

One `noul` question, which answers with the [probability](https://opendecisio.com/docs/glossary/#probability) of yes. Several policies are several questions in the same request, read once.

 

## 2 Teach it and certify it

 

A clear yes-or-no question the model already answers well often needs no teaching: the server declines a correction that does not help, and says so. Certify it anyway, so each answer says whether it can act on its own.

 

Send at least 118 labelled messages. The server holds back half to certify, and a 5% certificate needs 59 of those. More examples certify a larger share.

 

Prepare `guardrails-labels.jsonl` with one JSON object per line, containing `state` and `answer`. Use real inputs and labels chosen by a person; each answer is a JSON boolean, `true` or `false`. The code below builds complete requests using the same question as the caller.

 python

```
import json
import os
import urllib.request

QUESTION = {
    "type": "noul",
    "instructions": "Is this message toxic: insulting, hateful, threatening or sexually explicit?"
}
# One JSON object per line: state and the answer chosen by a person.
with open("guardrails-labels.jsonl", encoding="utf-8") as source:
    rows = [json.loads(line) for line in source if line.strip()]
examples = [
    {"request": {"state": row["state"], "questions": {"toxic": QUESTION}},
     "answer": row["answer"]}
    for row in rows
]
body = {"id": "guardrails", "examples": examples, "certify": {"alpha": 0.05}}
base_url = os.environ.get("DECISIO_BASE_URL", "http://127.0.0.1:8000").rstrip("/")
request = urllib.request.Request(
    base_url + "/v1/tasks", data=json.dumps(body).encode(),
    headers={"Content-Type": "application/json"},
)
# Registration reads all your examples; allow more time than an ordinary decision.
with urllib.request.urlopen(request, timeout=300) as response:
    record = json.load(response)
print(json.dumps(record.get("certificate"), indent=2))
```

 

Needs the reader’s own human-labelled JSONL file.

 

Save the [registration script](https://opendecisio.com/examples/recipes/guardrails-register.py) beside the labels file and run it with Python. Registration replaces a [task](https://opendecisio.com/docs/glossary/#task) of the same id. Check the returned certificate: a `null` [threshold](https://opendecisio.com/docs/glossary/#threshold) means no answer can be certified.

 

[Certify answers](https://opendecisio.com/docs/tasks/certify/#2-teach-the-task-with-a-certificate) runs this call on a server, with its answer.

 

## 3 Route on the certificate

 

The caller acts only when `certified` is `true` and `certificate_kind` is `gold`, with a certificate id. A learned table’s `agreement` certificate measures agreement with the model, so it goes to review in this recipe.

 

- A certified yes blocks; a certified no allows.
- Everything else goes to a moderator.
- When the messages change, a new kind of abuse, a new language, certification is suspended until you certify again ([Watch for drift](https://opendecisio.com/docs/tasks/drift/)).

 

## What it did

 

- **97.3%** right on ToxicChat's toxicity question, with a calibration error of 0.036, on Gemma 4 31B, untaught, in decisio's 1,400-item suite: one RTX PRO 6000, vLLM 0.30.0, 2026-10-04 (its evaluation card, section 7.2). The model's default settings were tuned on that same suite, so that calibration error is its best case.
- Other guardrails, such as off-topic or prompt-injection checks, follow the same recipe; no run of them is published.

 

 

## Limits

 

- An HTTP error, timeout or invalid response goes to the review path, like an uncertified answer ([Handle review and service failures](https://opendecisio.com/docs/use-cases/#handle-review-and-service-failures)).
- Keep the question and [options](https://opendecisio.com/docs/glossary/#option) stable after registration, and certify again after changing the task or [serving setup](https://opendecisio.com/docs/glossary/#serving-setup) ([Keep a certificate valid](https://opendecisio.com/docs/production/#keep-a-certificate-valid)).

 

## What next

 

- [Certify answers](https://opendecisio.com/docs/tasks/certify/): the promise, and how to choose the [error target](https://opendecisio.com/docs/glossary/#error-target).
- [Scale](https://opendecisio.com/docs/scale/): many policy questions about one message, for the price of one read.
- [Use cases](https://opendecisio.com/docs/use-cases/): the other recipes.
