Guardrails are the safety checks that run on AI traffic inside the gateway: they inspect a request before the model sees it (llm_input) and the model’s response before your client does (llm_output). A guardrail can validate content — allow it or block it — or mutate it, replacing what it found before the request or response continues. Every guardrail runs inside the gateway process. There are no external moderation services, no remote guardrail servers and no third-party calls on the request path.
Guardrails decide what safety checks apply. Policies decide whether a request is allowed at all. Policy runs first; a request refused by a policy never reaches a guardrail.

Concepts

Groups, guardrails and rules belong to a Gateway workspace, or — with "scope": "organization" — to the organization, where they apply to every Gateway workspace. A resource in one workspace is invisible from every other. In the console, open Guardrails in the Gateway sidebar: the Registry tab holds groups and their guardrails, the Rules tab holds rules.

The built-in guardrails

GET /admin/gateway/guardrail-types returns the same catalog with each type’s operations, default operation, default priority and default settings.

Operations

Validate inspects content and never changes it. If the guardrail finds a violation, the verdict is block. Mutate may rewrite content. The rewritten content is what every later guardrail, and the model, receives:
When a PII vault key is configured, a mutating pii guardrail in placeholder mode, a mutating secrets guardrail and a mutating regex guardrail replace each value with a numbered token ([PII_1], [SECRET_1], [REGEX_1]) instead of the configured text, and the original is kept encrypted with the request trace. Masks and other rewrites (such as SQL comment stripping) are recorded as before/after pairs. In both cases Show original restores the request. Only the request side (llm_input) is tokenized; a response keeps the replacement the client received. Mutating guardrails run one at a time, in ascending priority — lower numbers first — because each one’s output is the next one’s input. Validating guardrails run after every mutation, concurrently, over the final mutated content.

Enforcement strategies

A violation (the guardrail ran and rejected the content) and an error (the guardrail could not complete, or timed out) are different facts, and strategies treat them differently: In audit mode a mutating guardrail records what it would have changed but leaves the content untouched.

How a request flows

Input validation runs alongside the model call, so an allowed request pays no extra latency for it. Nothing the model returns reaches your client until input validation has allowed the request; if it blocks, the upstream call is cancelled and the response is discarded. A cache hit is held to the same guardrails: input validation must allow the request, and the cached completion must pass the output hook, whether or not the request streams.

Streaming

With "stream": true, input guardrails run as usual. When any output guardrail applies, the gateway holds the provider’s stream, runs the output guardrails on the assembled completion, and then re-emits the guarded completion to your client as a stream — or returns the refusal. Nothing the model generated reaches your client before the output guardrails have passed it. The cost is time to first token. Such responses carry X-ManyLayers-Guardrails-Output: buffered-streaming.

Message scope

Each guardrail has a message_scope: all (default), last, or a number N for the latest N messages. System and developer messages are never inspected — they are your instructions, not caller content — and are never rewritten. Text parts of a multimodal message are inspected and rewritten individually; image parts are left as they were.

Rules

A rule targets requests and binds guardrails to hooks:
  • A rule must bind at least one guardrail, binds at most 50 guardrails per hook, and each list in conditions holds at most 100 entries.
  • Within a rule, every dimension it names must match; a dimension matches when the request’s value is any listed value. An empty dimension matches everything.
  • users matches the person a request belongs to — the session’s user, or the person an API key was issued to.
  • teams matches the request’s team, or a team its person belongs to.
  • keys matches the API key the request arrived on.
  • service_accounts matches every request made through that virtual account, across all its tokens. Like keys, it is allowed on workspace rules only; an organization-wide rule that names a key or a virtual account is refused.
  • models matches the requested model or the model an alias points at.
  • metadata matches values from the X-ManyLayers-Metadata request header. A key listed with no values matches any value for that key.
  • Every matching rule applies. Resolution is a union, never first-match-wins. A guardrail selected by several rules runs once.
A workspace rule may bind its own workspace’s guardrails and organization-wide ones; an organization-wide rule may bind only organization-wide guardrails. A rule can also be disabled without deleting it (PATCH with {"enabled": false}). Creating a group in the console also lets you say where it applies (applies: named, workspace or conditions). That is saved as a rule the group owns, listed under Rules.

Selecting guardrails per request

A request can add guardrails with the X-ManyLayers-Guardrails header:
Names are <group>/<guardrail> or guardrail ids; the header holds at most 32 names and 8 KB. The header only adds guardrails — it cannot remove one a rule applies. Naming a guardrail requires gateway.guardrails.read, and only guardrails visible from the caller’s workspace resolve; anything else is unknown_guardrail. A group restricted to named users, teams or keys can be selected only by them (403 guardrail_access_denied); the deployment operator and anyone holding gateway.guardrails.manage in the workspace can always select any group. This limits who can choose a group, never whether a rule’s guardrails apply. The header is never forwarded to a provider.

Errors

Configuring a guardrail

