Sub topic 11
What to do when a check fails
This chapter assumes you can write basic Python functions, know how to call an LLM through an SDK, and have read the earlier chapters on where checks sit around a model call and on deterministic checks. A guardrail that detects a problem is only half the work. The other half is deciding what the application does next.
The four basic responses
When a check fails, the application has four main options. Each fits a different kind of failure.
| Response | What it does | Good fit | Main risk |
|---|---|---|---|
| Block | Stops the request and returns a refusal or error | Clear policy violations, secrets in output | Frustrates legitimate users when the check is wrong |
| Redact | Removes or masks the offending part and continues | PII in input, small leaks in output | Redaction can miss variants, or break the meaning of the text |
| Retry | Calls the model again, often with feedback | Malformed or invalid structured output | Extra latency and cost, and repeated failure |
| Fall back | Returns a safe default, a cached answer, or a human handoff | Repeated failures, high-stakes requests | Lower quality, or a default that hides a real problem |
Pick the response from the kind of failure, not from habit. A malformed JSON object is a quality problem, so a retry is reasonable. A private key in the output is a security problem, so a retry is wrong: the next attempt may leak a different secret, and the first attempt has already shown the model can produce it.
Match the response to the failure
A useful rule is to ask two questions. First, is the failure likely to change if you ask again? Second, is it safe to show any part of the result?
- Format errors are random and fixable. Retry with the error message.
- Sensitive content in input can often be removed. Redact, then continue.
- Policy violations from the user are intentional or irrelevant to retrying. Block.
- Sensitive content in output is a leak. Block, and log it for review.
- Uncertain cases, such as a judge that gives a low confidence score, can go to a fallback or a human.
The following diagram shows this as a decision flow.
Blocking
Blocking is the simplest response and the safest. The wrapper from the placement chapter already does it:
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 answerNotice two design choices in this code. The input block tells the user the reason, because the user can act on it ("input too long"). The output block gives a generic message, because the reason ("secret in output") would tell an attacker what the check looks for. Decide for each check how much to reveal. The detailed reason belongs in your logs, not in the response.
Some blocks should also stop the session, not just one request. If a user triggers the injection check several times in a row, you may rate limit them or require review.
Redacting
Redaction keeps the request alive. It works best when the sensitive part is not needed to answer the question:
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]Edge cases to plan for:
- Missed variants. The SSN pattern misses "123 45 6789" and "123456789". Redaction reduces exposure but does not guarantee removal.
- Meaning changes. If the user asks "Is [email protected] a valid address format?", the placeholder makes the question unanswerable. Consider telling the user that you masked part of the input.
- Output redaction. Redacting model output is riskier than redacting input. A partial secret may still be useful to an attacker, and surrounding text may reveal the masked value. For secrets, block instead.
Retrying with feedback
Retry suits failures that are random, such as invalid JSON or a missing field. Pass the validation error back to the model so it can correct itself, and always set a limit:
import json
def parse_ticket(raw: str) -> dict:
data = json.loads(raw)
if not isinstance(data, dict):
raise ValueError("expected a JSON object")
if data.get("priority") not in ("low", "medium", "high"):
raise ValueError("priority must be low, medium or high")
if not isinstance(data.get("summary"), str) or not data["summary"]:
raise ValueError("summary must be a non-empty string")
return data
def get_ticket(prompt: str, call_model, max_attempts: int = 3) -> dict:
last_error = ""
for _ in range(max_attempts):
suffix = f"\nPrevious attempt failed: {last_error}" if last_error else ""
raw = call_model(prompt + suffix)
try:
return parse_ticket(raw)
except ValueError as err: # json.JSONDecodeError is a ValueError
last_error = str(err)
raise RuntimeError(f"No valid output after {max_attempts} attempts: {last_error}")Points to check in a retry design:
- Cap the attempts. Without
max_attempts, a persistent failure becomes an infinite loop that costs money on each pass. - Count the cost. Each retry repeats the full call. Three attempts can triple latency and token spend in the worst case.
- Do not retry unsafe output. Retrying a safety failure invites the model to try again until something passes. That turns your guardrail into a filter an attacker can probe.
- Be careful with feedback. The error message goes into the prompt. If it quotes the model's previous output, and that output contained untrusted text, you may feed injected content back in. Prefer short, fixed error messages like the ones in
parse_ticket. - Consider changing the call. If the first attempt failed, a lower temperature or a stricter structured-output mode on the second may help more than repeating the same request.
Falling back
A fallback is what the application does when it cannot produce a trustworthy answer. Options, from least to most disruptive:
- A cached or templated answer for common questions.
- A shorter, simpler answer from a more constrained prompt.
- A different model or provider, when the failure was a timeout or an API error.
- A human handoff, with the conversation attached.
- An honest error message that tells the user to try again later.
The RuntimeError in get_ticket is one kind of fallback signal. The caller decides what to do with it:
def handle_ticket_request(prompt: str, call_model) -> dict:
try:
return get_ticket(prompt, call_model)
except RuntimeError:
return {
"priority": "medium",
"summary": "Needs manual triage",
"needs_review": True,
}A default like this is acceptable only when the downstream system treats it correctly. Marking the record with needs_review keeps a failed extraction from looking like a successful one. A silent default is a common bug: the pipeline looks healthy while it fills a database with placeholder values.
Fail open or fail closed
A second decision concerns the guardrail itself failing, for example a moderation API that times out or a classifier that raises an exception. This is different from a check that ran and returned "not allowed".
- Fail closed: treat the failure as a block. Use this for high-risk checks such as secret detection or checks on actions with side effects.
- Fail open: let the request through and log the failure. Use this only where the harm is low and availability matters more, such as a quality check on a casual chat feature.
def safe_check(check, text: str, fail_closed: bool = True) -> GuardResult:
try:
return check(text)
except Exception as err:
reason = f"guardrail error: {type(err).__name__}"
return GuardResult(not fail_closed, reason)Choose the policy per check and write it down. An unspecified policy usually ends up as whatever the exception handler happens to do.
Messages to the user
A failure response is part of the product. Good messages:
- Say what happened in plain words, without exposing check internals.
- Offer a next step: rephrase, shorten the input, or contact support.
- Differ by cause. "Your message is too long" and "I can't help with that" are different situations.
Avoid messages that coach an attacker, such as "Blocked because the text contained 'ignore previous instructions'".
Record every decision
Whatever you choose, log the check name, the decision, and the action taken, without storing the raw sensitive text. Later chapters on evaluation and monitoring use these records to measure false positives and to find checks that fire too often or never.
Exercise
A model returns JSON where "priority" is "urgent", which is not an allowed value. A second check finds a string that looks like an API key in the same response. For each failure, state which response (block, redact, retry, fall back) you would use and why.
Show answer
Invalid priority: retry with the error message "priority must be low, medium or high", capped at a small number of attempts, because the failure is a random format error that a second try can fix. API key in the output: block, log the event, and return a generic message. Retrying is wrong because the model has shown it can leak a secret and another attempt may leak a different one. Redacting is weaker because partial or reformatted keys can slip through. If the retry limit for priority is exhausted, fall back to a marked default such as a needs_review record.
Exercise
A moderation API used by your input check times out. Should the request go through? What does your answer depend on?
Show answer
It depends on the risk of the feature. For a high-risk feature, such as one that can trigger actions or handle sensitive data, fail closed: block the request or show a "try again" message. For a low-risk feature where availability matters more, you may fail open and log the error. Either way, write the policy down, catch the exception explicitly, and record the failure so you can see how often it happens.