Check the output
Pass or fail in code
A guardrail returns a pair: True keeps the result, False sends back a short reason.
Instructions ask the model to behave. A guardrail is code that checks what came back.
Press Try it Yourself to run the check on a fixed sentence.
Example
import json
class Result:
raw = '{"status": "ok", "summary": "Order ORD-104 delivered."}'
def has_required_fields(output):
try:
data = json.loads(output.raw)
except json.JSONDecodeError:
return False, 'Not valid JSON'
if 'status' not in data or 'summary' not in data:
return False, 'Missing required keys'
return True, data
passed, value = has_required_fields(Result())
print('Passed:', passed)
print('Parsed:', value)Example explained
- json.loads(output.raw) — Checks machine-readable JSON validity before downstream code consumes the reply.
- has_required_fields — Returns (True, data) when required keys exist or (False, reason) to trigger a retry.
Ban a word
Add a second guardrail pattern: fail when a forbidden word appears.
Example
class Result:
raw = "Contact support for billing help."
def no_billing(output):
text = output.raw.lower()
if "refund" in text:
return (False, "Mention refund without policy")
return (True, output)
passed, value = no_billing(Result())
print("Passed:", passed)Example explained
- def no_billing — Defines `no_billing` used directly in the ban a word workflow.
Reference: documentation