Custom Script Guardrails
A custom script guardrail runs screening logic you write inside the gateway. Use it for an in-house classifier, a commercial product AISIX has no integration for, or a policy that combines several checks.
Remote guardrail integrations speak a specific provider's protocol. There is no industry standard for content-screening APIs, so reaching another service would otherwise require an adapter that translates between AISIX and that service. A custom script puts the translation inside the gateway.
Use a custom script only when a maintained guardrail does not already fit the service or policy. If matching by meaning is sufficient, use Semantic Screening Guardrails; otherwise, compare the available guardrails before maintaining a custom integration.
Start with one test model so a broken script cannot affect unrelated traffic. After the input path works, the same script contract can screen responses or rewrite content.
Prerequisites
Before starting, prepare the following:
- A test environment with a running gateway, a working Chat Completions model alias, and a caller API key.
- A screening service the gateway can reach. Because the script runs inside the gateway, the service can be on a private network.
- A shell with
curlfor sending verification requests. - For AISIX Enterprise or AISIX Cloud, permission to manage guardrails and policy attachments in the environment.
- For AISIX Enterprise or AISIX Cloud through the Admin API, a write-scoped admin token, the environment ID, the test-model ID, and
jq. - For AISIX OSS, a complete format-v2
resources.yamlfile that the gateway loads.
Export the gateway values used by the verification request:
# AISIX_PROXY has no trailing slash or endpoint path.
# The local quickstarts use http://127.0.0.1:3000.
export AISIX_PROXY="YOUR_AISIX_GATEWAY_URL"
export AISIX_API_KEY="YOUR_CALLER_API_KEY"
export AISIX_MODEL="YOUR_MODEL_ALIAS"
# Admin API examples encode this value; AISIX OSS injects it into the gateway process.
export SCREENING_SERVICE_KEY="YOUR_SCREENING_SERVICE_KEY"
Write a Script
A script is an ES module exporting checkInput, checkOutput, or both. A hook you do not export is skipped, so a script may cover one direction only. Replace the example URL, header name, and response fields with your screening service's contract.
export async function checkInput(ctx) {
const resp = await fetch("https://screening.internal/scan", {
method: "POST",
headers: {
"content-type": "application/json",
"x-api-key": ctx.secrets.SCAN_KEY,
},
body: JSON.stringify({ text: ctx.text }),
});
if (!resp.ok) {
throw new Error("screening service returned " + resp.status);
}
const body = await resp.json();
return body.outcome.deny
? { action: "block", reason_code: body.outcome.rule }
: { action: "none" };
}
Throwing, as this script does on a non-2xx response, hands the decision to the guardrail's failure policy rather than guessing. The default policy blocks a request that the script cannot screen.
What the Hook Receives
| Field | Description |
|---|---|
ctx.hook | "input" or "output". |
ctx.text | Every text slot joined, for a script that screens the request as a whole. |
ctx.segments | The text slots as an array. A rewriting script returns one replacement per slot. It can be empty on the output hook, as described below. |
ctx.messages | The slots as {role, text}. On /v1/chat/completions, /v1/responses, and /v1/messages, a custom guardrail runs on the segment pass, where every entry's role is "user" on both hooks, whatever role the text had in the request. Do not use role to tell system, assistant, or tool text apart. |
ctx.model | On the input hook of a model request, the caller-addressed alias. For a routing, semantic routing, or ensemble model, this is the group alias rather than the selected member or upstream model. It is absent on the output hook and on model-less requests such as MCP tool calls. |
ctx.secrets | The values configured on the guardrail, by name. |
The output hook can run even when the response contains no text, such as an image-only answer, empty stream, or empty transcript. In that case, ctx.segments is empty.
Check for an empty array before reading ctx.segments[0]. An unconditional block still refuses the response, monitor mode still records the verdict, and a thrown error follows the configured failure policy. If the upstream stream fails before producing any text, the script does not run.
What the Hook Returns
| Return value | Result |
|---|---|
{action: "none"} or {action: "allow"} | Allowed. |
{action: "block", reason_code, reason} | Refused. Both fields go to your gateway logs; neither reaches the caller. |
{action: "mask", segments} | Allowed with the text replaced. segments must have one entry per ctx.segments entry. An optional legacy counts object is accepted but ignored. |
Returning anything else — including nothing — is treated as a failure, not as an allow. A script that decided nothing must not read as a script that decided to permit.
What the Script Can Call
| API | Purpose |
|---|---|
fetch(url, init) | Call your service. Returns {status, ok, headers, text(), json()}. |
console.log/info/warn/error/debug | Write to your gateway's log. console.log and console.info write at info, so they need log_level: "info"; the others write at their own level. |
crypto.hmac(alg, key, data, outEncoding, keyEncoding) | HMAC-SHA1 or HMAC-SHA256, for a service that requires a signed request. |
crypto.hash(alg, data, outEncoding) | SHA-1 or SHA-256. |
crypto.base64Encode/base64Decode(data) | Base64. |
crypto.randomUUID() | A random UUID, for a nonce. |
aisix.embed(model, texts) | Embed text with an embedding model available in the same AISIX environment or resources-file configuration. |
crypto.hmac accepts and returns "hex" or "base64", and reads its key as "utf8", "hex", or "base64". Reading a key as hex is what lets you express a derivation chain, where each step's raw output keys the next:
let k = crypto.hmac("sha256", "AWS4" + ctx.secrets.SECRET, date, "hex");
k = crypto.hmac("sha256", k, region, "hex", "hex");
There is no file system, no environment access, and no timer. A failed fetch or an unsupported algorithm throws, so your script can decide what to do about it.
In AISIX Enterprise and AISIX Cloud, each aisix.embed call is recorded as a child of the screened request with internal_call_purpose set to guardrail_embedding. The call is billed at the price of the embedding model it names.
If the call is still in flight when the hook's timeout_ms expires, its child event records status 504 and error_class timeout. For pricing details, see Bill the Gateway's Internal Model Calls.
For complete scripts built on this interface, see Qwen3Guard Guardrails for a guard model you operate or TypeSafe Jev Guardrails for a hosted decision model.
Create a Custom Script Guardrail
The first policy screens requests sent to one test model. Keeping the initial attachment narrow lets you verify allow, block, and failure behavior before the script governs other traffic.
- AISIX Enterprise or Cloud
- AISIX OSS
- Dashboard
- Admin API
- In the Dashboard, select the environment and open Guardrails, then select New guardrail.
- Enter
in-house-screeningfor Name. Select Custom Script, Input only (pre-LLM), Whole request, and Block. - Under Scope, select Specified resources and select the alias you exported as
AISIX_MODEL.

