Skip to main content
Version: 1.13.0

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 curl for 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.yaml file 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​

FieldDescription
ctx.hook"input" or "output".
ctx.textEvery text slot joined, for a script that screens the request as a whole.
ctx.segmentsThe 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.messagesThe 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.modelOn 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.secretsThe 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 valueResult
{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​

APIPurpose
fetch(url, init)Call your service. Returns {status, ok, headers, text(), json()}.
console.log/info/warn/error/debugWrite 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.

  1. In the Dashboard, select the environment and open Guardrails, then select New guardrail.
  2. Enter in-house-screening for Name. Select Custom Script, Input only (pre-LLM), Whole request, and Block.
  3. Under Scope, select Specified resources and select the alias you exported as AISIX_MODEL.
Guardrail scope with Specified resources selected and the docs-research-model checkbox outlined
  1. Under Script, paste the ES module from Write a Script.
  2. Under Credentials, select Add secret. Enter SCAN_KEY for Name and the screening-service credential for Value.
Input screening script and SCAN_KEY credential name outlined; the credential value is masked
  1. Under Limits, set Timeout (ms) to 5000. Keep the request and response failure settings at their default blocking choices.
Custom Script limits and failure settings with a 5000 millisecond timeout and Create guardrail outlined
  1. Select Create guardrail. Confirm enabled status and 1 model, then check that the model detail names the selected alias before verifying traffic.
Saved input policy with enabled status and one-model scope outlined; the model detail names test-model

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.

  1. Send representative allowed and denied requests to the test alias.
  2. Make the screening service return an error or exceed the script timeout.
  3. Read the gateway logs and usage events. Output from the script's console functions appears in the gateway log alongside the resulting verdict.
  4. Widen the attachment only after all three paths behave as intended.

Diagnose Save-Time Errors​

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.

Custom Script save rejected with a syntax error; the prior saved policy remains unchanged

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.

Diagnose Runtime Failures​

When a script fails after loading, the gateway log and the request's usage event identify the cause:

Reason codeCause
custom_timeoutThe script exceeded its execution budget.
custom_script_errorThe script threw an exception.
custom_unknown_actionThe returned action is unsupported.
custom_no_verdictThe hook returned no decision or omitted action.
custom_bad_verdictThe verdict has the wrong structure or type, or a mask returned missing or misaligned segments.
custom_engine_errorAISIX 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.

  1. On Guardrails, select New guardrail.
  2. Enter in-house-response-screening for Name. Select Custom Script, Output only (post-LLM), Block, and the same test model under Specified resources.
Guardrail scope with Specified resources selected and the docs-research-model checkbox outlined
  1. Paste a version of the service-calling script that exports checkOutput. Add SCAN_KEY under Credentials.
Response screening script with its output hook and masked service credential
  1. Under Streaming output, select Window for Streaming mode. Keep If the output check cannot run at Block the response (safer).
Window streaming controls with mode, window size, and overlap outlined
  1. Select Create guardrail. Confirm enabled status, the output hook, and the selected test model.
Guardrails list with the response policy enabled and scoped to the test model
  1. Send non-streaming requests that produce allowed and denied model responses. Confirm that a denied response returns 422 before 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.

Buffer full streaming mode with the complete-response buffer limit outlined

Understand Script Limits and Defaults​

Each hook invocation has its own execution budget and memory ceiling. Request and response failures are controlled independently.

SettingDefaultDescription
timeout_ms5000Wall-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_bytes16777216Memory ceiling for the script. One response body may use a quarter of it, since the body is parsed inside the same memory.
fail_openfalseWhether to allow a request that the script cannot screen. The default blocks the request.
output_fail_openfalseWhether 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.

  1. On Guardrails, select Edit on the in-house-screening row. Keep the service-calling script and SCAN_KEY in place while testing service failures.
  2. Under Limits, set Timeout (ms) and Max memory (bytes) for the script's work.
Custom Script timeout and memory controls outlined in the Limits panel
  1. Choose Allow the request through for If the check cannot run only when availability should override screening, then select Save changes.
Request failure setting with Allow the request through and Save changes outlined
  1. On the output policy's row, select Edit. Configure If the output check cannot run independently, then select Save changes.
Response failure control with Allow the response through selected and outlined
  1. 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.
  2. Restore the default blocking choices after the availability test unless bypassing is intentional.

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.

  1. On Guardrails, select Edit on the in-house-screening row.
  2. Review the stored names under Credentials. Leaving the secret editor untouched keeps those credentials; values are never shown.
Credentials panel showing stored SCAN_KEY and the Add secret and Clear all controls
  1. To replace the stored set, select Add secret and enter every name/value pair the script still needs. A new SCAN_KEY pair replaces the previous set with that one credential.
Credential replacement editor containing a complete SCAN_KEY name and masked value
  1. 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.
Credentials editor showing that saving will remove every stored credential
  1. 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.

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:

  1. On Guardrails, select Edit on the in-house-screening row.
  2. Replace Script with the masking function above and keep the input hook.
Custom Script editor containing the complete SSN masking function
  1. Select Save changes.
  2. Send a request containing 123-45-6789 through a test upstream that echoes or captures the received prompt. Confirm that it receives <SSN> instead of the original value.

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.

  1. On Guardrails, select Delete on the in-house-screening row and confirm Delete.
Delete confirmation naming in-house-screening with Delete outlined
  1. If you created in-house-response-screening, delete it separately and confirm the policy name before proceeding.
Delete confirmation naming in-house-response-screening with Delete outlined
  1. Confirm that the removed policies no longer appear on the page.