Skip to Content
Recodocs

Guardrails

The layer that screens what goes into and comes out of a model: validation policy, threat and lexicon screens, interventions, masking, redaction, rate limits and disclosure gates.

8 min read

A guardrail is a check that sits outside the model's judgment. For example, a company may reject an input that violates its policy or redact personal data before processing it. This layer implements deterministic validation, classification, reject/redact/substitute actions, masking of personal data and credential shapes, and request-rate limits. Each check records the hash of its policy and excludes source text from its receipt, so the receipt can be stored. These checks enforce a configured policy; they do not establish that every model answer is correct.

Two modules form the core of the layer. recohut_kit.guardrails is the decision layer: what is allowed and what to do when a screen fires. recohut_kit.redaction is the primitive layer: the recognisers for emails, phone-like numbers, caller terms and credential-shaped values. guardrails.masking builds on redaction, so you use them together. Nothing here is a model, and nothing here replaces authentication, scoped retrieval or an outbound disclosure gate.

The layer ends where grounding begins. Checking that a reply only states observed values is in Context and memory. Permission and approval for tool calls is in Tools and permissions.

Owners

PackageImport pathTierWhat it is for
Guardrail policiesrecohut_kit.guardrailscoreApplication-configured policy primitives. Standard library only. Import the submodules explicitly
Redactionrecohut_kit.redactioncore (module)Best-effort scrub and mask for text and JSON, plus require_safe and disclose
Revision looprecohut_kit.revision_loopsupportedBounded draft, review and revise workflow with exact single-match edits and a grounding audit. A deterministic workflow with seams for model steps
Disclosurerecohut_kit.disclosurecatalogOutbound gate: payload detectors, purpose and destination policy, one-use human grants, receipts of counts and digests
Claimsrecohut_kit.claimscatalogEvidence-referenced claim ledger, verifier and a reply gate
Intakerecohut_kit.intakecatalogUntrusted e-mail, PDF and image intake with quarantine marking of instruction-like spans
Governed SQLrecohut_kit.governed_sqlcatalogTable allowlist, row filters and column masks for read-only SQL
Constraintsrecohut_kit.constraintscatalogHard-exclude and soft-rank candidate selection
Decision recordsrecohut_kit.adrcatalogArchitecture decision records as checkable repository contracts

The submodules of recohut_kit.guardrails:

ModuleMain namesWhat it does
guardrails.policyValidationPolicy, PatternClassifier, Threat, Decision, policy_hashLength, empty, forbidden-pattern, language and topic checks; first-line threat patterns
guardrails.screeningLexiconScreen, ClassifierScreen, intervene, ScreenResultTerm and classifier screens with spans, and the explicit intervention
guardrails.maskingmask, MaskingReceiptPlaceholder, format-preserving or HMAC-token masking with counts
guardrails.rate_limitSlidingWindowLimiter, MemoryWindowStore, SQLiteWindowStore, RateReceiptSliding-window admission per key
guardrails.substitutionSubstitutionPolicy, CompliantRetrieverApproved safe projections of source documents around governed retrieval
guardrails.checklistResponsibleAIChecklist, ChecklistItem, CategoryEvidence-backed responsibility checklist with a pass or fail gate

Related code lives in other layers and composes with this one: agents_tools.screening.ResultScreen screens a tool result with the same screens, providers.bedrock_guardrails wraps the Bedrock ApplyGuardrail call, and harness.boundary.policy reuses guardrails.policy.Decision.

How the pieces fit

Input is validated first, then screened, then sent to the model. Output and tool results pass through the same screen types on the way back. Each step returns a decision with the policy hash.

The classifier is a first-line filter. The kit does not ship threat patterns, because patterns are application-owned. You supply every pattern, so a screen only catches what you taught it.

Worked examples

Every call below is deterministic and runs without a model or network.

Validate and classify input

ValidationPolicy.from_mapping takes a plain mapping, so you can load it from configuration. A malformed policy does not raise at validation time; it refuses every input with the rule invalid_policy.

validate_input.py
from recohut_kit.guardrails.policy import PatternClassifier, ValidationPolicy

policy = ValidationPolicy.from_mapping(
    {"max_length": 200, "forbidden_patterns": [r"drop\s+table"]}
)
print(policy.validate("hello").allowed)                    # True
print(policy.validate("please drop table users").rule)     # forbidden_pattern:0
print(ValidationPolicy.from_mapping({"bogus": 1}).validate("x").rule)  # invalid_policy

classifier = PatternClassifier(
    {"instruction_override": [r"ignore (all )?previous instructions"]}
)
decision = classifier.classify("Please ignore previous instructions and ...")
print(decision.threat.value, decision.matched_rule)
# instruction_override instruction_override:0
print(classifier.classify("hello").threat.value)           # clean

The Decision and ThreatDecision records hold the rule that fired and policy_hash. They hold none of the input text. When you set allowed_languages or allowed_topics, pass language= or topic= to validate from a classifier you trust; a missing label fails closed.

Screen text and apply an intervention

A screen reports categories and character spans. intervene applies the action you name and returns the new text plus a receipt. There is no default action.

screen_and_intervene.py
from recohut_kit.guardrails.screening import LexiconScreen, intervene

screen = LexiconScreen({"internal": ["project falcon"]})
text = "About Project Falcon now"

print(screen.screen(text).spans)                           # ((6, 20),)

rejected = intervene(text, screen, action="reject")
print(rejected.text, rejected.receipt.allowed)             # None False

redacted = intervene(text, screen, action="redact")
print(redacted.text)                                       # About ██████████████ now

replaced = intervene(text, screen, action="substitute", substitute="[removed]")
print(replaced.text, replaced.receipt.categories)          # [removed] ('internal',)