- Under Script, paste the ES module from Write a Script.
- Under Credentials, select Add secret. Enter
SCAN_KEYfor Name and the screening-service credential for Value.

- Under Limits, set Timeout (ms) to
5000. Keep the request and response failure settings at their default blocking choices.

- Select Create guardrail. Confirm enabled status and 1 model, then check that the model detail names the selected alias before verifying traffic.

Export the control-plane connection details and the ID of the test model:
# AISIX_CP includes /api and has no trailing slash
# The local AISIX Enterprise quickstart uses http://localhost:8080/api
export AISIX_CP="YOUR_AISIX_CONTROL_PLANE_API_URL"
export AISIX_TOKEN="YOUR_ADMIN_TOKEN"
export ENV_ID="YOUR_ENVIRONMENT_ID"
export MODEL_ID="YOUR_TEST_MODEL_ID"
Create the guardrail disabled and capture its ID. Building the request with jq preserves the multi-line script and safely encodes the screening-service credential:
CUSTOM_SCRIPT=$(cat <<'EOF'
export async function checkInput(ctx) {
const resp = await fetch("https://screening.internal/scan", {
method: "POST",
headers: {
"content-type": "application/json",
"x-api-key": ctx.secrets.SCAN_KEY,
},
body: JSON.stringify({ text: ctx.text }),
});
if (!resp.ok) {
throw new Error("screening service returned " + resp.status);
}
const body = await resp.json();
return body.outcome.deny
? { action: "block", reason_code: body.outcome.rule }
: { action: "none" };
}
EOF
)
CUSTOM_PAYLOAD=$(
jq -n \
--arg script "$CUSTOM_SCRIPT" \
--arg scanKey "$SCREENING_SERVICE_KEY" \
'{
name: "in-house-screening",
enabled: false,
kind: "custom",
hook_point: "input",
fail_open: false,
config: {
script: $script,
secrets: {SCAN_KEY: $scanKey},
timeout_ms: 5000
}
}'
)
GUARDRAIL_RESPONSE=$(printf '%s\n' "$CUSTOM_PAYLOAD" | \
curl --fail-with-body -sS -X POST "$AISIX_CP/environments/$ENV_ID/guardrails" \
-H "Authorization: Bearer $AISIX_TOKEN" \
-H "Content-Type: application/json" \
--data-binary @-)
GUARDRAIL_ID=$(printf '%s\n' "$GUARDRAIL_RESPONSE" | jq -er '.guardrail.id')
The AISIX Cloud Admin API validates the script when the guardrail is created or updated. It encrypts secret values at rest and never returns them; read operations expose only the secret names.
Attach the guardrail to the test model, then enable it. The && prevents an attachment failure from enabling an unscoped guardrail:
curl --fail-with-body -sS -X POST "$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID/attachments" \
-H "Authorization: Bearer $AISIX_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"scope_type": "model",
"scope_id": "'"$MODEL_ID"'"
}' && \
curl --fail-with-body -sS -X PATCH "$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID" \
-H "Authorization: Bearer $AISIX_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"enabled": true
}'
Use this Admin API sequence when the guardrail must remain disabled until its attachment succeeds.
Add the following guardrail and model attachment to the gateway's resources file. Set scope_id to the UUID of the model entry addressed by AISIX_MODEL.
If guardrails or guardrail_attachments already exists, add the entry to the existing collection instead of creating a duplicate top-level key. The block scalar keeps the script readable, while environment interpolation keeps the screening-service credential out of the file.
guardrails:
- id: 10b1934a-dea0-4529-adb8-3862d32b403c
name: in-house-screening
enabled: true
kind: custom
hook_point: input
fail_open: false
script: |
export async function checkInput(ctx) {
const resp = await fetch("https://screening.internal/scan", {
method: "POST",
headers: {
"content-type": "application/json",
"x-api-key": ctx.secrets.SCAN_KEY,
},
body: JSON.stringify({ text: ctx.text }),
});
if (!resp.ok) {
throw new Error("screening service returned " + resp.status);
}
const body = await resp.json();
return body.outcome.deny
? { action: "block", reason_code: body.outcome.rule }
: { action: "none" };
}
secrets:
SCAN_KEY: ${SCREENING_SERVICE_KEY}
timeout_ms: 5000
guardrail_attachments:
- id: 28e18519-c37d-4f5b-9044-0606deca4622
guardrail_id: 10b1934a-dea0-4529-adb8-3862d32b403c
scope_type: model
scope_id: 7c239c0d-d4ea-48c6-9c2d-5713796cf775
priority: 100
The model attachment limits the guardrail to that alias. Without an attachment, the guardrail loads but inspects no traffic.
Validate the complete file in a short-lived container before applying it.
SCREENING_SERVICE_KEY is new to the gateway process, so a running container cannot inherit the host export. Validate from the directory containing resources.yaml before recreating the gateway.
The command below also passes the quickstart variables OPENAI_API_KEY and CALLER_API_KEY_SHA256. Replace or add -e entries so the validation container receives every environment variable referenced by your file:
docker run --rm \
-v "$(pwd):/etc/aisix:ro" \
-e OPENAI_API_KEY \
-e CALLER_API_KEY_SHA256 \
-e SCREENING_SERVICE_KEY \
--entrypoint /usr/local/bin/aisix \
ghcr.io/api7/aisix:1.13.0 \
validate --resources /etc/aisix/resources.yaml
aisix validate checks the resource shape and builds every enabled guardrail. It exits nonzero if the custom script cannot compile, so apply the file only after validation succeeds.
After validation, recreate the gateway as shown in Add New Environment Variables. Substitute ghcr.io/api7/aisix:1.13.0 for the image in that workflow as well.
Verify the Guardrail
Send a request your screening service refuses:
curl -i "$AISIX_PROXY/v1/chat/completions" \
-H "Authorization: Bearer $AISIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "'"$AISIX_MODEL"'",
"messages": [
{
"role": "user",
"content": "something your service denies"
}
]
}'
AISIX answers 422 with a content_filter error and never calls the upstream model. An unrelated request returns the model's answer as usual.
Debug a Script
AISIX has no dry-run tool for Custom Script guardrails. Keep the policy attached to one test model until its allow, block, and failure paths behave as intended.
- Send representative allowed and denied requests to the test alias.
- Make the screening service return an error or exceed the script timeout.
- Read the gateway logs and usage events. Output from the script's
consolefunctions appears in the gateway log alongside the resulting verdict. - Widen the attachment only after all three paths behave as intended.
Diagnose Save-Time Errors
- AISIX Enterprise or Cloud
- AISIX OSS
- Dashboard
- Admin API
The Dashboard compiles a script before saving it. A syntax error, excessive nesting, or parsing work that exceeds the validation limits leaves the previous policy unchanged and displays the error.