The admin API is served by the console at https://app.manylayers.io. Authenticate with a personal access token (ml_pat_…) and name the Gateway workspace with ?workspace_id=. A group and its guardrails are usually written together, in one call. Either the whole group is stored or none of it is:
PUT /admin/gateway/guardrail-groups/{id} with a guardrails list replaces the group’s guardrails in the same way: an entry with an id updates that guardrail, an entry without one creates a guardrail, and a guardrail you leave out is deleted — which also removes it from every rule. Omit guardrails to rename a group without touching what it holds. PUT also accepts the updated_at you read: if the group changed since, it is refused with 409 stale_group, and a duplicate name is 409 conflict. A group holds at most 100 guardrails. A failure is reported against the entry it belongs to, for example param: "guardrails[1].operation". Guardrails can also be managed one at a time:
Every configuration is validated — and every regular expression compiled — when it is written. A configuration the gateway cannot run is refused with 400 invalid_guardrail_config, naming the offending field, so no request is ever the first to find out. POST …/guardrails/{id}/test with {"text": "...", "hook": "llm_input"} (text up to 64 KB; hook defaults to llm_input) runs a stored guardrail over sample text and returns blocked, mutated, status, verdict, action, findings and — for a mutating guardrail — the rewritten text. Nothing is sent to a model and nothing is recorded.

Settings by type

categories limits detection to a subset (empty means all): aws_access_key, aws_secret_key, openai_api_key, anthropic_api_key, google_api_key, github_token, slack_token, jwt, bearer_token, oauth_token, refresh_token, private_key, rsa_private_key, ssh_private_key, pgp_private_key, database_connection_string, generic_api_key, password, high_entropy_secret. For key=value assignments only the value is redacted.
redaction is mask (one mask_char per character, keeping the shape) or placeholder ({category} expands to the upper-cased category, e.g. [REDACTED:CREDIT_CARD]). Names are detected from context cues (“my name is”, honorifics, “call …”). Aadhaar numbers are redacted when labelled (“Aadhaar”, “UID”) in any 4-4-4 form, or unlabelled when they pass the UIDAI format and Verhoeff checksum.
sensitivity is low (block at score 80), medium (50) or high (30); a threshold of 1–100 overrides it, and 0 uses the sensitivity. Categories: direct_injection, instruction_override, system_prompt_extraction, jailbreak, instruction_hierarchy, indirect_injection, obfuscation. Signals in tool results weigh more, since that is where indirect injection arrives.
Content blocks when its detected severity is at or above the category’s threshold (low, medium, high, critical). thresholds overrides severity_threshold per category.
Any finding at or above min_severity blocks. disabled_rules names rules to skip, such as python.eval or shell.chmod_777.
Each check can be turned on or off on its own. The older grouped keys block_destructive_statements (DROP, TRUNCATE, ALTER, GRANT, REVOKE) and block_delete_update_without_where are still accepted; a per-check key overrides its group. Defaults to validate at priority 1. In mutate mode comments are stripped; if anything blocking remains, the guardrail blocks rather than rewriting the SQL into something it cannot vouch for.
Presets: ssn, email, us_phone, india_aadhaar, india_pan, passports for India, US, UK, Germany, France, Netherlands, Canada, Australia, China and Japan (india_passport, us_passport, …), visa, mastercard, amex, discover, aws_access_key, aws_secret_key, github_token, slack_token, generic_api_key, ipv4, ipv6, url. Families expand to several: pii, passports, government_id, financial, credentials, network. Patterns use RE2 syntax — matching is linear-time, so there is no catastrophic backtracking — and patterns that are too complex, or that match the empty string, are refused.
Each rule has a name, a match of keywords or regex, an action of block or redact, and an optional enabled. A keywords rule takes keywords, plus case_sensitive (default false) and whole_word (default true); a regex rule takes a pattern in RE2 syntax. redaction_text on a rule overrides the guardrail-wide one. In validate mode (the default) any match blocks, even for a redact rule; redact rules take effect in mutate mode. Limits: at most 64 rules, 500 keywords per rule, 200 bytes per keyword, rule names up to 64 bytes of letters, digits, spaces, ., _ and -, and at least one enabled rule.

Observability

Every guardrail execution is recorded with the request id, organization, workspace, user, team, model, guardrail, type, hook, operation, priority, enforcement strategy, status, verdict, action, execution time, whether a mutation was applied, and its normalized findings. Execution records are kept for audit.retention_days (default 90).
  • In the console, Request Traces → Guardrail executions lists them; a single request’s trace shows its guardrail verdicts.
  • GET /admin/gateway/guardrail-executions?request_id=… returns one request’s guardrail trace in execution order. It also accepts guardrail_id, action, q, since, until, limit and offset, and requires gateway.audit.read.
  • In the console, click a guardrail in the registry to see its metrics: evaluations, how many it flagged, mutated and blocked, the latency it added, an over-time chart, and the people and API keys that tripped it. GET /admin/gateway/guardrail-groups/{id}/guardrails/{guardrailID}/metrics?since=…&until=… returns the same data. Flagged is a violation recorded but not enforced (audit mode); skipped runs are not counted as evaluations.
  • A guardrail execution structured log line is written per execution.
  • manylayers_guardrail_executions_total (labels guardrail_type, hook, status, action) and manylayers_guardrail_execution_seconds (guardrail_type, hook) are exported; see Metrics.
  • Executions that blocked, mutated or found something appear in the request’s audit row, and each hook is a span in exported traces.
Detected values are never recorded. A finding holds a category, a severity and a byte range — never the matched text. Content a guardrail flagged but did not remove (audit-mode findings, or a block by a secrets or pii guardrail) is left out of the audit row. Audit-mode redactions are applied to the stored copy. A prompt refused by any other guardrail type is kept so the block can be inspected in Request Traces; a blocked response is never kept.

Guardrail management API

Every route takes ?workspace_id=. Organization-wide resources require gateway.guardrails.manage across the Gateway product to write.

Gateway-wide checks that run before guardrails

Two older checks run on every request independently of guardrails, and guardrails see the request after both: A pii or prompt_injection guardrail adds per-workspace, per-rule control on top of these.