Sub topic 11
What to do when a check fails
This chapter assumes you can write basic Python, call an LLM through an SDK, and read JSON. It also assumes you have seen the deterministic input and output checks from earlier chapters. A check that never fires is easy to build. The harder question is what your application does when a check does fire.
The four responses
When a guardrail rejects an input or an output, you have four main options.
| Response | What it does | Best for |
|---|---|---|
| Block | Stop the request and return a refusal | Injection attempts, secrets in output |
| Redact | Remove or mask the bad part and continue | PII in input, minor leaks in output |
| Retry | Call the model again, often with feedback | Malformed JSON, missing fields |
| Fall back | Return a safe default or hand off to a human | Repeated failures, high-stakes requests |
Choose by asking two questions. Can the problem be fixed without changing the user's meaning? And is another model call likely to produce something different? Redaction fits the first question. Retry fits the second.
Matching the response to the risk
Blocking is the safest choice but the most frustrating for users. Redaction keeps the request moving, but it only works when the unsafe part is separable. Replacing an email address with [EMAIL] leaves a usable prompt. Removing the core of an injection attempt does not, because you cannot be sure what else the text contains.
Retrying suits output that is wrong in a checkable way. It is a poor fit for policy violations, because a model that produced harmful text once may do so again. Every retry also adds latency and cost, so cap the number of attempts.
A retry with a fallback
The get_ticket function validates the model's JSON and retries with the error appended to the prompt. When attempts run out, it raises an exception. The caller can catch that exception and fall back.
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}")
def ticket_or_fallback(prompt: str, call_model) -> dict:
try:
return get_ticket(prompt, call_model)
except RuntimeError:
return {"priority": "medium", "summary": "Needs manual review"}The fallback ticket is a safe default. The request is still handled, and a person looks at it later.
How the decision flows
Common mistakes
- Leaking the reason. A message like "blocked: matched pattern X" teaches attackers what to avoid. Give users a generic message and keep details in your logs.
- Failing open. If a classifier times out and the request goes through unchecked, an attacker only has to cause timeouts. Decide deliberately whether each check fails closed (block) or open (allow). High-risk checks should fail closed.
- Silent redaction. If you change the user's text, record that you did. Otherwise you cannot explain odd answers later.
- Retrying the wrong failures. Retry format errors. Do not retry policy violations.
Exercise
A user's message contains a Social Security number, and the rest of the question is harmless. Your model call also returns JSON with an invalid priority value. Which response do you use for each failure, and why?
Show answer
Redact the Social Security number, because it is a separable part and the rest of the question stays usable. Retry the invalid JSON with the validation error appended, because the failure is checkable and a new call may fix it. Cap the retries and fall back to a safe default or human review if they run out.
Exercise
Your moderation classifier times out. Should the request proceed? Explain the trade-off.
Show answer
For a high-risk check, fail closed and block or fall back, since otherwise an attacker can trigger timeouts to skip the check. Failing open keeps the app available but weakens the guardrail. Choose per check, based on how harmful an unchecked request could be.