If the control plane is temporarily too busy to validate the script, wait a few seconds and save again. The failed attempt does not change the stored policy.
The Admin API compiles a script before creating or updating the guardrail. A syntax error, excessive nesting, or parsing work that exceeds the validation limits returns HTTP 400, and nothing is saved.
When validation capacity is temporarily unavailable, the API returns HTTP 503 with error.code set to SCRIPT_CHECK_BUSY and a Retry-After header. Resend the same request after that interval.
Run aisix validate against the complete resources file. Validation builds every enabled custom guardrail and exits nonzero if a script cannot compile, so do not reload the gateway until it passes.
Diagnose Runtime Failures
When a script fails after loading, the gateway log and the request's usage event identify the cause:
| Reason code | Cause |
|---|---|
custom_timeout | The script exceeded its execution budget. |
custom_script_error | The script threw an exception. |
custom_unknown_action | The returned action is unsupported. |
custom_no_verdict | The hook returned no decision or omitted action. |
custom_bad_verdict | The verdict has the wrong structure or type, or a mask returned missing or misaligned segments. |
custom_engine_error | AISIX could not start the script engine or install its host functions. |
The configured failure policy determines whether the request or response is blocked or bypasses screening. Test that policy explicitly before expanding the guardrail's scope.
Screen Model Responses
Add a separate output policy whose script exports checkOutput. The response hook receives the model's reply in the same shape as the request hook.
The Admin API and AISIX OSS also accept hook_point: both when one script and configuration should govern both directions. The Dashboard exposes one direction per Custom Script guardrail.
Window mode screens a streamed response in chunks and releases each chunk after it passes, which keeps the client responsive. Use buffer_full when the script must decide on the complete response before any content is released.
The Messages and Responses APIs cannot release streams by window. On those routes, AISIX holds the complete response and delivers it after screening in either mode. For the route-specific behavior, see Window Mode on Messages and Responses.
- AISIX Enterprise or Cloud
- AISIX OSS
- Dashboard
- Admin API
- On Guardrails, select New guardrail.
- Enter
in-house-response-screeningfor Name. Select Custom Script, Output only (post-LLM), Block, and the same test model under Specified resources.

