guardrail()

Decorator that turns a function into a composable guardrail.

Usage

Source

guardrail(
    func=None,
    *,
    name=None,
    phase=GuardPhase.BOTH,
    states=None,
)

Can be used as a bare decorator or with keyword arguments.

Parameters

func: Callable[[str], GuardResult] | None = None

The guard function (when used as bare @guardrail).

name: str | None = None

Override the guard’s display name (defaults to the function name).

phase: GuardPhase = GuardPhase.BOTH

When to run: "input", "output", or "both" (default).

states: list[str] | None = None
Optional list of pathway state names where this guard is active. When None (the default), the guard runs in all states. When set, the guard is skipped unless the current pathway state matches one of the listed names.

Returns

Guard
A configured guard instance.

Examples

Bare decorator:

@tb.guardrail
def no_profanity(text: str) -> tb.GuardResult:
    if any(w in text.lower() for w in BAD_WORDS):
        return tb.GuardResult.blocked("Profanity detected")
    return tb.GuardResult.passed()

With options:

@tb.guardrail(name="PII Filter", phase=GuardPhase.INPUT)
def strip_emails(text: str) -> tb.GuardResult:
    cleaned = re.sub(r'\S+@\S+', '[EMAIL]', text)
    if cleaned != text:
        return tb.GuardResult.rewrite(cleaned, reason="Stripped email addresses")
    return tb.GuardResult.passed()