Guardrails
Guardrails are project-scoped policies that sit between your application and the upstream LLM provider. They evaluate every request (input) and/or every response (output) and can block, redact, or silently log content that matches your rules — without any changes to your API calls.
Your App → [input rules] → LLM Provider → [output rules] → Your App
Where Guardrails Run
| Endpoint |
Direction |
route_scope values |
POST /v1/chat/completions |
input, output |
chat_completion, chat_completion_stream |
POST /v1/messages (Anthropic) |
input, output |
messages, messages_stream |
POST /v1/responses |
input, output |
responses, responses_stream |
POST /v1/embeddings |
input |
embeddings |
A rule with an empty route_scope runs on every endpoint in the table where its direction and mode apply, streamed or not, so Claude Code and the Anthropic SDK get the same rules as OpenAI-compatible clients.
Other endpoints do not evaluate rules: batches (/v1/batches), images, audio, video, OCR, and decisions reach the provider unscanned. The native Gemini endpoints refuse a generation request with 400 when the project has an enabled input or output rule whose route_scope covers the matching chat scope: chat_completion for generateContent, chat_completion_stream for streamGenerateContent. A rule with an empty scope covers both.
On /v1/messages, the gateway extracts the system prompt, text blocks, tool results, documents (the title, the context, and a plain-text or content source), search results, web-fetch results, and MCP tool results. Images, the body of a PDF, URL, or file-ID document, tool-call inputs, thinking blocks, and web-search results are not extracted. Every input rule reads the extracted text except prompt_injection, which reads only the newest turn (see prompt_injection below). Output rules read the text blocks of the response, not tool-call inputs.
On /v1/embeddings, only string and string-array inputs are scanned; token-ID arrays and other input shapes pass unscanned. llm_evaluation rules do not run there, even when their route_scope lists embeddings.
Why Guardrails?
- Compliance — prevent sensitive data (PII, card numbers, secrets) from leaving your system.
- Content moderation — reject harmful or off-topic prompts before they cost you tokens.
- Output enforcement — ensure model responses match a required JSON schema.
- Observability — record every rule hit for auditing and debugging without blocking traffic.
Creating a Rule
Rules are created in the Guardrails section of your project dashboard or via the management API. Each rule requires:
| Field |
Description |
title |
Human-readable label |
direction |
input (check the request) or output (check the response) |
mode |
Matching strategy — see Matching Modes |
action |
What to do on a match — see Actions |
config |
Mode-specific configuration object |
INFO
Rules are cached and applied in under 1 ms on the hot path. When a project has no enabled rules
the evaluator is skipped entirely.
Matching Modes
regexp — Regular Expression
Matches when the payload contains a substring matching a RE2 regular expression.
{
"mode": "regexp",
"config": {
"pattern": "\\b\\d{4}[\\s-]?\\d{4}[\\s-]?\\d{4}[\\s-]?\\d{4}\\b"
}
}
The pattern is validated at rule-creation time — an invalid regex returns 400 GUARDRAIL_RULE_INVALID.
string_presence — Keyword List
Matches when the payload contains any of the listed literal terms (case-sensitive).
{
"mode": "string_presence",
"config": {
"terms": ["confidential", "internal only", "do not share"]
}
}
json_validator — JSON Schema
Fires when the model's response is valid JSON but does not conform to the provided JSON Schema. Use this on direction: output to enforce structured-output shapes.
{
"mode": "json_validator",
"direction": "output",
"config": {
"schema": {
"type": "object",
"required": ["customer_id", "status"],
"properties": {
"customer_id": { "type": "string" },
"status": { "type": "string", "enum": ["active", "inactive"] }
}
}
}
}
WARNING
json_validator is silently skipped on streaming endpoints. Use it only with non-streaming
requests.
llm_evaluation — AI Judge
Sends the payload to a configured judge model. The judge's response is checked for a denial keyword to determine pass/fail.
{
"mode": "llm_evaluation",
"config": {
"judge_model": "gpt-4o-mini",
"prompt": "Does the following message discuss competitor pricing? Answer YES or NO only.",
"deny_response_substring": "YES"
}
}
INFO
Judge requests carry an internal bypass marker so they are never themselves evaluated by
guardrails, preventing infinite recursion.
WARNING
llm_evaluation is silently skipped on streaming endpoints and on /v1/embeddings.
prompt_injection — Built-in Detector
Checks request input against built-in prompt-injection signatures derived from the OWASP LLM Prompt Injection Prevention Cheat Sheet. It runs inside the gateway with no model call, so it adds no cost and well under a millisecond for typical prompts.
The signatures cover instruction overrides ("ignore all previous instructions"), developer or admin mode activation, prompt extraction ("reveal your system prompt"), role manipulation, DAN-style jailbreaks, safety bypass requests, fake <system> tags and [System] labels, and model control tokens such as <|im_start|>. The detector also undoes common evasions before matching:
- Spaced-out letters —
i g n o r e p r e v i o u s
- Scrambled keywords —
ignroe all pveriuos instructions
- Base64 and hex — encoded text is decoded and checked against the same signatures
{
"mode": "prompt_injection",
"direction": "input",
"action": "log_only",
"config": {
"allowlist": ["ignore previous instructions"]
}
}
allowlist is optional: up to 200 case-insensitive phrases (1,000 bytes each) that never trigger the detector, for text your application sends on purpose. Events and test results name the signatures that matched, for example ignore_previous_instructions or base64:reveal_prompt.
INFO
On chat completions, /v1/messages, and /v1/responses the detector scans only the newest turn
(new user text and tool results), not the system prompt or earlier turns, which clients resend
with every request. On /v1/embeddings it scans every input. Start in log_only, review the
events, and allowlist phrases your own prompts use before switching to reject or mask. Pair it
with an llm_evaluation rule (the Prompt injection classifier template) to catch paraphrased
attacks that no fixed signature covers.
pii — Built-in Personal Data Detector
PII detection has two layers:
- Built-in entities (free). Deterministic pattern matching with checksum validation, run inside the LLM API gateway. Your text is not sent to any third party for this step.
- Contextual entities (paid, opt-in). Names, addresses, and other identifiers that only context reveals are detected by Amazon Bedrock Guardrails (sensitive-information filter). Bedrock processes the text to return the entity types and positions; it does not store it or use it for model training. LLM API caches only those types and positions, keyed by a hash of the text, never the personal data itself.
When a rule matches, the gateway blocks, masks, or logs the request before it reaches the model, as set by the rule's action.
Finds personal data with built-in patterns, validated the way data-loss-prevention tools do: payment card numbers must pass the Luhn check, IBANs must match their country's length and mod-97 check digits, US Social Security numbers must have a valid area, group, and serial, and IP addresses must parse. Bare digit runs (a phone number without separators, an unformatted SSN) only count when a context word such as "phone", "mobile", or "SSN" appears nearby. It runs inside the gateway with no model call, on input and output.
| Entity |
Detects |
email |
Email addresses |
phone |
International (+44 20 7946 0958), parenthesised, and separated numbers; bare digits need context |
credit_card |
13–19 digit card numbers that pass Luhn |
iban |
IBANs with valid length and check digits, with or without spaces |
us_ssn |
NNN-NN-NNNN with valid ranges; bare nine digits need context |
ip_address |
IPv4 and IPv6 addresses |
{
"mode": "pii",
"direction": "input",
"action": "mask",
"mask_template": "[{entity}]",
"config": {
"entities": ["email", "phone", "credit_card"],
"allowlist": ["support@example.com"]
}
}
entities is optional and selects a subset; omit it to detect everything. allowlist holds up to 200 case-insensitive values (1,000 bytes each) that never count, such as your own support address. In mask_template, {entity} expands to the matched entity, so [{entity}] rewrites an address as [EMAIL] and a card as [CREDIT_CARD]. Events and test results name the entities that matched.
Contextual entities (paid)
Names, postal addresses, and other identifiers that only context reveals are found by a language model. Select them with contextual_entities; they are opt-in because every scan is billed.
{
"mode": "pii",
"config": {
"contextual_entities": ["name", "address"]
}
}
| Entity |
Detects |
name |
People's names |
address |
Postal addresses |
age, username, password, pin |
Ages, account names, passwords, PINs |
driver_id, license_plate, vehicle_id |
Driver's licenses, plates, VINs |
card_cvv, card_expiry, swift_code |
Card security codes and expiry dates, SWIFT/BIC |
url, mac_address, aws_access_key, aws_secret_key |
URLs, MAC addresses, AWS credentials |
us_passport_number, us_bank_account_number, us_bank_routing_number, us_itin |
US identifiers |
uk_national_insurance_number, uk_nhs_number, uk_taxpayer_reference |
UK identifiers |
ca_social_insurance_number, ca_health_number |
Canadian identifiers |
email, phone, credit_card, iban, us_ssn, ip_address |
Model-based twins of the free built-in entities; they also catch a bare phone number with no context word or a card given by its last four digits |
- Billing. Each request is charged by the characters of text scanned (billed in blocks of 1,000), shown in the dashboard and as
guardrailCost on the request log. Text already scanned in an earlier turn of the same project is not scanned or billed again while it stays in the scan cache — 24 hours by default, set by the deployment — so an active conversation pays only for its new messages. A conversation resumed after the entry expires pays for its history once more. The fee applies to requests on your own provider keys too, and to a request that the scan's rule rejects or that fails after the scan: the scan ran, so it is charged. A request refused earlier by a rate limit, a credit check, or model access is never scanned.
- Size limit. One request scans at most 100,000 new characters (set by the deployment). Above that nothing is sent, and the rule's
on_failure applies: reject blocks the request with 413 GUARDRAIL_PAYLOAD_TOO_LARGE, allow keeps only the built-in matches.
- Credit balance. Saving or enabling a rule with contextual entities, and every scan, needs a credit balance. Without one the scan fails and the rule's
on_failure applies: reject blocks the request with 402 GUARDRAIL_CREDIT_REQUIRED, allow keeps only the built-in matches.
- Languages. English, German, French, Spanish, Italian, Portuguese, Dutch, Polish, Swedish, Norwegian, Finnish, Arabic, Chinese, Japanese, Korean, Hindi, and Vietnamese. Text in any other language, including every Cyrillic-script language such as Ukrainian or Russian, is still scanned and billed but finds nothing. For that traffic, rely on the built-in entities instead.
- Streaming. Contextual entities are checked on input and on non-streaming output. Streamed output gets the built-in entities only.
- Testing. The rule tester runs the scan without charge on up to 3 samples.
Actions
When a rule matches, one of three actions is applied. Rules are evaluated in three ordered passes — reject first, then mask, then log-only:
reject
The request is immediately blocked. On direction: input the upstream LLM is never called and the client receives 403 before any response starts, streamed or not. On direction: output a buffered response is discarded and the client receives 403; a streamed response that has already started ends with an error event instead (see Streaming Behaviour). The body uses the endpoint's own error format; param is the ID of the rule that matched:
{
"error": {
"message": "Request blocked by guardrail policy",
"type": "guardrail_error",
"param": "b3d1e2a0-...",
"code": "GUARDRAIL_REJECTED"
}
}
/v1/messages answers in the Anthropic error format, so the Anthropic SDK raises its usual PermissionDeniedError:
{
"type": "error",
"error": {
"type": "guardrail_error",
"message": "Request blocked by guardrail policy",
"param": "b3d1e2a0-...",
"code": "GUARDRAIL_REJECTED"
}
}
An output rejection reads Response blocked by guardrail policy. /v1/embeddings answers with code EMBEDDING_GUARDRAIL_REJECTED and does not name the rule (param is null).
mask
Matching substrings are replaced with mask_template before the request is forwarded (or the response is returned). The call proceeds normally with the rewritten payload.
Only regexp, string_presence, prompt_injection, and pii modes support masking.
{
"action": "mask",
"mask_template": "[REDACTED]"
}
On /v1/messages an input mask may rewrite only the last entry of messages. Rewriting the system prompt or an earlier message, including a user message followed by an assistant prefill, would invalidate the conversation's thinking signatures, so such a request is rejected with 422 GUARDRAIL_HISTORY_REWRITE instead.
log_only
The match is recorded as an event but the payload is never modified and the request is never blocked. This is the recommended mode for dry-running a new rule before enforcing it.
Precedence when multiple rules match
| Active actions |
User sees |
Events |
reject only |
403 blocked |
One per matched reject rule |
mask only |
Normal response (rewritten) |
One per matched mask rule |
log_only only |
Normal response (unchanged) |
One per matched log_only rule |
reject + others |
403 blocked |
All matched rules |
Optional Rule Settings
| Field |
Default |
Description |
enabled |
true |
Toggle a rule on/off without deleting it |
on_failure |
reject |
What to do when evaluation itself fails (e.g. judge timeout). allow lets the request through; reject blocks it. |
event_sample_rate |
1.0 |
Fraction of mask/log_only hits to persist as events (0.0–1.0). Reject hits are always stored. |
event_redaction |
partial |
How much matched text to store: full (none), partial (truncated preview), none (raw — requires PII acknowledgement). |
route_scope |
[] |
Restrict to specific routes. Empty = all routes. Values are listed in Where Guardrails Run. |
Event Sampling
High-traffic log_only rules can produce a large number of event rows. Use event_sample_rate to cap writes while still capturing trend data:
{
"action": "log_only",
"event_sample_rate": 0.1
}
This stores ~10 % of hits. reject events are always stored regardless of this setting.
Streaming Behaviour
| Mode |
Works on streaming? |
regexp |
✅ Evaluated on a sliding window over accumulated chunks |
string_presence |
✅ Evaluated on a sliding window over accumulated chunks |
pii |
✅ Evaluated on a sliding window over accumulated chunks; mask only logs |
json_validator |
❌ Silently skipped |
llm_evaluation |
❌ Silently skipped |
prompt_injection checks input only, so it runs before the request is dispatched on every endpoint, streaming included.
An input rejection on a streamed request is a plain 403 sent before the stream starts. So is an output reject match on a streamed chat completion served from the response cache: the cached output is checked against the current rules before it is replayed. For an output reject on streaming: the stream is terminated early and the client receives a GUARDRAIL_REJECTED error event; on /v1/messages it is an Anthropic event: error frame, and no message_stop follows. Chunks already flushed to the client are not recalled — handle this error event in your UI to indicate that the response was truncated.
Failure Modes
When evaluation itself fails (Redis unavailable, judge timeout, etc.) the on_failure field controls the outcome:
on_failure |
Behaviour |
reject (default) |
Block the request — favours compliance over availability |
allow |
Let the request through — favours availability over enforcement |
Use on_failure: allow for llm_evaluation rules where a judge timeout should not interrupt production traffic.
Audit Log
Every change to a guardrail rule (create, update, enable, disable, delete) is recorded as an immutable audit entry. Entries include the full before/after rule snapshot so you can diff exactly what changed and who made the change.
Access audit history from Guardrails → Audit Log in your project dashboard.
Examples
Block credit card numbers on input
const rule = await fetch("https://api.llmapi.ai/projects/{projectId}/guardrails", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.LLM_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "Block credit card numbers",
direction: "input",
mode: "pii",
action: "reject",
config: { entities: ["credit_card"] },
}),
});
Mask internal keywords before forwarding
const rule = await fetch("https://api.llmapi.ai/projects/{projectId}/guardrails", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.LLM_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "Mask internal project names",
direction: "input",
mode: "string_presence",
action: "mask",
mask_template: "[REDACTED]",
config: {
terms: ["Project Atlas", "Operation Sunrise"],
},
}),
});
Dry-run before enforcing
Start with log_only, review events in the dashboard, then switch to reject:
// Step 1 — observe
await fetch("https://api.llmapi.ai/projects/{projectId}/guardrails", {
method: "POST",
body: JSON.stringify({
title: "Detect competitor mentions",
direction: "output",
mode: "string_presence",
action: "log_only",
config: { terms: ["CompetitorX", "CompetitorY"] },
}),
});
// Step 2 — enforce (after reviewing events)
await fetch("https://api.llmapi.ai/projects/{projectId}/guardrails/{ruleId}", {
method: "PATCH",
body: JSON.stringify({ action: "reject" }),
});
Handle a rejected request in your app
const response = await fetch("https://api.llmapi.ai/v1/chat/completions", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.LLM_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "gpt-4o",
messages: [{ role: "user", content: userMessage }],
}),
});
if (response.status === 403) {
const error = await response.json();
if (error.error?.code === "GUARDRAIL_REJECTED") {
// The error names the rule by ID only; map IDs to titles via the management API
console.warn("Blocked by rule:", error.error.param);
return { blocked: true, ruleId: error.error.param };
}
}