- Paste a version of the service-calling script that exports
checkOutput. AddSCAN_KEYunder Credentials.

- Under Streaming output, select Window for Streaming mode. Keep If the output check cannot run at Block the response (safer).

- Select Create guardrail. Confirm enabled status, the output hook, and the selected test model.

- Send non-streaming requests that produce allowed and denied model responses. Confirm that a denied response returns
422before content reaches the caller.
To screen the complete response before releasing it, edit the output policy and select Buffer full instead. The window size and overlap controls are replaced by the buffer controls. Select Save changes if you choose this mode.

Build the output script by changing the exported hook name in the input script:
OUTPUT_SCRIPT=$(printf '%s\n' "$CUSTOM_SCRIPT" | sed 's/checkInput/checkOutput/')
Create the output policy disabled and capture its ID:
OUTPUT_PAYLOAD=$(
jq -n \
--arg script "$OUTPUT_SCRIPT" \
--arg scanKey "$SCREENING_SERVICE_KEY" \
'{
name: "in-house-response-screening",
enabled: false,
kind: "custom",
hook_point: "output",
fail_open: false,
config: {
script: $script,
secrets: {SCAN_KEY: $scanKey},
timeout_ms: 5000,
output_fail_open: false,
stream_processing_mode: "window"
}
}'
)
OUTPUT_RESPONSE=$(printf '%s\n' "$OUTPUT_PAYLOAD" | \
curl --fail-with-body -sS -X POST "$AISIX_CP/environments/$ENV_ID/guardrails" \
-H "Authorization: Bearer $AISIX_TOKEN" \
-H "Content-Type: application/json" \
--data-binary @-)
OUTPUT_GUARDRAIL_ID=$(printf '%s\n' "$OUTPUT_RESPONSE" | jq -er '.guardrail.id')
Attach the output policy to the test model, then enable it:
curl --fail-with-body -sS -X POST "$AISIX_CP/environments/$ENV_ID/guardrails/$OUTPUT_GUARDRAIL_ID/attachments" \
-H "Authorization: Bearer $AISIX_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"scope_type": "model",
"scope_id": "'"$MODEL_ID"'"
}' && \
curl --fail-with-body -sS -X PATCH "$AISIX_CP/environments/$ENV_ID/guardrails/$OUTPUT_GUARDRAIL_ID" \
-H "Authorization: Bearer $AISIX_TOKEN" \
-H "Content-Type: application/json" \
-d '{"enabled": true}'
Send non-streaming requests that produce allowed and denied model responses. The denied response returns 422 before content reaches the caller.
Add a second guardrail and attachment to the existing collections. Use the same service call as the input script, but export checkOutput:
guardrails:
- id: c35d0b03-6832-485a-8263-fb44adf34857
name: in-house-response-screening
enabled: true
kind: custom
hook_point: output
fail_open: false
script: |
export async function checkOutput(ctx) {
const resp = await fetch("https://screening.internal/scan", {
method: "POST",
headers: {
"content-type": "application/json",
"x-api-key": ctx.secrets.SCAN_KEY,
},
body: JSON.stringify({ text: ctx.text }),
});
if (!resp.ok) throw new Error("screening service returned " + resp.status);
const body = await resp.json();
return body.outcome.deny
? { action: "block", reason_code: body.outcome.rule }
: { action: "none" };
}
secrets:
SCAN_KEY: ${SCREENING_SERVICE_KEY}
timeout_ms: 5000
output_fail_open: false
stream_processing_mode: window
guardrail_attachments:
- id: d85e5e24-51d7-4cea-bce9-b27bc3dfe41e
guardrail_id: c35d0b03-6832-485a-8263-fb44adf34857
scope_type: model
scope_id: 7c239c0d-d4ea-48c6-9c2d-5713796cf775
priority: 100
Validate the complete file, recreate or reload the gateway as required, and send traffic that produces allowed and denied responses.
Understand Script Limits and Defaults
Each hook invocation has its own execution budget and memory ceiling. Request and response failures are controlled independently.
| Setting | Default | Description |
|---|---|---|
timeout_ms | 5000 | Wall-clock budget for one hook invocation, covering the script and every call it makes. The script API has no separate timer or per-fetch timeout. |
max_memory_bytes | 16777216 | Memory ceiling for the script. One response body may use a quarter of it, since the body is parsed inside the same memory. |
fail_open | false | Whether to allow a request that the script cannot screen. The default blocks the request. |
output_fail_open | false | Whether to release a response that the script cannot screen. The default blocks the response. |
The budget covers both a script stuck in a loop and a script waiting on a call that never answers. When the budget expires, the failure policy decides the verdict.
Each invocation runs in a fresh sandbox, so nothing a script stores survives to the next request. Screening state that has to persist belongs in your own service.
Configure Failure Behavior
Keep fail-closed behavior for security-critical policies. Choose fail-open behavior only when availability is more important than screening, and verify the bypass evidence in usage telemetry.
- AISIX Enterprise or Cloud
- AISIX OSS
- Dashboard
- Admin API
- On Guardrails, select Edit on the
in-house-screeningrow. Keep the service-calling script andSCAN_KEYin place while testing service failures. - Under Limits, set Timeout (ms) and Max memory (bytes) for the script's work.