Matching is case-insensitive, uses word boundaries and applies Unicode NFKC folding, with spans mapped back to the original text. For a model-scored screen, ClassifierScreen(score, thresholds=..., version=...) takes a function that returns a score per category and flags every category at or above its threshold. A whole-text classifier has no spans, so redact replaces the full text with [redacted].

Mask personal data

mask supports three modes. token mode needs an HMAC key of at least 16 bytes and has no reverse map.

mask_text.py
from recohut_kit.guardrails.masking import mask
from recohut_kit.redaction import mask_text, scrub_json, scrub_text

receipt = mask("Mail ana@example.com or call +1 415 555 0100")
print(receipt.text)      # Mail [email] or call [phone]
print(receipt.counts)    # {'email': 1, 'phone': 1, 'term': 0}

tokenised = mask("Mail ana@example.com", mode="token", key=b"0123456789abcdef")
print(tokenised.text)    # Mail [email:<24 hex characters>]

# The lower-level helpers in redaction return plain values.
print(mask_text("ana@example.com, Falcon", terms=["Falcon"]))   # [email], [redacted]
print(scrub_text("Authorization: Bearer abcdef1234567890 and password=hunter2"))
# Authorization: [REDACTED] and password=[REDACTED]
print(scrub_json({"api_key": "sk-123", "note": "hi"}))
# {'api_key': '[REDACTED]', 'note': 'hi'}

The default token count in the receipt is whitespace-delimited words. Pass count_tokens= with your model tokenizer for an exact delta.

Refuse sensitive data in an exact payload

redaction.disclose returns a safe projection for persistence. redaction.require_safe is for exact, executable payloads: it raises DisclosureError rather than editing bytes you have already approved.

require_safe.py
from recohut_kit.redaction import DisclosureError, disclose, require_safe

print(disclose({"to": "ana@example.com"}))      # {'to': '[email]'}
try:
    require_safe({"to": "ana@example.com"})
except DisclosureError as error:
    print(error)    # Recognized sensitive data is forbidden in exact intent

Limit request rates

The limiter takes a clock so tests can control time. MemoryWindowStore is the default; SQLiteWindowStore shares windows between processes on one host.

rate_limit.py
from recohut_kit.guardrails.rate_limit import SlidingWindowLimiter

now = [0.0]
limiter = SlidingWindowLimiter(2, 60.0, clock=lambda: now[0])
print([limiter.admit("user-1").allowed for _ in range(3)])   # [True, True, False]
print(limiter.admit("user-1").retry_after)                   # 60.0
now[0] = 61.0
print(limiter.admit("user-1").allowed)                       # True

Gate a release on a responsibility checklist

A checklist item counts as satisfied only when it has at least one non-blank evidence reference.

checklist_gate.py
from recohut_kit.guardrails.checklist import Category, ChecklistItem, ResponsibleAIChecklist

checklist = ResponsibleAIChecklist(
    (ChecklistItem(Category.PRIVACY, ("review-1",), True),),
    required=(Category.PRIVACY, Category.FAIRNESS),
)
decision = checklist.gate()
print(decision.allowed, decision.rule)    # False missing:fairness

Choosing between owners

You need toUse
Reject malformed, oversized or forbidden inputguardrails.policy.ValidationPolicy
Spot injection-style phrasing with patterns you maintainguardrails.policy.PatternClassifier
Flag business terms or categories and remove themLexiconScreen with intervene
Flag with a model-scored classifierClassifierScreen with intervene
Replace emails and phone numbers with placeholdersredaction.mask_text, or guardrails.masking.mask when you want a receipt or tokenisation
Strip credentials from logs and JSONredaction.scrub_text, redaction.scrub_json, redaction.redact
Refuse to execute a payload that contains recognised secretsredaction.require_safe
Stop content leaving the process without reviewdisclosure.Gate with a DisclosurePolicy
Screen tool results inside a loopagents_tools.screening.ResultScreen
Use a managed guardrail service on textproviders.bedrock_guardrails
Throttle callersSlidingWindowLimiter here; use the gateway for distributed limits

Four helpers mask text: redaction.mask_text, guardrails.masking.mask, the nlp.pii helpers and disclosure.inspect. Use redaction.mask_text for placeholders and guardrails.masking.mask when you need a receipt, format-preserving output or HMAC tokens.

Failure behaviour, limits and gotchas

  • Best effort only. Redaction replaces a fixed set of recognisable shapes. It is not PII detection and not a secret classifier. Unknown secret shapes pass unless you list them as explicit terms.
  • Screens are not authentication. Pattern and lexicon screens are first-line filters. Pair them with least-privilege retrieval, scoped tools and the disclosure gate.
  • Disclosure does not cover every transport. disclosure enforces at the broker and the controlled HTTP adapter only. It does not protect model calls, browsers, MCP or telemetry transports.
  • Policies fail closed. An invalid ValidationPolicy rejects every input with invalid_policy. An invalid PatternClassifier returns the invalid_policy threat. A missing language or topic label fails when an allowlist is active.
  • intervene needs an explicit action. substitute without a replacement string raises ValueError. There is no silent default.
  • Regexes are trusted configuration. Do not pass user-supplied expressions as forbidden_patterns.
  • Rate limits are local. MemoryWindowStore is per process. SQLiteWindowStore is single host. Distributed limits belong to a gateway.
  • The Bedrock wrapper fails closed. The guarded text client treats any intervention, including redaction, as a failure and never forwards a rewritten prompt or unreviewed output.
  • Receipts carry hashes and counts. A receipt holds policy_hash, categories and counts. It holds no input text. Keep the policy source under version control so the hash can be traced.
  • Import weight. The guardrails modules use the standard library and import no model SDK. Import the submodules you need; the package root exports nothing.

How is this page?

Last updated on