Sub topic 1
Why LLM Applications Need Guardrails
Prerequisites
Assume you know basic Python, regular expressions, JSON, prompts, and how an application calls an LLM through an API or SDK.
Why Guardrails Are Needed
A language model generates likely text. It does not automatically enforce your application's rules. A user can submit unsafe or irrelevant input, and a model can return leaked data, harmful content, invalid JSON, or an answer unsupported by your source material.
A guardrail is a check that limits or validates data around a model call. Guardrails reduce risk at known boundaries. They do not make the model reliable in every situation.
What Can Go Wrong
Inputs can contain:
- Excessively long text that increases cost or exceeds context limits.
- Personal data or secrets that should not reach the model.
- Prompt injection, where user content tries to override application instructions.
- Content your application is not designed to handle.
Outputs can contain:
- Empty, malformed, or incorrectly structured data.
- Private information or unsafe instructions.
- Claims that are not supported by retrieved documents.
- Text that violates business rules.
Where Checks Go
Place input checks before the model call. Reject, normalize, or redact the request before it enters the prompt. Place output checks after the model returns a response. Validate the result before displaying it, storing it, or sending it to another system.
Deterministic Checks
A deterministic check gives the same result for the same input. Length limits, regular expressions, and allowlists are useful because they are fast, cheap, and easy to test.
import re
EMAIL = re.compile(r"\b[\w.+-]+@[\w.-]+\.\w+\b")
ALLOWED_PRIORITIES = {"low", "medium", "high"}
def check_input(text: str) -> str:
if len(text) > 4000:
raise ValueError("input too long")
return EMAIL.sub("[EMAIL]", text)
def check_priority(priority: str) -> str:
if priority not in ALLOWED_PRIORITIES:
raise ValueError("unsupported priority")
return priority
print(check_input("Contact [email protected]"))
print(check_priority("high"))Use patterns for narrow, known formats. Use allowlists when the valid choices are finite. Regular expressions can miss unusual representations, so sensitive data usually needs additional controls and testing.
Exercise
Where should an application check whether a model response matches the required JSON structure?
Show answer
After the model call and before the response is used by the application.