- Choose Allow the request through for If the check cannot run only when availability should override screening, then select Save changes.

- On the output policy's row, select Edit. Configure If the output check cannot run independently, then select Save changes.

- Make the screening service return an error or exceed the timeout. Disable the other example policy before testing each one, then restore it afterward. Confirm the caller result and the bypass or block evidence in gateway logs and usage events.
- Restore the default blocking choices after the availability test unless bypassing is intentional.
The example below allows request traffic through when screening fails while keeping output failures closed. It repeats the non-secret settings that should survive; omitted secrets remain stored:
jq -n \
--arg script "$CUSTOM_SCRIPT" \
'{
fail_open: true,
config: {
script: $script,
timeout_ms: 5000,
max_memory_bytes: 16777216,
output_fail_open: false
}
}' | curl --fail-with-body -sS -X PATCH \
"$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID" \
-H "Authorization: Bearer $AISIX_TOKEN" \
-H "Content-Type: application/json" \
--data-binary @-
If you created the output policy, disable it before testing input fail-open behavior:
curl --fail-with-body -sS -X PATCH "$AISIX_CP/environments/$ENV_ID/guardrails/$OUTPUT_GUARDRAIL_ID" \
-H "Authorization: Bearer $AISIX_TOKEN" \
-H "Content-Type: application/json" \
-d '{"enabled": false}'
Make the screening service fail or exceed the timeout. The request is served because fail_open is true, and the bypass is recorded. Restore fail_open: false after the availability test unless bypassing is intentional. If you disabled the output policy, enable it again:
curl --fail-with-body -sS -X PATCH "$AISIX_CP/environments/$ENV_ID/guardrails/$OUTPUT_GUARDRAIL_ID" \
-H "Authorization: Bearer $AISIX_TOKEN" \
-H "Content-Type: application/json" \
-d '{"enabled": true}'
- Set
timeout_ms,max_memory_bytes,fail_open, and any output-streaming fields on the guardrail entry. - Disable the other example policy while testing this failure path.
- Validate the complete resources file, then recreate or reload the gateway.
- Make the screening service fail or exceed the timeout. Confirm the caller result and the bypass or block evidence in gateway logs.
- Restore the other policy and the intended failure settings after the test.
For shared hook, attachment, enforcement, and bypass behavior, see Guardrail Policy Behavior and Guardrail Failure Handling.
Rotate or Clear Secrets
Managed secret updates have three distinct outcomes: keep the stored set, replace the entire set, or clear it. Adding one secret is not additive.
- AISIX Enterprise or Cloud
- AISIX OSS
- Dashboard
- Admin API
- On Guardrails, select Edit on the
in-house-screeningrow. - Review the stored names under Credentials. Leaving the secret editor untouched keeps those credentials; values are never shown.

