Guardrails AIguardrails-ai 0.11.0 · Python 3.10+
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
27 small wins to finish your pathNext lesson

The first failure

Lesson 2's string passed. This lesson makes one fail, and what happens is not what the documentation leads you to expect.

Example
from guardrails import Guard
from guardrails_ai.valid_length import ValidLength

desk = Guard().use(ValidLength(min=1, max=40))

try:
    desk.validate("We can refund order 8821 in full, today, no questions asked.")
except Exception as error:
    print(type(error).__name__)
    print(error)

No boolean, no None. The Guard raised. If you had written that line without a try, as every quickstart does, your support desk would have stopped serving customers the first time a reply came back too long.

Why it raised

Every validator takes an on_fail argument that says what to do when the check does not pass. The how-to guide Use on_fail actions says, in a comment in its own example, that the parameter does not have to be set because the default is noop. In guardrails-ai 0.11.0 that is not true. Validator.__init__ in guardrails/validator_base.py reads if on_fail is None: on_fail = OnFailAction.EXCEPTION.

The library is what runs, so the library wins. Set on_fail on every validator you write, and never rely on the default.

Example
desk = Guard().use(ValidLength(min=1, max=40, on_fail="noop"))
outcome = desk.validate("We can refund order 8821 in full, today, no questions asked.")

print(outcome.validation_passed)
print(outcome.validated_output)

noop means notice it, write it down, and hand the value back unchanged. That is the quietest of the eight actions and the right one while you are still learning what your rules do to real traffic. Part 3 is the other seven.

Notice that validated_output holds the offending text. The Guard did not repair anything and did not withhold anything; it only disagreed.

Both spellings work: on_fail="noop" and on_fail=OnFailAction.NOOP, imported from guardrails. The string is matched case-insensitively against the enum member names. This course uses the strings because they are shorter, and lesson 9 prints the whole enum.
Try it yourself
  • Take the on_fail off again and wrap the call in try. That is the shape of every Guardrails program that has not been told about this.
  • Set on_fail="exception" explicitly and confirm you get exactly what the default gave you.
  • Pass on_fail="shout" and read the error. The list of names it prints is the subject of lesson 9.

Slow is fine. Stopping is the only problem.