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.
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
| Package | Import path | Tier | What it is for |
|---|---|---|---|
| Guardrail policies | recohut_kit.guardrails | core | Application-configured policy primitives. Standard library only. Import the submodules explicitly |
| Redaction | recohut_kit.redaction | core (module) | Best-effort scrub and mask for text and JSON, plus require_safe and disclose |
| Revision loop | recohut_kit.revision_loop | supported | Bounded draft, review and revise workflow with exact single-match edits and a grounding audit. A deterministic workflow with seams for model steps |
| Disclosure | recohut_kit.disclosure | catalog | Outbound gate: payload detectors, purpose and destination policy, one-use human grants, receipts of counts and digests |
| Claims | recohut_kit.claims | catalog | Evidence-referenced claim ledger, verifier and a reply gate |
| Intake | recohut_kit.intake | catalog | Untrusted e-mail, PDF and image intake with quarantine marking of instruction-like spans |
| Governed SQL | recohut_kit.governed_sql | catalog | Table allowlist, row filters and column masks for read-only SQL |
| Constraints | recohut_kit.constraints | catalog | Hard-exclude and soft-rank candidate selection |
| Decision records | recohut_kit.adr | catalog | Architecture decision records as checkable repository contracts |
The submodules of recohut_kit.guardrails:
| Module | Main names | What it does |
|---|---|---|
guardrails.policy | ValidationPolicy, PatternClassifier, Threat, Decision, policy_hash | Length, empty, forbidden-pattern, language and topic checks; first-line threat patterns |
guardrails.screening | LexiconScreen, ClassifierScreen, intervene, ScreenResult | Term and classifier screens with spans, and the explicit intervention |
guardrails.masking | mask, MaskingReceipt | Placeholder, format-preserving or HMAC-token masking with counts |
guardrails.rate_limit | SlidingWindowLimiter, MemoryWindowStore, SQLiteWindowStore, RateReceipt | Sliding-window admission per key |
guardrails.substitution | SubstitutionPolicy, CompliantRetriever | Approved safe projections of source documents around governed retrieval |
guardrails.checklist | ResponsibleAIChecklist, ChecklistItem, Category | Evidence-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.
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) # cleanThe 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.
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.
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.
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 intentLimit request rates
The limiter takes a clock so tests can control time. MemoryWindowStore is the default; SQLiteWindowStore shares windows between processes on one host.
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) # TrueGate a release on a responsibility checklist
A checklist item counts as satisfied only when it has at least one non-blank evidence reference.
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:fairnessChoosing between owners
| You need to | Use |
|---|---|
| Reject malformed, oversized or forbidden input | guardrails.policy.ValidationPolicy |
| Spot injection-style phrasing with patterns you maintain | guardrails.policy.PatternClassifier |
| Flag business terms or categories and remove them | LexiconScreen with intervene |
| Flag with a model-scored classifier | ClassifierScreen with intervene |
| Replace emails and phone numbers with placeholders | redaction.mask_text, or guardrails.masking.mask when you want a receipt or tokenisation |
| Strip credentials from logs and JSON | redaction.scrub_text, redaction.scrub_json, redaction.redact |
| Refuse to execute a payload that contains recognised secrets | redaction.require_safe |
| Stop content leaving the process without review | disclosure.Gate with a DisclosurePolicy |
| Screen tool results inside a loop | agents_tools.screening.ResultScreen |
| Use a managed guardrail service on text | providers.bedrock_guardrails |
| Throttle callers | SlidingWindowLimiter 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.
disclosureenforces 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
ValidationPolicyrejects every input withinvalid_policy. An invalidPatternClassifierreturns theinvalid_policythreat. A missing language or topic label fails when an allowlist is active. interveneneeds an explicit action.substitutewithout a replacement string raisesValueError. There is no silent default.- Regexes are trusted configuration. Do not pass user-supplied expressions as
forbidden_patterns. - Rate limits are local.
MemoryWindowStoreis per process.SQLiteWindowStoreis 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