Sub topic 4
Deterministic checks: length, patterns and allowlists
Deterministic checks are rules that give the same verdict for the same input every time. They run in microseconds, cost nothing per call, and can be unit tested like any other function. This chapter covers the three most common kinds: length limits, pattern matching and allowlists. It also covers where each one fails.
This chapter assumes you can write Python functions, read basic regular expressions, and have already seen where input and output checkpoints sit around a model call.
Why start with rules
Rule-based checks are the cheapest layer of a guardrail stack. They catch the obvious problems before you pay for a classifier or a judge model. They also make decisions you can explain: "blocked because the input was 5,200 characters" is easy to audit.
Their weakness is that they only see what you thought of in advance. A rule matches strings, not meaning. Keep that in mind through the rest of the chapter.
| Property | Rule-based check | Model-based check |
|---|---|---|
| Latency | Microseconds | Tens to thousands of milliseconds |
| Cost per call | Effectively zero | Tokens or inference fees |
| Same input, same verdict | Always | Not guaranteed |
| Handles paraphrase | No | Often |
| Easy to explain | Yes | Harder |
Length limits
A length limit is the simplest guardrail. It protects against three problems:
- Cost: long inputs consume tokens, and you pay for them.
- Context overflow: input beyond the model's context window fails or gets truncated silently.
- Abuse: very long inputs can hide injected instructions or be used to inflate your bill.
Decide what you are counting. Characters are easy to count. Tokens are what the model and your bill actually use. A character limit is a fast first gate. If you need precision, count tokens with your provider's tokenizer.
Also limit outputs. Set a maximum output token count in the API call, and check output length afterwards, because a runaway or looping response is a real failure mode.
Pattern matching
Regular expressions detect text with a recognizable shape: email addresses, Social Security numbers, API keys, private key headers, phrases like "ignore previous instructions".
The next example is a minimal wrapper with an input check and an output check.
from dataclasses import dataclass
@dataclass
class GuardResult:
allowed: bool
reason: str = ""
def check_input(text: str) -> GuardResult:
if len(text) > 4000:
return GuardResult(False, "input too long")
if "ignore previous instructions" in text.lower():
return GuardResult(False, "possible prompt injection")
return GuardResult(True)
def check_output(text: str) -> GuardResult:
if not text.strip():
return GuardResult(False, "empty output")
if "BEGIN PRIVATE KEY" in text:
return GuardResult(False, "secret in output")
return GuardResult(True)
def guarded_call(prompt: str, call_model) -> str:
pre = check_input(prompt)
if not pre.allowed:
return f"Request blocked: {pre.reason}"
answer = call_model(prompt)
post = check_output(answer)
if not post.allowed:
return "Sorry, I can't provide that response."
return answercall_model is any function that takes a prompt string and returns a string. Each check returns a GuardResult with a reason, so callers and logs can say why a request was refused. The user sees a generic message on output failure, while the specific reason stays available for your logs.
Common pattern pitfalls
Patterns are easy to write and easy to get wrong. These are the errors you will meet most often.
- Case and spacing.
"ignore previous instructions"misses"Ignore previous instructions"with extra spaces. Lowercasing helps with case, but not with whitespace. Collapse whitespace first, or use a regex with\s+. - Unicode tricks. Look-alike characters, zero-width characters and full-width letters defeat plain string matching. Apply
unicodedata.normalize("NFKC", text)and strip zero-width characters before matching. - Missing word boundaries. A pattern for a number can match inside a longer number. Use
\bwhere it makes sense. - Catastrophic backtracking. Nested quantifiers such as
(a+)+$can take exponential time on crafted input. Your guardrail then becomes a denial-of-service target. Keep patterns simple, apply the length limit first, and avoid nested repetition. - Paraphrase. "Disregard everything you were told earlier" means the same thing and matches nothing. A phrase blocklist is a speed bump, not a defense.
A normalization step makes the earlier checks more reliable:
import re
import unicodedata
ZERO_WIDTH = re.compile(r"[\u200b\u200c\u200d\u2060\ufeff]")
INJECTION = re.compile(
r"\b(ignore|disregard|forget)\s+(all\s+)?(previous|prior|earlier)\s+instructions\b"
)
def normalize(text: str) -> str:
text = unicodedata.normalize("NFKC", text)
text = ZERO_WIDTH.sub("", text)
return re.sub(r"\s+", " ", text).strip().lower()
def looks_like_injection(text: str) -> bool:
return INJECTION.search(normalize(text)) is not None
print(looks_like_injection("Please IGNORE previous\u200b instructions")) # True
print(looks_like_injection("Summarize the previous instructions page")) # FalseThe second call shows the benefit of a structured pattern over a bare substring: it avoids matching unrelated text that merely contains similar words. It still cannot catch a rephrased attack.
Redaction as a pattern check
Patterns can also transform text instead of rejecting it. This guardrail replaces email addresses and US Social Security numbers with placeholders before the text reaches the model.
import re
EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
US_SSN = re.compile(r"\b\d{3}-\d{2}-\d{4}\b")
def redact_pii(text: str) -> str:
text = EMAIL.sub("[EMAIL]", text)
return US_SSN.sub("[SSN]", text)
print(redact_pii("Mail [email protected], SSN 123-45-6789"))
# Mail [EMAIL], SSN [SSN]Redaction lets the request continue, which is often better for the user than a block. It only covers formats you wrote a pattern for. Names, street addresses and SSNs written without dashes pass straight through. A later chapter covers personal data in more depth.
Allowlists
A blocklist says what is forbidden. An allowlist says what is permitted and rejects everything else. For narrow tasks, allowlists are stronger, because you do not have to predict every bad input. You only describe the good ones.
Use allowlists wherever the valid set is small and known:
- Enumerated values. A "category" field must be one of
billing,technical,other. - Tools. If the model can request a function call, only run functions on a fixed list.
- Domains. If the model returns or follows URLs, accept only your approved hosts.
- Formats. An order ID must match
^ORD-\d{8}$, nothing more.
from urllib.parse import urlparse
ALLOWED_TOOLS = {"search_docs", "get_order_status"}
ALLOWED_HOSTS = {"docs.example.com", "support.example.com"}
def tool_allowed(name: str) -> bool:
return name in ALLOWED_TOOLS
def url_allowed(url: str) -> bool:
parsed = urlparse(url)
return parsed.scheme == "https" and parsed.hostname in ALLOWED_HOSTS
print(tool_allowed("delete_account")) # False
print(url_allowed("https://docs.example.com/guide")) # True
print(url_allowed("https://docs.example.com.evil.io/")) # FalseThe last line shows why you compare the parsed hostname with exact set membership. A check like "docs.example.com" in url would accept the malicious address. Likewise, url.startswith("https://docs.example.com") accepts https://docs.example.com.evil.io/.
Choosing thresholds and responses
Every rule has a cost when it is wrong. A false positive blocks a legitimate user. A false negative lets a bad input through. Tight rules raise false positives, loose rules raise false negatives.
Practical guidance:
- Set length limits from real traffic. Look at the 99th percentile of legitimate inputs and leave headroom.
- Start new pattern rules in log-only mode. Record what they would have blocked, review it, then enforce.
- Prefer redaction over blocking when the unwanted text is a small part of a legitimate request.
- Return specific reasons internally and generic messages to users, so attackers learn little about your rules.
Limits of deterministic checks
Rules cannot judge meaning. They cannot tell whether an answer is true, polite, on topic or harmful when phrased in new words. They do not notice an injection written in another language or encoded as base64. Treat them as the first layer, which removes cheap and obvious problems and protects the later, costlier layers. The rest of the stack has to handle what the rules miss.
Exercise
A teammate writes if "docs.example.com" in url: to decide whether the model may fetch a link. Name one URL that passes this check but should not, and describe a safer check.
Show answer
https://docs.example.com.evil.io/ and https://evil.io/?ref=docs.example.com both contain the substring but point to other hosts. A safer check parses the URL, requires the https scheme, and tests that parsed.hostname is an exact member of a set of approved hosts.
Exercise
Your regex blocklist catches "ignore previous instructions" but a user submits "Ignore previous instructions" with two spaces, and then "Disregard earlier instructions". Which fixes are available for each case, and what does the second case show about blocklists?
Show answer
The extra-space case is fixed by normalizing whitespace (or using \s+) before matching. The second case needs the pattern extended with synonyms, but that only covers the phrasings you list. It shows that a phrase blocklist cannot cover paraphrase, so it must be combined with other layers.