Generative AI & LLM

Module 14 of 16

Module 14: Guardrails, Safety, and Alignment

3 min read559 words
What you'll learn
Map common LLM threat categories (injection, data exfil, toxic outputs)Apply layered defenses for prompts and toolsValidate and filter outputs before users see themIntegrate Guardrails AI or NeMo Guardrails-style policiesFollow a responsible deployment checklist

Duration: 4 hours | Difficulty: Intermediate–Advanced | Prerequisites: Modules 01–08

Learning Objectives

By the end of this module, you will be able to:

  • Map common LLM threat categories (injection, data exfil, toxic outputs)
  • Apply layered defenses for prompts and tools
  • Validate and filter outputs before users see them
  • Integrate Guardrails AI or NeMo Guardrails-style policies
  • Follow a responsible deployment checklist

1. The Threat Landscape

Why Safety Matters

Models optimize for plausible text, not safe outcomes. In prod, you own PII, brand, and legal risk—assume adversarial users and sloppy insiders.

RiskExample
Data leakModel echoes secrets from context
AbuseInstructions for harm
MisinformationConfident wrong medical/legal claims
AvailabilityPrompt bomb spikes cost

Try This! Write three “friendly” prompts that try to exfiltrate system instructions—see if your app blurs secrets.

2. Prompt Injection Attacks and Defenses

Types of Prompt Injection

StyleWhat attacker does
Direct“Ignore previous rules…”
IndirectPoisoned doc retrieved by RAG
Tool misuseArgs that hit forbidden APIs

Defense: Input Validation

LayerIdea
Length limitsCheap DoS brake
AllowlistsOnly expected languages/channels
Separate trusted system textDon’t concat untrusted docs into system

Defense: LLM-Based Injection Detection

Run a small classifier prompt (“is this trying to override policies?”) before the main call—treat as heuristic, not proof.

Concept: Defense in depth beats one magic filter.

3. Output Validation and Filtering

Key Example: Regex PII scan + simple issue list—extend with your DLP vendor patterns.

python
[object Object], re
,[object Object], dataclasses ,[object Object], dataclass

,[object Object],
,[object Object], ,[object Object],:
    patterns: ,[object Object],[,[object Object],, ,[object Object],]

    ,[object Object], ,[object Object],(,[object Object],):
        ,[object Object],._rx = {k: re.,[object Object],(v) ,[object Object], k, v ,[object Object], ,[object Object],.patterns.items()}

    ,[object Object], ,[object Object],(,[object Object],) -> ,[object Object],:
        hits = {name: rx.findall(text) ,[object Object], name, rx ,[object Object], ,[object Object],._rx.items() ,[object Object], rx.search(text)}
        ,[object Object], {,[object Object],: ,[object Object], hits, ,[object Object],: hits}


guard = OutputGuard(
    {
        ,[object Object],: ,[object Object],,
        ,[object Object],: ,[object Object],,
    }
)
sample = ,[object Object],
,[object Object],(guard.scan(sample))
Post-processWhen
Redact PIISupport transcripts
Block toxic phrasesConsumer apps
JSON schema validateTool pipelines

4. Guardrails AI

Declarative validators (ToxicLanguage, DetectPII, etc.) wrap outputs or prompts. Configure on_fail strategies: fix, reask, exception.

PlusMinus
Fast to prototypeAnother dependency + latency

Fun Fact: Validators can fight each other—e.g., PII redactor vs citation requirement—test combined configs.

5. NeMo Guardrails

YAML + Colang flows describe conversational policies: input rails, output rails, specialized dialog flows. Good when you want explicit policy files reviewed by compliance.

AssetRole
config.ymlModel endpoints
.co flowsAllowed / forbidden topics

6. Responsible AI Deployment Checklist

AreaSample items
InputRate limits, injection alerts, file type allowlist
OutputPII scan, moderation, citation rules for RAG
SystemSecret management, audit logs, kill switch
PeopleDisclosure, escalation path, red-team cadence

Key Takeaway

Safety is ongoing ops: logs, drills, and updates—not a checkbox before launch.

Practice Exercises

Exercise 1: Injection Red Team (Beginner)

10 prompts; document which defenses triggered.

Exercise 2: PII Shield (Intermediate)

Wire OutputGuard into FastAPI middleware.

Exercise 3: Content Moderation Pipeline (Intermediate)

Tier-1 regex, tier-2 LLM judge.

Exercise 4: Guardrails Integration (Advanced)

Guardrails AI + JSON schema for tool args.

Exercise 5: Adversarial Testing Suite (Advanced)

Mutation fuzzing on user prompts.

Mini-Project: Secure AI Chat Application

Chat UI + RAG + output guard + rate limit + admin view of blocked events (no PII stored raw).

Key Takeaways

Key Takeaway

  • Treat user content and retrieved docs as hostile by default.
  • Layer input and output controls; no single silver bullet.
  • Structured tool args shrink injection surface vs freeform code gen.
  • Policy-as-code (NeMo/Guardrails) helps compliance reviews.
  • Monitoring + runbooks complete the story—tech alone isn’t enough.

Resources for Further Learning

← Previous: Evaluation | Next: Production Deployment →