Skip to main content

Custom code guardrails

A custom code guardrail is a check you write yourself as a small Python function, without deploying a separate service. The function receives the texts of the request or the response, decides to allow, block, flag or rewrite them, and runs inside a sandbox on the gateway with a fixed set of helper functions for regular expressions, JSON, URLs, code detection, text handling and HTTP calls. It is the right tool when the built-in guardrails do not cover a rule that is specific to your business, such as an internal id format, a list of project code names, or a check against a service only you run.

A real-world scenario​

A healthcare company issues patient ids in the form PT- followed by eight digits, and those ids must never reach an outside model. No off the shelf guardrail knows the format. An engineer writes a six line custom code guardrail that matches the pattern and blocks the request, tests it in the Admin UI against a sentence that contains an id, saves it, and attaches it to the clinical team. From then on a request with a patient id is refused with the message Patient id detected, and the attempt is visible on the Logs page.

Write the function​

The function is named apply_guardrail and receives inputs, request_data and input_type. inputs["texts"] holds the texts to check, inputs may also carry images, tools, tool_calls, structured_messages and model, request_data carries the request context such as the model, user and team, and input_type is request or response. The function returns one of the decision helpers.

def apply_guardrail(inputs, request_data, input_type):
for text in inputs["texts"]:
if regex_match(text, r"PT-\d{8}"):
return block("Patient id detected")
return allow()
HelperEffect
allow()Let the request or response through unchanged.
block(reason, detection_info=None)Refuse it with the reason.
modify(texts=None, images=None, tool_calls=None)Replace the texts, images or tool calls with rewritten versions. Anything left as None keeps the original.
flag(reason, metadata=None)Let it through and record the finding in the log.

Any other return value lets the content through. A function that returns something other than a dictionary, or a dictionary whose action is not allow, block, flag or modify (a typo such as blocked included), is treated as allow and logs a warning, so test the function before you rely on it.

The function can be async and call external services with await http_get(...), await http_post(...) or await http_request(method, url, ...) for GET, POST, PUT, DELETE and PATCH. Each returns a dictionary with success, status_code, body, headers and, when the call failed, error. A call waits 30 seconds by default and at most 60 seconds, set with timeout=.

async def apply_guardrail(inputs, request_data, input_type):
for text in inputs["texts"]:
response = await http_post("https://moderation.example.com/check", body={"text": text})
if response["success"] and response["body"].get("flagged"):
return block("Content flagged by moderation service")
return allow()

Available primitives​

GroupFunctions
Regular expressionsregex_match, regex_match_all, regex_replace, regex_find_all.
JSONjson_parse, json_stringify, json_schema_valid.
URLsextract_urls, is_valid_url, all_urls_valid, get_url_domain.
Codedetect_code, detect_code_languages, contains_code_language.
Textcontains, contains_any, contains_all, word_count, char_count, lower, upper, trim.
HTTPhttp_request, http_get, http_post.

The code runs with only these primitives and a restricted set of built-ins. It cannot import modules, read files or reach the gateway's internals, and its running time is bounded by the guardrail's timeout (30 seconds by default), so a slow function cannot stall requests. HTTP calls go through the gateway's outbound client with its timeouts and egress rules. Private, loopback, link-local and cloud metadata addresses are refused unless the host is listed in user_url_allowed_hosts, see the settings reference, so add an internal moderation service there before you call it. A refused call returns success: false with error Blocked URL: ....

Modes​

ModeWhat your function checks
pre_callThe prompt, before the model sees it. A block means the model is never called.
during_callThe prompt, while the model call runs beside it.
post_callThe model's reply, before the caller gets it.
pre_mcp_callAn MCP tool call, before the tool runs.
during_mcp_callAn MCP tool call, while the tool runs.
logging_onlyThe request and reply after the fact, for the logs only. It never blocks.

post_mcp_call is not supported and is refused when you save.