- To replace the stored set, select Add secret and enter every name/value pair the script still needs. A new
SCAN_KEYpair replaces the previous set with that one credential.

- To clear every stored credential instead, first update Script so it no longer reads those values. The masking example needs no service credential. Select Clear all and review the removal notice.

- Select Save changes and reopen Edit to verify the stored names. Test the screening service after a rotation, or verify the updated script's behavior after clearing its credentials.
Omit secrets from a PATCH to keep the stored set. To replace it, send every secret the script still needs and repeat the non-secret settings that should remain:
jq -n \
--arg script "$CUSTOM_SCRIPT" \
--arg scanKey "$SCREENING_SERVICE_KEY" \
'{
config: {
script: $script,
secrets: {SCAN_KEY: $scanKey},
timeout_ms: 5000
}
}' | curl --fail-with-body -sS -X PATCH \
"$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID" \
-H "Authorization: Bearer $AISIX_TOKEN" \
-H "Content-Type: application/json" \
--data-binary @-
Before removing the stored secrets, update CUSTOM_SCRIPT to a module that no longer reads them. The masking example shows a script that needs no service credential. Then send an empty map while retaining the updated script settings:
jq -n \
--arg script "$CUSTOM_SCRIPT" \
'{
config: {
script: $script,
secrets: {},
timeout_ms: 5000
}
}' | curl --fail-with-body -sS -X PATCH \
"$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID" \
-H "Authorization: Bearer $AISIX_TOKEN" \
-H "Content-Type: application/json" \
--data-binary @-
A Custom Script PATCH handles omitted fields as follows:
| PATCH input | Result |
|---|---|
Omit script, or send an empty script | Keeps the stored script. |
Omit secrets | Keeps the stored secret set. |
Send secrets: {} | Clears every stored secret. |
Omit output_fail_open | Keeps the stored response failure policy. |
| Omit another custom setting | Restores its default. Repeat any non-default timeout, memory, streaming, or buffer values that must survive. |
After rotating a credential, verify allowed, blocked, and screening-service-failure requests against the test model. After clearing the set, confirm that no secret names remain and verify the updated script's behavior. Read operations return secret names only.
Update SCREENING_SERVICE_KEY in the gateway process environment and recreate the gateway so it receives the new value. To remove the secret, remove the SCAN_KEY entry and update the script so it no longer reads ctx.secrets.SCAN_KEY; then validate the complete file and recreate the gateway.
Rewrite Content
A custom script can replace sensitive text instead of blocking the request. Return {action: "mask", segments} with one replacement per entry in ctx.segments:
export function checkInput(ctx) {
const masked = ctx.segments.map((s) => s.replace(/\d{3}-\d{2}-\d{4}/g, "<SSN>"));
const changed = masked.filter((s, i) => s !== ctx.segments[i]).length;
if (changed === 0) return { action: "none" };
return { action: "mask", segments: masked };
}
Apply the script through the interface that owns the guardrail:
- AISIX Enterprise or Cloud
- AISIX OSS
- Dashboard
- Admin API
- On Guardrails, select Edit on the
in-house-screeningrow. - Replace Script with the masking function above and keep the input hook.

