# Guardrails

Put rules and a budget on a set of keys.

1. [Write the rules](#1-write-the-rules).
2. [Create the guardrail](#2-create-the-guardrail).
3. [Assign it to your keys](#3-assign-it-to-your-keys).
4. [Read what it stopped](#4-read-what-it-stopped).

## 1. Write the rules

A guardrail is a set of rules you put on your keys. It binds only the keys it is assigned to: your other keys run as before. Each rule below is optional; a guardrail holds any mix of them.

| Rule | Does | You send |
|---|---|---|
| budget | a cap in DA, reset daily, weekly or monthly | `limit`, `reset_interval` |
| models | only these models run | `allowed_models` |
| providers | only these providers serve | `allowed_providers` |
| zero data retention | only endpoints that keep nothing, per lab | `enforce_zdr_anthropic`, `enforce_zdr_openai`, `enforce_zdr_google`, `enforce_zdr_xai`, `enforce_zdr_other`: `true` |
| prompt injection | blocks known injection patterns | `content_filter_builtins`: an entry with `slug` `regex-prompt-injection` and `action` `block` |
| sensitive information | redacts or blocks personal data | `content_filter_builtins`: one entry per kind, its `slug` and an `action`, `redact` or `block` |
| custom filters | your own patterns, redacted or blocked | `content_filters`: one entry per pattern, its `pattern` and an `action`, `redact` or `block` |

Every guardrail also takes a `name`, which it needs, and a `description`. Every field: [Guardrail rules](/docs/reference/guardrails).

The kinds of personal data a guardrail knows, each named by its `slug`:

| `slug` | Finds |
|---|---|
| `email` | an email address |
| `phone` | a phone number |
| `credit-card` | a card number |
| `ip-address` | an IP address |
| `address` | a street address |
| `ssn` | a US social security number |
| `secrets` | an API key or token pasted into a prompt |

`redact` replaces what it finds with a label, such as `[PHONE]`, before the model reads the prompt. `block` refuses the request.

## 2. Create the guardrail

Souk Bot runs on its own key, named *Souk Bot*. Yacine wants it held to 2 000 DA a month, an illustrative budget, on one model, with phone numbers redacted before any model reads them.

<div class="watch-out">
<p>The guardrail routes take a management key, never an API key. Set <code>OPENDUNES_MANAGEMENT_KEY</code> to your management key in the terminal that runs this sample. An API key gets a 401. See <a href="/docs/api-keys">API keys</a>.</p>
</div>

The sample creates the guardrail, finds the key named *Souk Bot* and assigns the guardrail to it.

```python
import json
import os
import urllib.request

MANAGEMENT_KEY = os.environ["OPENDUNES_MANAGEMENT_KEY"]
base_url = "https://opendunes.com/v1"
model = "anthropic/claude-sonnet-4.5"
key_name = "Souk Bot"


def call(method, path, body=None):
    data = json.dumps(body).encode() if body is not None else None
    request = urllib.request.Request(
        base_url + path,
        method=method,
        data=data,
        headers={
            "Authorization": "Bearer " + MANAGEMENT_KEY,
            "Content-Type": "application/json",
        },
    )
    with urllib.request.urlopen(request) as response:
        return json.load(response)


guardrail = call("POST", "/guardrails", {
    "name": "Souk Bot, monthly",
    "limit": 2000,
    "reset_interval": "monthly",
    "allowed_models": [model],
    "content_filter_builtins": [{"slug": "phone", "action": "redact"}],
})["data"]
print("guardrail", guardrail["id"])

keys = call("GET", "/keys")["data"]
hashes = [k["hash"] for k in keys if k["name"] == key_name]
if not hashes:
    raise SystemExit("No key is named " + key_name + ".")

path = "/guardrails/" + guardrail["id"] + "/assignments/keys"
assigned = call("POST", path, {"key_hashes": hashes})
print("assigned", assigned["assigned_count"])
```

```javascript
const MANAGEMENT_KEY = process.env.OPENDUNES_MANAGEMENT_KEY;
const baseURL = "https://opendunes.com/v1";
const model = "anthropic/claude-sonnet-4.5";
const keyName = "Souk Bot";

async function call(method, path, body) {
  const response = await fetch(baseURL + path, {
    method,
    headers: {
      Authorization: `Bearer ${MANAGEMENT_KEY}`,
      "Content-Type": "application/json",
    },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  if (!response.ok) {
    throw new Error(`${response.status} ${await response.text()}`);
  }
  return response.json();
}

const { data: guardrail } = await call("POST", "/guardrails", {
  name: "Souk Bot, monthly",
  limit: 2000,
  reset_interval: "monthly",
  allowed_models: [model],
  content_filter_builtins: [{ slug: "phone", action: "redact" }],
});
console.log("guardrail", guardrail.id);

const { data: keys } = await call("GET", "/keys");
const hashes = keys.filter((k) => k.name === keyName).map((k) => k.hash);
if (hashes.length === 0) throw new Error(`No key is named ${keyName}.`);

const path = `/guardrails/${guardrail.id}/assignments/keys`;
const assigned = await call("POST", path, { key_hashes: hashes });
console.log("assigned", assigned.assigned_count);
```

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

var managementKey = os.Getenv("OPENDUNES_MANAGEMENT_KEY")

const (
	baseURL = "https://opendunes.com/v1"
	model   = "anthropic/claude-sonnet-4.5"
	keyName = "Souk Bot"
)

func call(method, path string, body any, out any) {
	var reader io.Reader
	if body != nil {
		encoded, err := json.Marshal(body)
		if err != nil {
			panic(err)
		}
		reader = bytes.NewReader(encoded)
	}

	req, err := http.NewRequest(method, baseURL+path, reader)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+managementKey)
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()
	if res.StatusCode >= 300 {
		text, _ := io.ReadAll(res.Body)
		panic(fmt.Sprintf("%d %s", res.StatusCode, text))
	}
	if err := json.NewDecoder(res.Body).Decode(out); err != nil {
		panic(err)
	}
}

func main() {
	var created struct {
		Data struct {
			ID string `json:"id"`
		} `json:"data"`
	}
	phone := map[string]string{"slug": "phone", "action": "redact"}
	call("POST", "/guardrails", map[string]any{
		"name":                    "Souk Bot, monthly",
		"limit":                   2000,
		"reset_interval":          "monthly",
		"allowed_models":          []string{model},
		"content_filter_builtins": []map[string]string{phone},
	}, &created)
	fmt.Println("guardrail", created.Data.ID)

	var keys struct {
		Data []struct {
			Hash string `json:"hash"`
			Name string `json:"name"`
		} `json:"data"`
	}
	call("GET", "/keys", nil, &keys)
	hashes := []string{}
	for _, k := range keys.Data {
		if k.Name == keyName {
			hashes = append(hashes, k.Hash)
		}
	}
	if len(hashes) == 0 {
		panic("No key is named " + keyName + ".")
	}

	var assigned struct {
		AssignedCount int `json:"assigned_count"`
	}
	path := "/guardrails/" + created.Data.ID + "/assignments/keys"
	call("POST", path, map[string]any{"key_hashes": hashes}, &assigned)
	fmt.Println("assigned", assigned.AssignedCount)
}
```

```bash cURL
BASE_URL="https://opendunes.com/v1"
MODEL="anthropic/claude-sonnet-4.5"
KEY_NAME="Souk Bot"

rules='{
  "name": "Souk Bot, monthly",
  "limit": 2000,
  "reset_interval": "monthly",
  "allowed_models": ["'"$MODEL"'"],
  "content_filter_builtins": [
    {
      "slug": "phone",
      "action": "redact"
    }
  ]
}'

created=$(curl -s "$BASE_URL/guardrails" \
  -H "Authorization: Bearer $OPENDUNES_MANAGEMENT_KEY" \
  -H "Content-Type: application/json" \
  -d "$rules")
guardrail=$(echo "$created" | grep -o '"id": *"[^"]*"' | head -1 |
  cut -d '"' -f 4)

keys=$(curl -s "$BASE_URL/keys" \
  -H "Authorization: Bearer $OPENDUNES_MANAGEMENT_KEY")
key_hash=$(echo "$keys" |
  grep -o '{[^{}]*"name": *"'"$KEY_NAME"'"[^{}]*}' |
  grep -o '"hash": *"[^"]*"' | cut -d '"' -f 4)

curl -s "$BASE_URL/guardrails/$guardrail/assignments/keys" \
  -H "Authorization: Bearer $OPENDUNES_MANAGEMENT_KEY" \
  -H "Content-Type: application/json" \
  -d '{"key_hashes": ["'"$key_hash"'"]}'
```

`201`, with the guardrail under `data`: its `id` and every rule as you set it. `limit` comes back in DA.

A day, a week and a month are UTC. The week starts on Monday.

## 3. Assign it to your keys

A guardrail binds nothing until a key is assigned to it. A key is named by its hash, which the list of your keys gives: `GET /v1/keys`, under a management key.

| Route | Does |
|---|---|
| `POST /v1/guardrails/{id}/assignments/keys` | assigns the keys in `key_hashes` |
| `POST /v1/guardrails/{id}/assignments/keys/remove` | unassigns the keys in `key_hashes` |
| `GET /v1/guardrails/{id}/assignments/keys` | this guardrail's keys |
| `GET /v1/guardrails/assignments/keys` | every assignment on your account |

To change a rule, send only that rule to `PATCH /v1/guardrails/{id}`. `DELETE /v1/guardrails/{id}` removes the guardrail, and its keys run free of it. Every guardrail route is free.

A key can sit under several guardrails. Each rule then combines its own way.

| Rule | Under several guardrails |
|---|---|
| models, providers | the lists intersect: only what every guardrail allows |
| filters | they add up: every guardrail's filters run |
| budget | each counts on its own; the first spent stops the key |

<div class="good-to-know">
<p>A key's own cap still holds under a guardrail. A request stops at whichever limit is spent first. See <a href="/docs/limits">Limits</a>.</p>
</div>

## 4. Read what it stopped

| Status | When | The body |
|---|---|---|
| 403 | the guardrail's budget is spent | `metadata.limit_source` reads `guardrail` |
| 403 | a rule blocked the request: a model or provider not allowed, a filter set to `block`, a prompt injection | the message says which rule |

A spent budget stops every key the guardrail is assigned to, until it resets or you raise `limit`.

```json
{
  "error": {
    "code": 403,
    "message": "This guardrail has spent its budget.",
    "metadata": {
      "limit_source": "guardrail"
    }
  }
}
```

The message above is illustrative.

<div class="dont">
<p>Don't retry a 403 as it stands: the same request meets the same rule.</p>
</div>

<div class="do">
<p>Do read the message, which names the rule. Then change the request, or change the guardrail with <code>PATCH /v1/guardrails/{id}</code>.</p>
</div>

## Errors

The guardrail routes answer these. The body says why.

| Status | When |
|---|---|
| 400 | the body is malformed: no `name`, a `slug` or an `action` it does not know, or a pattern that does not compile |
| 401 | the key is missing, wrong, disabled or expired, or it is an API key |
| 404 | no guardrail of yours has this `id` |

What to do on each: [Errors and retries](/docs/errors-and-retries).
