Guardrails
Last updated: 2026-11-26T03:21:52-03:00 (UTC-3)
Guardrails inspect text before it goes to the provider and, if you want, the answer before it goes back to the app. They mask what is sensitive (a CPF becomes a placeholder) or block the request (an API key pasted by mistake). Detection can be local, with no external call, or delegated to services such as Azure AI Content Safety, Presidio, Lakera, Bedrock Guardrails or a moderation model.
| Flag | What it turns on |
|---|---|
guardrails |
Guardrails on input and output |
guardrail_management |
Editing in the console, the simulator and the catalog with metrics |
guardrail_policies |
Policies per team, key or model |
guardrail_compliance |
Compliance testing in the Playground |
guardrail_streaming |
Output guardrails inspect streamed answers in bounded windows (needs guardrails and stream_usage) |
judge_guardrails |
Provider type judge: one of your evaluators decides, at input or output (judge guardrails) |
How to turn it on
Section titled “How to turn it on”Available local detectors: email, cpf, cnpj, credit_card (with Luhn), phone, ipv4, secret_key, private_key and prompt_injection, plus your own patterns in patterns (RE2).
features: guardrails: true guardrail_management: trueguardrails: - id: pii-mask name: PII mask mode: mask # mask | block | monitor detectors: [email, cpf, cnpj, credit_card, phone, ipv4, secret_key] - id: injection name: Prompt injection mode: block detectors: [prompt_injection, private_key] patterns: - {name: ticket, regex: 'TCK-\d{6}'} models: [] # empty = all aliases - id: secrets name: Block secrets mode: block detectors: [secret_key]| Key | Default | What it does |
|---|---|---|
guardrails[].id |
required | Unique identifier, used by policies, the request header and the response counts |
guardrails[].name |
required | Display name |
guardrails[].mode |
required | mask replaces findings, block refuses the request, monitor only reports what it would do |
guardrails[].detectors |
[] |
Built-in local detectors to run, from the list above |
guardrails[].patterns |
[] |
Your own detectors: each has a name and a regex |
guardrails[].patterns[].regex |
required | An RE2 expression (linear time, no backtracking), so a pattern cannot slow a request down |
guardrails[].models |
[] |
Aliases the guardrail applies to; empty means every alias |
guardrails[].stages |
[input] |
input (request text) and/or output (the answer) |
guardrails[].disabled |
false |
Keeps the guardrail declared without running it |
- Coverage: text in Chat Completions, Anthropic Messages, OpenAI Responses and Conversations.
- Order: as declared. A
blockwith a finding ends the request with400 guardrail_blocked, before the provider is called. - Models:
modelslimits the guardrail to certain aliases; empty applies to all. - Privacy: the response and the logs carry only counts (
X-Gateway-Guardrails: pii-mask=2), never the text that was found. - Console: Guardrails, with detectors,
name=regexpatterns, models and Simulate (nothing is sent, saved or recorded). - API:
GET /api/v1/admin/guardrails(with the bootguardrail_streamingsettings under that key),PUT|DELETE /api/v1/admin/guardrails/{id},POST /api/v1/admin/guardrails/simulate.
Monitor mode (try a guardrail before enforcing it)
Section titled “Monitor mode (try a guardrail before enforcing it)”mode: monitor runs a guardrail on real traffic without acting on it. It evaluates the request text and, with the output stage, the non-streaming answer exactly as its monitor_action would, but the provider receives the request as the client sent it and the client receives the answer as the provider generated it. What it would have done is recorded, so you can measure false positives and coverage before switching the guardrail to enforcement.
guardrails: - id: pii-watch name: PII (watch) mode: monitor monitor_action: mask # block (default) | mask: what it would do sample_percent: 25 # 0-100, default 100 detectors: [email, cpf, phone] stages: [input, output] - id: moderation-watch name: Moderation (watch) mode: monitor # a provider monitor would block sample_percent: 10 stages: [input, output] provider: {type: moderation, model: safety-moderation}| Field | Default | Contract |
|---|---|---|
mode: monitor |
— | Evaluate and record; never rewrite, block, refuse or add a client header |
monitor_action |
block |
block or mask: the outcome recorded for a finding (would_block or would_mask). A provider guardrail only blocks, so it accepts only block. Only with mode: monitor |
sample_percent |
100 |
Integer 0–100: the share of requests evaluated at each stage, drawn independently for the input and the output of each request with crypto/rand, so a client cannot predict or steer which requests are evaluated. 0 evaluates nothing (no provider call). Only with mode: monitor: an enforcing guardrail always runs, since sampling a block would make the policy optional |
What is recorded for each evaluated stage, never with the matched text:
- the request event (
logging.request_events) gets aguardrails[]entry withoutcomewould_blockorwould_maskand the finding count, orpassed;error_allowedwhen a provider monitor’s service failed (whateveron_errorsays) or the answer could not be parsed;incompletewhen an enforcing guardrail stopped the request or the answer before the monitor saw it. A request that was not sampled has no entry for that guardrail; gateway_guardrail_findings_total{guardrail,outcome="would_block"|"would_mask"}counts the findings (observability);- an Info log line
guardrail_monitorwith the request ID, guardrail ID, stage, outcome and finding count.
What stays exactly as without the monitor:
- the request and the answer, their status, body and headers:
X-Gateway-GuardrailsandX-Gateway-Guardrails-Outputcount only enforcing guardrails, and no alert fires; - streams: a monitor never refuses a stream, a background response or a conversation the way a provider guardrail on the output stage does; without
guardrail_streaming, streamed answers are not evaluated at output (with it, a monitor evaluates the whole stream, see inspecting streamed answers); - an answer the monitor cannot inspect (not JSON, above 8 MiB): it goes out unchanged and the monitor records
error_allowed; - the semantic cache: monitors are not part of its key, so adding one keeps the cached answers, and a cached answer is served without evaluation;
- an enforcing guardrail next to a monitor keeps enforcing; guardrails run in declared order, so a monitor after a
masksees the masked text, as the real one would. - the request checks that only enforcing input guardrails need (the refusal of a body that repeats a member name) and the way the answer is relayed: with monitors alone on the output stage, the answer streams to the client as it arrives, live evaluation capture and the semantic cache see it as usual, and the monitors evaluate a copy afterwards.
The cost is the evaluation itself: local detectors take microseconds, but a provider monitor makes the same call to its service as an enforcing one, synchronously: on a sampled request the input check delays the provider call, and the output check runs after the answer is sent but before the response ends, so the client sees the end of the body that much later (up to the service’s timeout when it hangs). The service’s price applies too; sample_percent bounds both. Policies (default_on, guardrail_policies) and models select monitors like any guardrail. The Simulate button reports Monitor: would block or would mask and returns the sample unchanged, and the Playground compliance test lists would_block/would_mask without letting a monitor decide the verdict. A refusal is kept on a monitor that would block, unused, so turning it into an enforcing guardrail is one change: mode: block (or mode: mask). The released parameter catalogs (V10, V11) still list mask and block for guardrails[].mode; the gateway and the console accept monitor beyond them.
Tested on 2026-11-08 with the native binary, PostgreSQL 16.15 and the real OpenAI moderation endpoint (omni-moderation-latest) behind a monitor on both stages, with a local stand-in for the chat model: a threatening prompt got its normal answer (200, unchanged, no X-Gateway-Guardrails header) and its request event recorded input would_block (1 finding) and output passed; a benign prompt whose answer was the threat got that answer unchanged and recorded input passed and output would_block. gateway_guardrail_findings_total{guardrail="moderation-watch",outcome="would_block"} read 2, two guardrail_monitor lines were logged at Info, and neither the texts nor the key appeared in the output.
Policies per team, key or model
Section titled “Policies per team, key or model”With guardrail_policies, a policy groups guardrails and is attached to teams, keys or models (* for all), with inheritance and removal; a guardrail with default_on: false runs only where a policy adds it. Ready-made templates (LGPD, injection and secrets, content safety, regulated) and a simulator are on the Policies tab.
features: guardrail_policies: trueguardrail_policies: - id: regulated name: Regulated teams guardrails: [pii-mask, injection] teams: [payments, support] - id: payments-batch name: Batch key without masking inherit: regulated remove: [pii-mask] keys: [batch-key]| Key | Default | What it does |
|---|---|---|
guardrail_policies[].id |
required | Unique lower-case identifier, up to 64 characters (at most 100 policies) |
guardrail_policies[].name |
required | Display name, 1–80 characters |
guardrail_policies[].description |
empty | Up to 500 characters, shown on the Policies tab |
guardrail_policies[].inherit |
empty | Another policy whose guardrails this one starts from; chains go at most 5 deep and never loop |
guardrail_policies[].guardrails |
[] |
Up to 50 existing guardrail IDs the policy adds |
guardrail_policies[].remove |
[] |
Up to 50 guardrail IDs taken out of what the policy inherits |
guardrail_policies[].teams |
[] |
Up to 100 team IDs the policy applies to, or * |
guardrail_policies[].keys |
[] |
Up to 100 key IDs the policy applies to, or * |
guardrail_policies[].models |
[] |
Up to 100 model aliases the policy applies to, or * |
Guardrails a request adds
Section titled “Guardrails a request adds”With the operator flag request_guardrails (off by default, requires guardrails), a client adds guardrails to one Chat Completions, Messages or Responses request with a header:
X-Gateway-Add-Guardrails: pii-opt-in,injection-block- 1 to 8 distinct guardrail IDs, comma separated, in one header (up to 600 characters).
- Each one must exist, apply to the request’s alias (its
models, or all) and list the key’s team, or*, inselectable_teams. Otherwise the request is refused with403 guardrail_not_selectablebefore any guardrail or provider call; a malformed header is400 invalid_request_guardrails. A key without a team can add none. - The header only adds checks. The guardrails that already apply (default on, or through a policy) keep running, and run first: an added guardrail sees the text after them, so an added mask can never hide text from a configured block. Nothing can be removed or relaxed per request. An added guardrail runs at its own stages, input and output, streams included, as configured.
- A semantic fallback or a customer allowance fallback carries the header to its destination, which admits the guardrails again for its own alias: one that does not apply there refuses the fallback.
- With the flag off, the header is refused with
400 request_guardrails_disabled, never ignored, so a client never believes a check ran when it did not. - Other routes do not read the header.
selectable_teams is set per guardrail in YAML, in the API (PUT /api/v1/admin/guardrails/{id}) and in the console (Selectable by teams, shown while the flag is on):
features: request_guardrails: trueguardrails: - id: pii-opt-in name: PII mask on demand mode: mask detectors: [email, cpf] default_on: false # runs only where a policy or a request adds it selectable_teams: [team-a, team-b] # or ["*"] for any teamUp to 64 entries, each a team ID or *, without repetition. Empty or absent means no key may add the guardrail. A guardrail with default_on: false is the usual choice: it runs only for the requests that ask for it. The Playground lists the selectable guardrails of the console session’s teams under Request options (playground_request_options).
Catalog with metrics
Section titled “Catalog with metrics”In Guardrails › Catalog, each built-in detector appears with precision, recall and F1 measured against 55 labeled cases, and each configured guardrail, including provider ones, can be evaluated with Evaluate; the round is saved. prompt_injection and private_key are built-in detectors. API: GET /api/v1/admin/guardrails/catalog, GET …/datasets, POST /api/v1/admin/guardrails/{id}/evaluate.
Compliance testing
Section titled “Compliance testing”With guardrail_compliance, the Playground has a Compliance tab that runs the configured guardrails (including provider ones) against datasets with an expected result and counts false positives and false negatives. The API is POST /api/v1/admin/guardrails/test.
Inspecting the answer (output stage)
Section titled “Inspecting the answer (output stage)”stages says where a guardrail runs: [input] (the default) checks the request, [output] checks the answer, [input, output] checks both. The Gemini Interactions API is covered on both stages too, with its own rules for stored and streamed answers; see file inputs. The output stage covers the non-streaming answers of Chat Completions, Anthropic Messages and Responses, whether the alias serves the route natively or through translation, and their streamed answers with guardrail_streaming (see Inspecting streamed answers). The gateway reads the whole answer (up to 8 MiB), records its usage, and only then decides what the app receives.
-
maskrewrites the answer text, as on input, unless the original would stay readable (see Held rewrites). -
blockwith a refusal replaces the answer with the refusal, in the route’s own shape. The client gets200, the provider’susage, and the same finish signal the provider would send for a content filter, so SDKs need no new error handling:Route Refused answer Chat Completions choices[].message.contentis the refusal,finish_reason: content_filterAnthropic Messages one textblock with the refusal,stop_reason: refusalResponses one messageitem with the refusal,status: incomplete,incomplete_details.reason: content_filter, and a newidGenerateContent (translated) one candidate with the refusal, finishReason: SAFETY -
blockwithout a refusal (local detectors only) keeps the earlier answer:502 guardrail_blocked_output. -
Counts come out in
X-Gateway-Guardrails-Output(mod-out=1), never the text.
Only the envelope of the provider’s answer survives a refusal: id, model, created, usage and similar fields. Anything that could carry generated text (other choices, tool calls, reasoning, citations) is dropped. A refused Responses answer gets a fresh, unsigned id. The provider’s stored response can then be neither fetched through GET /v1/responses/{id} nor continued with previous_response_id.
guardrails: - id: answer-moderation name: Answer moderation mode: block stages: [output] # or [input, output] refusal: "I can't share that answer." # optional provider: {type: moderation, model: mod, on_error: block}Held rewrites
Section titled “Held rewrites”A rewritten answer must not keep the original elsewhere. Every rewrite of a non-streamed answer follows one rule: a local mask, an applied generic redaction (apply_redactions) and an extension redact verdict (which on output never rewrites and always withholds). When the original would stay readable, the answer is held instead of rewritten, as a block labelled redaction_not_applicable:
| Where the original stays | When |
|---|---|
Token logprobs |
A Chat Completions choice (or a legacy completion) whose logprobs carry tokens, or a Responses output_text part with non-empty logprobs: they spell the generated tokens out again. Empty shapes ({"content": null}, {"content": []}) do not count |
| A text the mask does not rewrite | A local mask rewrites only the visible text. When one of the local guardrails still finds something in the masked answer’s other generated text (reasoning, an audio transcript, tool-call arguments, a block read whole), the answer is held |
| The provider’s stored answer | A Responses answer that is stored: its store is not false, or the provider left store out and the request did not send store: false. The stored original is readable through GET /v1/responses/{id} and is continued with previous_response_id. store: null counts as stored, and so does an answer that names a conversation |
A Chat Completions alias on an openai target sends store: false whenever an enforcing output guardrail covers the alias and the client or the target’s request policy set store (an absent store stays absent). On a Responses-API target (api: responses, or auto when it picks Responses) the chat answer carries the provider’s raw resp_ id, and a stored original could be read or continued through it; on Chat Completions OpenAI would keep a stored completion of the original. The override is not reported in a header. Without such a guardrail (monitors only, or none) the client’s store goes through.
A held answer is answered like a block: a provider guardrail with its refusal (200), a local mask with 502 guardrail_blocked_output (a mask has no refusal). The finding still counts in X-Gateway-Guardrails-Output and the request event shows the guardrail as blocked. Messages answers carry neither, so they are always rewritten. To keep masking instead of holding, send logprobs: false and, on Responses, store: false. Answers with no finding are never held. Every guardrail whose mask fired is counted blocked in the metrics when the answer is held. A Responses request with background: true or a conversation is refused before dispatch (400 guardrail_output_unsupported) when any enforcing output guardrail covers the alias, local ones included: the answer is read later, outside the guardrails.
refusal
Section titled “refusal”| Field | Default | Bounds |
|---|---|---|
refusal |
empty. A provider guardrail then answers This answer was withheld by a content policy.; a local one answers 502 |
1 to 500 characters, no surrounding spaces; line breaks allowed, but no other control, line-separator or bidirectional-override characters, which could disguise the text in a log or a chat window. Only with mode: block and the output stage. |
Provider guardrails always answer with a refusal, because the answer was generated and paid for: a 200 with the provider’s usage lets the reservation settle and the cost be valued from that usage. A local guardrail keeps its 502 unless you set a refusal, so existing configurations behave as before. The console shows the field as Refusal (replaces a blocked answer) once the guardrail is block and Answer (output) is checked.
Usage, logs and audit
Section titled “Usage, logs and audit”- Billing: the provider’s usage is read from its own answer before the check. A refused answer is recorded as a
200with those tokens, so budgets, TPM and cost see what the provider charged. A502or503withholding still records the tokens, but, like any failed request, its cost stays unknown and its reservation stays held until reconciliation. - Log: one
guardrail_blocked_outputline withrequest_id,guardrail_id,stage: output, thecategoriesthe service named (for exampleviolence) andaction(refusalorerror). The answer itself is never logged. - Alert event:
guardrail_blockedwithmodel,stage: outputandcategories, for channels subscribed to that event. - Metrics:
gateway_guardrail_findings_total{guardrail,outcome="blocked"}.
Streams, background responses and conversations
Section titled “Streams, background responses and conversations”Without the guardrail_streaming flag the gateway does not inspect a stream. While a provider guardrail checks the answers of an alias, a request whose answer would escape the check is refused before anything is sent or billed, with 400 guardrail_output_unsupported:
stream: trueon Chat Completions, Messages, Responses or GenerateContent (withguardrail_streamingon, see Inspecting streamed answers);- a Responses request with
background: true, whose answer is fetched later; - a Responses request with a
conversation, whose answer is stored where its items can be listed; - any GenerateContent call (
:generateContentor:streamGenerateContent) on an alias served natively by Gemini, which the gateway relays without inspection. Such an alias cannot be used on/v1betawhile a provider guardrail covers its answers; an alias that reaches another provider through translation is inspected; - a
/v1/realtimesession.
Without this refusal, any client could skip the moderation by setting one field. To let an alias stream without inspection, scope the guardrail to other aliases with models. Without the flag, local output guardrails keep their earlier behavior: streams go through without inspection.
Inspecting streamed answers
Section titled “Inspecting streamed answers”With features.guardrail_streaming: true (it needs guardrails and stream_usage), the output guardrails inspect streamed answers instead of refusing them. This covers:
| Stream | Inspected as |
|---|---|
| Chat Completions, native or translated to any provider | OpenAI chat chunks |
| Anthropic Messages, native | Messages events |
| Anthropic Messages, Responses and GenerateContent translated through the chat format | OpenAI chat chunks, before the gateway turns them into the client’s dialect |
| Responses, native | Responses events; the request needs store: false, read on the body every target of the alias would be sent after its request policy, before any guardrail call, reservation or send (a target whose policy sets store: true refuses the stream with 400 guardrail_output_unsupported, whatever the order the targets are tried in; a policy store: false satisfies it) |
GenerateContent on an alias served natively by Gemini, /v1/realtime |
not inspected: still refused while a provider output guardrail covers the alias |
How a stream is held:
- The gateway reads the provider’s stream into complete SSE events. A character or an event split across network reads is put back together before anything is decided.
- It takes the generated text out of each event: the visible text, and also reasoning, refusals, tool-call arguments, transcripts and fields it does not know. An event without generated text (the role chunk,
message_start,response.created) goes out at once when nothing is waiting. - Events with text are held until
window_bytesof new text has arrived. Withboundary: sentence, the gateway then waits for a sentence end, but never past twice the window. The end of the answer ([DONE],message_stop,response.completed) triggers the check at once. - The held text is checked together with the last bytes already sent. Local guardrails check each output channel (a choice, a content block), and provider guardrails check everything generated, after masking.
- Events that passed go out in order. The last
holdback_bytesof text stay held and are checked again with the next window, so a value that straddles two windows is caught before any part of it is sent.
What ends a stream: a finding of a block guardrail, a required check that failed (on_error: block), a text larger than the service checks, or an event larger than max_held_bytes. When that happens, nothing that was held is sent, and the gateway keeps reading the provider’s stream to its end without forwarding it. That way the usage the provider reports is recorded exactly and billed as for any answer. The client then gets one error event in its own dialect, and nothing after it:
data: {"error":{"code":"guardrail_blocked_output","message":"I can't share that answer.","param":null,"type":"content_filter"}}| Dialect | Error event |
|---|---|
| Chat Completions | data: {"error":{"code":...,"message":...,"param":null,"type":...}}, without [DONE] |
| Messages | event: error with {"type":"error","error":{"type":"api_error","message":...}} (overloaded_error when a check failed) |
| Responses | event: error with {"type":"error","code":...,"message":...,"param":null} |
| Code | When | Message |
|---|---|---|
guardrail_blocked_output |
a block guardrail found something | the guardrail’s refusal, or the default refusal for a provider guardrail, or The answer was blocked by guardrail <id> |
guardrail_unavailable |
a required check failed | A required guardrail could not check the answer |
guardrail_output_unavailable |
an event above max_held_bytes, or a text above what the service checks |
The answer could not be inspected by output guardrails |
Masking rewrites the held text before it is sent. The masked text of each channel goes into the window’s first event of that channel, and the channel’s later events in the window carry an empty string. Every other field stays as the provider sent it. Some text cannot be rewritten in place: a finding there ends the stream as a block would. That covers:
- a finding that starts in text already sent;
- any finding in a native Responses stream, whose done events and final response repeat the text, unless
guardrail_stream_responses_maskis on (below); - a chat stream, or a native Responses stream, that returns token
logprobs; - text outside a text delta, such as content parts, non-JSON data or a done event that differs from its deltas.
Native Responses streams masked in place (operator flag guardrail_stream_responses_mask, off by default, requires guardrail_streaming). A Responses stream says its text twice: in response.output_text.delta events, then whole in response.output_text.done, response.content_part.done, response.output_item.done and the terminal response.completed (or response.incomplete, response.failed). With the flag on, a mask finding rewrites the deltas like a chat stream, and each later event that repeats a masked channel’s text carries exactly the masked text the client already received for it. No event is added, removed or reordered: the event names and every sequence_number stay as the provider sent them, and every other field (reasoning items with their encrypted_content, usage, obfuscation, item IDs) is unchanged. These still end the stream: a block finding, a finding in text already released, deltas with non-empty token logprobs, and a done event whose text differs from its deltas (it is scanned on its own and cannot be rewritten consistently). The guardrail list (GET /api/v1/admin/guardrails, streaming.responses_mask) and the console’s streamed-answers note say whether the flag is on. Limit: annotations offsets (start_index, end_index of a citation) in a masked part are not shifted; the native Responses route still needs store: false, so no unmasked original is kept by the provider.
features: guardrails: true stream_usage: true guardrail_streaming: true guardrail_stream_responses_mask: trueMonitors (mode: monitor) never hold a stream. The answer goes out unchanged, and the monitors check the whole text once the stream ended (up to 8 MiB), recording would_block or would_mask as for a JSON answer.
Client gone: when the client disconnects, nothing more is written, not even the error event, and the guardrails that had text still waiting record incomplete.
A provider that fails mid-stream: the text it sent before failing is checked and released, then the usual interruption event follows. An event the provider never finished is dropped.
features: guardrails: true stream_usage: true guardrail_streaming: trueguardrail_streaming: window_bytes: 1024 # new text checked at once holdback_bytes: 256 # checked text kept back and checked again with the next window boundary: sentence # or bytes max_held_bytes: 1048576guardrails: - id: answer-moderation name: Answer moderation mode: block stages: [output] stream: inspect # default; refuse keeps answering streams with 400 provider: {type: moderation, model: mod, on_error: block}| Field | Default | Bounds |
|---|---|---|
guardrail_streaming.window_bytes |
1024 |
64 to 65536 |
guardrail_streaming.holdback_bytes |
256, or half of a smaller window |
0 to 4096, smaller than window_bytes. The last 256 bytes sent (or holdback_bytes, if larger) are always rechecked as context. |
guardrail_streaming.boundary |
sentence |
sentence (a window waits for ., !, ?, ;, :, a line break or their CJK forms) or bytes |
guardrail_streaming.max_held_bytes |
1048576 |
65536 to 16777216, and at least four times window_bytes plus holdback_bytes. Reaching it with many events checks and releases early. A single larger event ends the stream. |
guardrails[].stream |
inspect |
inspect or refuse; only with the output stage. refuse answers stream requests on the aliases it covers with 400 guardrail_output_unsupported before dispatch. It has no effect while the flag is off. |
The guardrail_streaming block is read at boot (restart to apply). The console shows it, read-only, under Streamed answers in the guardrail editor, where stream is set.
Costs and trade-offs:
- Every window is a call to each provider guardrail. Their request IDs are
<request-id>.w<n>.guardrail-output, so each call has its own record. A larger window means fewer calls, and a longer wait before the first text. - The client sees text in bursts, one window at a time.
- A blocked stream’s error event arrives only after the provider finished generating, because the usage must be measured. A client with a short read timeout may give up first. If it does, it is recorded as a client cut.
- A streamed answer is never written to the semantic cache while an output guardrail applies.
An answer that was refused, blocked, or passed only because a guardrail service failed open is never written to the semantic cache. An answer that passed is cached as the client saw it, and a later hit is served without a new check. The cache key includes the output guardrails that applied, with their settings, so the hit already passed the same checks. Changing a guardrail changes the key. The exact cache does not serve Chat Completions, Messages or Responses.
External services
Section titled “External services”External services run after the local detectors, on the already masked text. A guardrail with provider needs mode: block, has no detectors or patterns of its own and runs on input, on output or both (stages). If the service fails, the response is 503 guardrail_unavailable, unless the guardrail declares on_error: allow.
On the output stage the service receives the generated text of the answer: its content, refusals, audio transcripts, the reasoning the provider returned and tool calls. A harmful answer can be written into a tool call or a reasoning summary that an app displays, so they are checked too. A block, item or message field the gateway does not know (hosted tool results, provider extensions) goes as its JSON, without base64 images, encrypted content and signatures: something unknown is never treated as nothing to check. Search results and code output in an answer are checked as well, so they can also be flagged. Each service is told it is reading an answer:
| Service | What changes on output |
|---|---|
| Moderation model | internal call with the derived ID <request_id>.guardrail-output (input uses .guardrail) |
| Azure AI Content Safety | harm categories only; Prompt Shields rates prompts, so an output guardrail needs categories |
| Presidio | the same analysis on the answer text |
| Amazon Bedrock Guardrails | source: OUTPUT |
| Generic guardrail API | input_type: response |
| Lakera Guard | the answer goes as assistant messages |
| Judge (an evaluator) | {{output}} is the answer; internal call <request_id>.guardrail-judge-output.0 (input uses .guardrail-judge.0) |
Service failure on output follows on_error, as on input. With block (the default) the answer is withheld with 503 guardrail_unavailable: the provider generated it, but the required check did not run. With allow the answer goes out, a Warn guardrail_provider_failed line with stage: output is logged, and the answer is not cached.
An answer longer than the service checks is withheld with 502 guardrail_output_unavailable even with on_error: allow. The client decides how long the answer is, so a size limit that let the answer through would be a way around the check. The limits are 200,000 characters for a moderation model (ten parts of 20,000), 100,000 for Presidio, Bedrock, Lakera and the generic API, and ten parts of 10,000 for Azure AI Content Safety. On input the earlier behavior stays: an oversized request is a service failure, and on_error decides.
The Compliance tab tests a guardrail that runs only on answers the way it reads answers: no Prompt Shields, Bedrock OUTPUT, Lakera assistant, generic input_type: response.
Judge (one of your evaluators)
Section titled “Judge (one of your evaluators)”Type judge runs one of your evaluators on the text, with its judge model: a fail assessment blocks (or, in monitor mode, would block). Settings: evaluator (required), max_tokens (16-600, default 64), max_input_chars (100-100000, default 8000), timeout and on_error. The evaluator must belong to the request’s team or to a team of the same organization; streams are refused. Everything about it, cost and latency included, is in Judge guardrails.
Azure AI Content Safety
Section titled “Azure AI Content Safety”A guardrail can delegate detection to Azure AI Content Safety:
guardrails: - id: safety name: Content safety mode: block # required with provider provider: type: azure_content_safety endpoint: https://<resource>.cognitiveservices.azure.com api_key_env: CONTENT_SAFETY_KEY # optional; without it, uses Entra ID categories: [Hate, SelfHarm, Sexual, Violence] severity_threshold: 4 # 0-7 prompt_shields: true # jailbreak on_error: block # or allow| Key | Default | What it does |
|---|---|---|
provider.endpoint |
required | The resource’s https URL, https://<resource>.cognitiveservices.azure.com, with no path |
provider.categories |
[] |
Azure categories that block: Hate, SelfHarm, Sexual, Violence; the guardrail needs categories, prompt_shields or both |
provider.severity_threshold |
4 |
Severity, 0–7, at or above which a category blocks |
provider.prompt_shields |
false |
Also runs Azure Prompt Shields, which blocks jailbreak attempts |
- Order: runs after the local guardrails, on the already masked text.
- Blocking: responds 400
guardrail_blocked, with a count inX-Gateway-Guardrails. - Service failure: 503
guardrail_unavailable, unlesson_error: allowis set. - Console: in the guardrail editor, check Check with an external service (blocks) and choose the service; check Answer (output) to also check answers.
Presidio (PII by an external analyzer)
Section titled “Presidio (PII by an external analyzer)”provider.type: presidio queries the open source Presidio Analyzer, running alongside the gateway:
guardrails: - id: pii-presidio name: PII (Presidio) mode: block provider: type: presidio endpoint: http://presidio-analyzer:3000 entities: [CREDIT_CARD, US_SSN, IBAN_CODE, PERSON] language: en score_threshold: 0.7 on_error: block-
When it runs: after the local detectors, on the already masked text. | Key | Default | What it does | | — | — | — | |
provider.endpoint| required | The analyzer’s http(s) URL; the gateway calls its/analyze| |provider.entities| required | 1–50 Presidio entity types that block (PERSON,CREDIT_CARD,US_SSN,IBAN_CODE, …) | |provider.language|en| Two-letter lower-case language code the analyzer reads the text in (en,pt) | |provider.score_threshold|0.5| Minimum recognizer score, 0–1, for an entity to block | -
What it blocks: each entity of a listed type with a score at or above the threshold blocks with 400
guardrail_blocked. Types the analyzer returns that are not on the list do not block. -
Service failure: with
on_error: block(the default), it responds 503; withallow, it lets the request through. -
Tested with the official
mcr.microsoft.com/presidio-analyzerimage and the real OpenAI: an ordinary question passed; a card number and a person’s name were blocked before the provider; the email, masked locally, went through.
Moderation model
Section titled “Moderation model”provider.type: moderation uses any moderations alias of the gateway itself:
models: - id: mod capabilities: [moderations] targets: [{provider: openai, model: omni-moderation-latest}]guardrails: - id: moderation name: Moderation mode: block models: [gpt] # empty = all aliases provider: type: moderation model: mod categories: [violence, self-harm/intent] # empty = whatever the provider flags score_threshold: 0.4 # optional: blocks by category_scores on_error: block- As the caller: moderation runs as the key that made the request, restricted to the
modalias. It appears in the request log and the usage ledger under that key and its team, and the key does not need its own access to the alias. - Budgets and token ceilings do not apply to the check: the moderation call is the gateway’s own check, chosen by the operator, so it takes no budget or TPM reservation and is never refused for quota, whatever policy applies to the caller (its key, team, user, project, organization, end user, or the moderation alias itself). A policy whose subject is the moderation alias therefore refuses every direct call to it (
422) and never applies to guardrail checks. The guarded request is reserved and settled as usual. Moderation has no quota profile, so without this exemption a covering policy would refuse every check. Nothing of the check is charged to the caller’s budget, TPM or TPD. A client calling/v1/moderationsdirectly is still refused under a covering policy (422 quota_profile_unsupported, see moderation); the exemption is attached only to the gateway’s own in-process call and cannot be requested by a header or a body field. - Where the check is visible: each check is its own entry in the request log and the usage ledger, with
operation: moderations, the caller’s key and team, the derived request ID<request_id>.guardrail(.guardrail-outputon the answer) and, in request audit events,"internal": true. Its tokens and cost are recorded as unknown, like any moderation call. With evaluation tracing on, every check is ahelpercall of kindguardrail, so the guardrails’ spend is its own line in Cost estimates (Spend by origin,by_helper_kindonGET /api/v1/admin/valuation), apart from the application’s. A moderation call has no price model, so today that line counts the checks as unknown rather than zero; a helper call valued through a priced model shows its known amount in the same line. A provider that bills moderation (by tokens, for example) charges the connection’s account; that cost is not in the caller’s budget, so read it from the provider’s billing. - RPM does not count the check either: for the same reason, the check is not a request of the caller’s key, team or end user for RPM. The guarded request is counted once, as before, and over its limit it answers
429 rate_limit_exceededbefore any guardrail runs, so no check is made for it. A check is therefore never refused for RPM:rpm: 1lets one guarded request a minute through with all of its checks (input and output),on_error: blocknever turns the caller’s RPM into503 guardrail_unavailable, andon_error: allownever lets a request out unchecked because of it. Monitor guardrails’ checks spend no RPM either. The check also takes no concurrency slot and is not checked for required attribution. Only that in-process call is exempt: a client calling/v1/moderationsdirectly, and the gateway’s other in-process calls, count as before, and no header or body field claims the exemption. - A request already over its quota does not pay for a check: input guardrails run before the guarded request’s quota reservation, because the reservation is estimated from the request as they leave it, and a mask can make the text longer or shorter. Right before the first moderation check of the request (enforcing or monitor), with
budget_limitsortpm_limitson, the gateway asks the quota store, without reserving or changing anything, whether that admission is certain to refuse the request whatever the guardrails do to its text: what settled requests already spent on a daily or monthly budget or TPD counter of a policy that applies leaves no room for the smallest reservation the request could take, or a budget, TPM or TPD ceiling is below that smallest reservation by itself. The smallest reservation is the request’s output limit plus the fixed 4,096-token allowance every input estimate carries, with the request’s images and shape as they are (a mask replaces text, never parts or items). If so, the request answers429 quota_exceededfor that policy, with theRetry-After,X-Gateway-Quota-PolicyandX-Gateway-Quota-Dimensionthe admission uses, and the moderation provider and the model’s provider are not called. It exists because a provider that bills moderation would otherwise charge a check for a request already bound to be refused.- It never refuses what the admission would admit: it applies the admission’s own comparison to that lower bound, so where it refuses, any larger reservation is refused too, and it counts only what cannot free before the admission runs. Reservations of requests still in flight are left out, since they may settle lower or be released. A TPM counter never refuses by its content, since its minute may end first; a daily or monthly counter does only while its window lasts longer than the guardrails and the admission can take (7 seconds per provider check of the stage, plus 5). A counter a billing reconciliation lowered below what its open reservations hold counts as empty. Only an operator action in those seconds (a billing import, a policy edit) can still change the outcome. When several policies would refuse, the admission might have named another one of them.
- When it is not certain, nothing changes: with room smaller than this request’s estimate but not smaller than the lower bound, room taken only by requests in flight, a full TPM minute, a profile or settings refusal (
422 quota_profile_unsupported), storage trouble, or a quota store other than PostgreSQL, the check runs and the admission answers after it, as before; such a request still makes one moderation call per input guardrail before its429. - Order: local detectors still run first and keep their
400 guardrail_blocked. A request the moderation check would have blocked, but that is certainly over its quota, gets the429. A provider guardrail listed before the first moderation guardrail still runs before the precheck. - Cost: with
budget_limitsortpm_limitson, each request that reaches a moderation guardrail reads the quota state once more (one short read transaction, no locks on counters; open reservations are found through their own index) before its check.
- What it blocks: without
categoriesand withoutscore_threshold, it blocks whatever comes backflagged. With categories, only the listed ones. Withscore_threshold, the score of each category applies. - When it runs and failures: order and failure handling are the same as Presidio: after the local detectors, 400
guardrail_blocked, and 503 withon_error: block. - OpenAI project: if the project restricts models, allow
omni-moderation-latestin it. Without that, OpenAI responds 403 and the guardrail fails closed. - Other providers: any
/v1/moderationsprovider works, and it was validated with OpenAI and Mistral. When the response has noflaggedfield (Mistral), any flagged category counts. - On answers: with
stages: [output]the same alias checks the answer, as a second moderation call per request (<request_id>.guardrail-output), also billed to the caller’s team. A flagged answer becomes the refusal; see Inspecting the answer. - Calibration: OpenAI’s
flaggedis sensitive; a question about a fight scene in a movie gets violence 0.43 and is flagged. To block threats (0.9+) without stopping that kind of question, usecategories: [violence]with ascore_thresholdaround 0.6.
Amazon Bedrock Guardrails
Section titled “Amazon Bedrock Guardrails”provider.type: bedrock_guardrail applies an AWS guardrail (ApplyGuardrail) to the request text, signed by one of the gateway’s own Bedrock connections:
providers: - id: aws protocol: bedrock base_url: https://bedrock-runtime.us-east-1.amazonaws.com auth: {type: aws_sigv4, region: us-east-1}guardrails: - id: bedrock name: Bedrock guardrail mode: block provider: type: bedrock_guardrail connection: aws # bedrock provider: region and identity guardrail_id: abc123def456 guardrail_version: "3" # default DRAFT on_error: block| Key | Default | What it does |
|---|---|---|
provider.connection |
required | ID of one of the gateway’s bedrock providers; its region and SigV4 identity sign ApplyGuardrail |
provider.guardrail_id |
required | The AWS guardrail identifier |
provider.guardrail_version |
DRAFT |
The guardrail version to apply, as a string ("3") |
- Policies: configured in AWS: filters, prompt attack, topics, words, PII, regex.
- What it blocks: each
BLOCKEDaction counts as a finding and blocks with 400guardrail_blocked. - Anonymized PII: PII with
ANONYMIZEdoes not block and goes through unmasked. To mask, use the local detectors or Presidio. - When it runs and failures: same order and same
on_erroras the other external services. - Permission: the connection’s identity needs
bedrock:ApplyGuardrailon the guardrail.
Generic guardrail (your own API)
Section titled “Generic guardrail (your own API)”provider.type: generic_api calls a service of yours: the gateway sends the request texts and the service responds whether to block. Use it for your company’s own rules:
guardrails: - id: company-policy name: Company policy mode: block provider: type: generic_api endpoint: http://guardrail-service:8080/check # the service's full URL api_key_env: GUARD_KEY # sent as x-api-key params: {policy: strict} # additional_provider_specific_params apply_redactions: false # true applies GUARDRAIL_INTERVENED texts timeout: 5s # 100ms-30s, default 5s on_error: block- What the service receives:
texts, already masked by the local detectors;modelandinput_type: request;call_idandtrace_id, with the request ID and the trace ID;request_data: the key’s alias, team and end user.
- What is not sent: client headers and the structured conversation.
- Decision:
BLOCKEDblocks with 400;NONElets the request through;GUARDRAIL_INTERVENEDlets it through unchanged by default: itstextsare advice. Withapply_redactions: truethey are applied (below);- any other action or a status other than 200 counts as a failure (
on_error).
- Applying redactions (
apply_redactions: true):- Validation: the answer must carry
textswith one JSON string per text sent, in the same order, each at most twice the original plus 4,096 bytes. A missing list, another count, anullor a number is a failure, andon_errordecides:blockanswers 503,allowsends the original text and logs the failure. - Input: each text replaces the one sent, in place. Roles, tool calls, images and the message structure stay as the client sent them; the next guardrails and the provider see the redacted text.
- Output (a non-streaming answer, with the
outputstage): the texts replace the visible answer text and refusals. A change the answer cannot carry rewritten (reasoning, an audio transcript, tool-call arguments, a block checked as raw JSON) withholds the answer with the guardrail’s refusal, so neither the original nor a half-redacted answer goes out. So does a redaction of an answer with tokenlogprobsor a stored Responses answer (Held rewrites). - Streams: a streamed window joins already released text, every output channel and the non-visible text in one check, so it cannot be rewritten. A redaction ends the stream like a block (error event
guardrail_blocked_output). Usestream: refuseif clients should sendstream: falseinstead. - Monitors (
mode: monitor) never rewrite; a redaction counts as a finding they would act on. - Audit: an applied redaction is counted as
maskedinX-Gateway-Guardrails(or-Output), in the metrics and in the request event, and logged asguardrail_redaction_appliedwith the guardrail ID and the number of texts changed and checked. Never the text. - Failure policy: pair it with
on_error: block. Withallow, a check the service cannot finish (a long request that outlaststimeout, for example) lets the original text through.
- Validation: the answer must carry
- Timeout:
timeoutis the deadline of one check, from100msto30s(default5s); every provider type takes it exceptextension, whose deadline is the plugin manifest’stimeout_ms. The guardrail editor offers Extension plugin as an external service whileextension_guardrailsandextensionsare on: it asks for the plugin ID only, with no endpoint, key or timeout. The deadline cancels the call, and a check cut by it is a failure (on_error). - Example service: a Python implementation of this contract, with a pinned Containerfile, a health check and timeout guidance, is in
extensions/examples/python-guardrail; see Out-of-process plugins (Python and ML).
Lakera Guard
Section titled “Lakera Guard”provider.type: lakera_guard calls Lakera Guard v2. The policy (prompt attack, PII, moderated content) lives in a Lakera project:
guardrails: - id: lakera name: Lakera Guard mode: block provider: type: lakera_guard api_key_env: LAKERA_API_KEY project_id: project-1234 # optional: that project's policy # endpoint: https://lakera.internal # only for self-hosted Lakera on_error: block| Key | Default | What it does |
|---|---|---|
provider.endpoint |
Lakera’s SaaS | The https base URL of a self-hosted Lakera; the key goes to it as a bearer token |
provider.project_id |
empty | Lakera project whose policy decides; without it the account’s default policy applies |
provider.api_key_env |
required | Variable holding the Lakera API key |
- Blocking:
flaggedblocks with 400, and each triggered detector counts inX-Gateway-Guardrails. A response without a verdict is a failure (on_error). - Tested with the real Lakera: a prompt attack in English and in Portuguese and an insult were blocked, and an ordinary question passed.
Limits
Section titled “Limits”- The output of streams is inspected only with
guardrail_streaming, in windows. Without it, a provider guardrail on the output stage refuses streams for the aliases it covers. Responses background requests and conversation turns are always refused, and so are stored (storenotfalse) native Responses streams while the flag is on. - A streamed value longer than
holdback_bytesthat straddles two windows can have its first part sent before the stream ends. Raiseholdback_bytesabove the longest value you mask or block. - On output, the local detectors mask only the visible answer text; the external services also read refusals, reasoning and tool-call arguments.
- A semantic fallback (
content_policy_fallback,context_window_fallback) answers through the other alias, whose own output guardrails apply, not those of the alias the client named. - The local detectors are heuristic: check precision and recall in the Catalog before you trust a block.
- The evaluated text never goes to logs or telemetry; only the counts do.
- External services receive the already masked text; check each service’s terms before sending data. On output they also receive reasoning, transcripts and tool calls, which the local detectors do not mask.
- A refusal replaces what the client receives, not what the provider did. The provider may still keep the response it stored (Responses
store), and a code-interpreter container it created is still claimed for the caller’s team. A refused Responses answer cannot be continued withprevious_response_id; an agent that chains responses starts over. - Bedrock
ANONYMIZEDdoes not block and does not rewrite the answer, as on input; nor does a generic APIGUARDRAIL_INTERVENEDwithoutapply_redactions. - A moderation guardrail on answers is a second call made as the caller. Like the input check it takes no budget or TPM reservation and spends no RPM (see above); if it fails for any reason,
on_errordecides, and withblockthe answer is withheld. The quota precheck applies only before input checks: the answer’s check runs after the request was admitted. - The native Gemini GenerateContent relay runs neither input nor output guardrails; see the refusal above for output provider guardrails.
Admin API routes
Section titled “Admin API routes”Every route below needs a console session or an admin Bearer token, the role’s permission and, for writes, the X-CSRF-Token header; the full contract is in the API reference.
| Route | What it does |
|---|---|
GET /api/v1/admin/guardrail-policies |
Lists the guardrail policies (GuardrailPolicy, with their source) and the ready-made templates |
PUT /api/v1/admin/guardrail-policies/{id} |
Creates or replaces a console policy |
DELETE /api/v1/admin/guardrail-policies/{id} |
Removes a console policy, or reverts a YAML one |
POST /api/v1/admin/guardrail-policies/simulate |
Shows which guardrails a request of a given team, key and model meets, and why |
POST /api/v1/admin/guardrail-policies/templates/{id}/apply |
Creates a template’s guardrails and a policy attached to the given teams, keys or models, in one change |
GET /api/v1/admin/guardrails/datasets |
The labeled cases the catalog and the compliance test use |
POST /api/v1/admin/guardrails/simulate |
Runs a draft guardrail on up to 8 KiB of sample text; nothing is sent or stored |
See also
Section titled “See also”- Guardrails: overview.
- Playground: the Compliance tab.
- Access control: the
guardrails:readandguardrails:managepermissions.
Policy schema boundaries
Section titled “Policy schema boundaries”Guardrail definitions and inheritance remain typed domain configuration. Pattern content, external endpoint and credential references are not published through the safe parameter catalog. Shared parameter definitions must preserve existing stages, detector/provider validation, default-on behavior, inheritance and removal precedence. A schema or enabled flag never grants access to a provider, model or managed writer.
Presidio and moderation score_threshold values must be finite and within 0–1. Their zero semantics remain different: Presidio selects its 0.5 fallback, while moderation keeps its existing provider-flag/category decision behavior. YAML NaN and infinities do not bypass these bounds.
Guardrail display names follow the server limit of eighty Unicode runes; identifiers retain their separate ASCII grammar. The score controls accept continuous values without rounding to a fixed increment, while the server remains authoritative for bounds and provider-specific validation.
On observed loss of management access or accepted configuration metadata, the console discards guardrail drafts and simulation results. A response started under the previous authority cannot restore them afterward. This adds no polling or permission grant.