- Select Save changes.
- Send a request containing
123-45-6789through a test upstream that echoes or captures the received prompt. Confirm that it receives<SSN>instead of the original value.
Store the masking script in a shell variable:
MASK_SCRIPT=$(cat <<'EOF'
export function checkInput(ctx) {
const masked = ctx.segments.map((s) => s.replace(/\d{3}-\d{2}-\d{4}/g, "<SSN>"));
const changed = masked.filter((s, i) => s !== ctx.segments[i]).length;
if (changed === 0) return { action: "none" };
return { action: "mask", segments: masked };
}
EOF
)
Update the script while preserving the example timeout. Omitting secrets keeps the stored set:
jq -n \
--arg script "$MASK_SCRIPT" \
'{config: {script: $script, timeout_ms: 5000}}' | \
curl --fail-with-body -sS -X PATCH \
"$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID" \
-H "Authorization: Bearer $AISIX_TOKEN" \
-H "Content-Type: application/json" \
--data-binary @-
Send a request containing 123-45-6789 through a test upstream that echoes or captures the received prompt. Confirm that it receives <SSN>.
Replace the guardrail's script block with the masking function above. Remove the unused SCAN_KEY secret, validate the complete resources file, and recreate or reload the gateway. Verify the rewrite with a test upstream that echoes or captures the received prompt.
The gateway derives masking telemetry from the returned segments. The usage-event name is always custom, and its value is the number of segments whose replacement differs from the original.
A script-provided counts object is accepted but ignored. Scripts cannot choose telemetry names or values because either could expose request content or ctx.secrets.
If AISIX cannot replace the original text with the returned segments, it blocks rather than releasing the unmodified content.
Remove the Guardrails
When testing is complete, remove the input policy and any optional output policy so they no longer inspect traffic.
- AISIX Enterprise or Cloud
- AISIX OSS
- Dashboard
- Admin API
- On Guardrails, select Delete on the
in-house-screeningrow and confirm Delete.

- If you created
in-house-response-screening, delete it separately and confirm the policy name before proceeding.

- Confirm that the removed policies no longer appear on the page.
Delete each guardrail you created. AISIX removes its attachments with it:
curl --fail-with-body -sS -X DELETE "$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID" \
-H "Authorization: Bearer $AISIX_TOKEN"
curl --fail-with-body -sS -X DELETE "$AISIX_CP/environments/$ENV_ID/guardrails/$OUTPUT_GUARDRAIL_ID" \
-H "Authorization: Bearer $AISIX_TOKEN"
Omit the second command if you did not create the output policy. A GET request for a deleted ID returns 404 Not Found.
Remove each example guardrail and its matching attachment from the complete resources file. Validate the file, recreate or reload the gateway, and confirm that the removed policies no longer affect test traffic.