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()
| Helper | Effect |
|---|---|
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
| Group | Functions |
|---|---|
| Regular expressions | regex_match, regex_match_all, regex_replace, regex_find_all. |
| JSON | json_parse, json_stringify, json_schema_valid. |
| URLs | extract_urls, is_valid_url, all_urls_valid, get_url_domain. |
| Code | detect_code, detect_code_languages, contains_code_language. |
| Text | contains, contains_any, contains_all, word_count, char_count, lower, upper, trim. |
| HTTP | http_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
| Mode | What your function checks |
|---|---|
pre_call | The prompt, before the model sees it. A block means the model is never called. |
during_call | The prompt, while the model call runs beside it. |
post_call | The model's reply, before the caller gets it. |
pre_mcp_call | An MCP tool call, before the tool runs. |
during_mcp_call | An MCP tool call, while the tool runs. |
logging_only | The 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
-
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-idsas the Guardrail Name, keep Mode (can select multiple) atpre_call (Request), paste the function into Python Logic, open Test Your Guardrail, click Load example and change the text to one that holdsPT-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
200withsuccessfalse, the error text anderror_typeset tocompilation, and one that raises while running reportsexecution. Nothing is stored by this call. -
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-idsspanway_params:guardrail: custom_codemode: pre_callcustom_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_callto check model responses instead, for example to block replies that leak an id back. -
Attach it. Open Teams, pick the clinical team, click Edit, add
block-patient-idsunder 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"]}' -
Send a request with a team key that contains
PT-00012345. Expected result: a200with no model call and zero usage, whose reply is your reason and whosefinish_reasoniscontent_filter, and a row on the Logs page whose Guardrails & Policy Compliance section showsblock-patient-idsas blocked:{"choices": [{"index": 0, "finish_reason": "content_filter", "message": {"role": "assistant", "content": "Patient id detected"}}]}A
post_callguardrail that blocks a reply answers400instead, because the model already ran. The error carries your reason aserror, the guardrail name asguardrailand yourdetection_info. Attaching to a team needs an Enterprise license with theguardrailsfeature. Without one, use Default On or a policy attachment.
Errors
| Status | Where | Meaning | Fix |
|---|---|---|---|
200 with success: false, error_type: compilation | POST /guardrails/test_custom_code, Run Test | The 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: execution | POST /guardrails/test_custom_code, Run Test | The 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 reply | Any model request, pre_call or during_call | Your function returned block(reason) on the prompt. | This is the intended answer. Use flag instead of block to record without refusing. |
| 400 with your reason | Any model request, post_call | Your 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 request | The 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 Guardrail | The saved code does not compile. Nothing was stored. | Run the test first and fix what it reports. |
Please enter custom code | Save Guardrail | The editor is empty. | Paste the function. |
403 Admin access required to test custom code guardrails | POST /guardrails/test_custom_code | The key is not a proxy admin. | Use an admin key. |
403 Admin access required to manage guardrails | Create, update, delete | The key is not a proxy admin. | Use an admin key. |
http_post returns success: false with error Blocked URL: ... | Inside your function | The 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 function | The 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
| Level | Line | What it means | Action |
|---|---|---|---|
| ERROR | Custom code guardrail '<name>' exceeded its <n>s execution timeout | The function ran too long and the request failed. | Action needed. Make the check cheaper or raise timeout. |
| ERROR | Custom code guardrail '<name>' execution error: <error> | The function raised and the request failed. | Action needed. Fix the function. |
| WARNING | Custom 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. |
| WARNING | Custom 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. |
| WARNING | Custom 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. |
Related
- Guardrails for modes, attaching guardrails and the shared error list.
- Generic guardrail API when the check should live in a service you run instead of in a function on the gateway.
- Apply guardrail to run the saved guardrail on text.
- Guardrails page for every control of the editor and its templates.
- Security settings for the egress allowlist that outbound HTTP calls follow.