Create, test and attach it​

  1. Test the code before saving anything. In the Admin UI open Guardrails under AI Gateway, click Add New Guardrail, then Create Custom Code Guardrail. Enter block-patient-ids as the Guardrail Name, keep Mode (can select multiple) at pre_call (Request), paste the function into Python Logic, open Test Your Guardrail, click Load example and change the text to one that holds PT-00012345, then click Run Test. Over the API:

    curl -X POST http://localhost:4000/guardrails/test_custom_code \
    -H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \
    -d '{
    "custom_code": "def apply_guardrail(inputs, request_data, input_type):\n for text in inputs[\"texts\"]:\n if regex_match(text, r\"\\d{3}-\\d{2}-\\d{4}\"):\n return block(\"Social Security Number detected\")\n return allow()",
    "test_input": {"texts": ["My SSN is 123-45-6789"]},
    "input_type": "request"
    }'

    Expected result:

    {"success": true, "result": {"action": "block", "reason": "Social Security Number detected"}, "error": null, "error_type": null}

    A function that does not compile answers 200 with success false, the error text and error_type set to compilation, and one that raises while running reports execution. Nothing is stored by this call.

  2. Save the guardrail. Click Save Guardrail in the editor. Over the API, or in config.yaml:

    curl -X POST http://localhost:4000/guardrails \
    -H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \
    -d '{
    "guardrail": {
    "guardrail_name": "block-patient-ids",
    "spanway_params": {
    "guardrail": "custom_code",
    "mode": "pre_call",
    "custom_code": "def apply_guardrail(inputs, request_data, input_type):\n for text in inputs[\"texts\"]:\n if regex_match(text, r\"PT-\\d{8}\"):\n return block(\"Patient id detected\")\n return allow()"
    }
    }
    }'
    guardrails:
    - guardrail_name: block-patient-ids
    spanway_params:
    guardrail: custom_code
    mode: pre_call
    custom_code: |
    def apply_guardrail(inputs, request_data, input_type):
    for text in inputs["texts"]:
    if regex_match(text, r"PT-\d{8}"):
    return block("Patient id detected")
    return allow()

    Expected result: a row on the Guardrails page with the CustomCode provider. Its detail view shows the code with an Edit Code button for admins. Use mode: post_call to check model responses instead, for example to block replies that leak an id back.

  3. Attach it. Open Teams, pick the clinical team, click Edit, add block-patient-ids under Guardrails and save, or set Default On in the editor to run it for everyone. Over the API:

    curl -X POST http://localhost:4000/team/update \
    -H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \
    -d '{"team_id": "team-clinical", "guardrails": ["block-patient-ids"]}'
  4. Send a request with a team key that contains PT-00012345. Expected result: a 200 with no model call and zero usage, whose reply is your reason and whose finish_reason is content_filter, and a row on the Logs page whose Guardrails & Policy Compliance section shows block-patient-ids as blocked:

    {"choices": [{"index": 0, "finish_reason": "content_filter", "message": {"role": "assistant", "content": "Patient id detected"}}]}

    A post_call guardrail that blocks a reply answers 400 instead, because the model already ran. The error carries your reason as error, the guardrail name as guardrail and your detection_info. Attaching to a team needs an Enterprise license with the guardrails feature. Without one, use Default On or a policy attachment.

Errors​

StatusWhereMeaningFix
200 with success: false, error_type: compilationPOST /guardrails/test_custom_code, Run TestThe code does not parse, or uses a name the sandbox does not provide, for example an import. The message quotes the line.Fix the syntax, or replace the import with one of the primitives above.
200 with success: false, error_type: executionPOST /guardrails/test_custom_code, Run TestThe function raised while running, for example an index error, or ran past the test limit, Execution timeout: code took longer than 5 seconds. A test always stops after 5 seconds, whatever timeout the guardrail is saved with.Guard the data access, or make the check cheaper.
200 with finish_reason content_filter and your reason as the replyAny model request, pre_call or during_callYour function returned block(reason) on the prompt.This is the intended answer. Use flag instead of block to record without refusing.
400 with your reasonAny model request, post_callYour function blocked the reply.This is the intended answer.
500 Custom code guardrail '<name>' exceeded its <n>s execution timeout or Custom code guardrail execution failed: <error>Any model requestThe function ran past its timeout (30 seconds by default) or raised. The request fails.Fix the function, or raise timeout with PATCH /guardrails/{guardrail_id}.
422 Invalid guardrail configuration, update rejected: ...Edit Code, PUT and PATCH /guardrails/{guardrail_id}The edited code does not compile. The stored guardrail keeps running unchanged.Run the test first and fix what it reports.
400 Guardrail configuration error: ...POST /guardrails, Save GuardrailThe saved code does not compile. Nothing was stored.Run the test first and fix what it reports.
Please enter custom codeSave GuardrailThe editor is empty.Paste the function.
403 Admin access required to test custom code guardrailsPOST /guardrails/test_custom_codeThe key is not a proxy admin.Use an admin key.
403 Admin access required to manage guardrailsCreate, update, deleteThe key is not a proxy admin.Use an admin key.
http_post returns success: false with error Blocked URL: ...Inside your functionThe URL points at a private, loopback or metadata address.Add the host to user_url_allowed_hosts.
http_post returns success: false with Request timeout after <n>s or Request failed: ...Inside your functionThe service could not be reached, timed out, or the host is not on the gateway's egress allowlist.Check the URL, the service and general_settings.egress_allowlist. Decide in your code whether to allow or block when the service is down.

Audit​

Creating, editing and deleting the guardrail write audit rows on Spanway_GuardrailsTable with who made the change and the code and settings before and after. Run Test writes no row. See audit logs.

Logs​

LevelLineWhat it meansAction
ERRORCustom code guardrail '<name>' exceeded its <n>s execution timeoutThe function ran too long and the request failed.Action needed. Make the check cheaper or raise timeout.
ERRORCustom code guardrail '<name>' execution error: <error>The function raised and the request failed.Action needed. Fix the function.
WARNINGCustom code guardrail '<name>': Expected dict result, got <type>. Treating as allow.The function returned something that is not a decision, so the content went through.Action needed. Return one of the helpers.
WARNINGCustom code guardrail '<name>': Unknown action '<action>'. Treating as allow.The returned action is misspelled, so the content went through.Action needed. Use allow, block, flag or modify.
WARNINGCustom code http_request blocked: <reason> (also timeout and error)An HTTP call from the function was refused or failed.Check the URL and user_url_allowed_hosts.